code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.MapView;
import android.content.Context;
import android.util.AttributeSet;
public class GeoMapView extends MapView {
private OverlayManager mOverlayManager;
public GeoMapView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
//Log.d("GeoBeagle", "~~~~~~~~~~onLayout " + changed + ", " + left + ", " + top + ", "
// + right + ", " + bottom);
if (mOverlayManager != null) {
mOverlayManager.selectOverlay();
}
}
public void setScrollListener(OverlayManager overlayManager) {
mOverlayManager = overlayManager;
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheListPrecomputed;
import com.google.code.geobeagle.GraphicsGenerator;
import com.google.code.geobeagle.IToaster;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Toaster;
import com.google.code.geobeagle.Toaster.OneTimeToaster;
import com.google.code.geobeagle.actions.CacheFilterUpdater;
import com.google.code.geobeagle.actions.MenuActionCacheList;
import com.google.code.geobeagle.actions.MenuActionEditFilter;
import com.google.code.geobeagle.actions.MenuActionFilterListPopup;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection;
import com.google.code.geobeagle.activity.main.GeoUtils;
import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch;
import com.google.code.geobeagle.activity.map.OverlayManager.OverlaySelector;
import com.google.code.geobeagle.database.CachesProviderDb;
import com.google.code.geobeagle.database.CachesProviderLazyArea;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.PeggedCacheProvider;
import com.google.code.geobeagle.database.CachesProviderLazyArea.CoordinateManager;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class GeoMapActivity extends MapActivity {
public static Toaster.ToasterFactory peggedCacheProviderToasterFactory = new OneTimeToaster.OneTimeToasterFactory();
static class NullOverlay extends Overlay {
}
private static final int DEFAULT_ZOOM_LEVEL = 14;
private static boolean fZoomed = false;
private DbFrontend mDbFrontend;
private GeoMapActivityDelegate mGeoMapActivityDelegate;
private GeoMapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
private OverlayManager mOverlayManager;
@Override
protected boolean isRouteDisplayed() {
// This application doesn't use routes
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
// Set member variables first, in case anyone after this needs them.
mMapView = (GeoMapView)findViewById(R.id.mapview);
mDbFrontend = new DbFrontend(this, new GeocacheFactory());
//mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMyLocationOverlay = new FixedMyLocationOverlay(this, mMapView);
mMapView.setBuiltInZoomControls(true);
mMapView.setSatellite(false);
final Resources resources = getResources();
final Drawable defaultMarker = resources.getDrawable(R.drawable.pin_default);
final GraphicsGenerator graphicsGenerator = new GraphicsGenerator(
new GraphicsGenerator.RatingsGenerator(), null);
final CacheItemFactory cacheItemFactory = new CacheItemFactory(resources, graphicsGenerator, mDbFrontend);
final FilterTypeCollection filterTypeCollection = new FilterTypeCollection(this);
final List<Overlay> mapOverlays = mMapView.getOverlays();
final Intent intent = getIntent();
final MapController mapController = mMapView.getController();
final double latitude = intent.getFloatExtra("latitude", 0);
final double longitude = intent.getFloatExtra("longitude", 0);
final Overlay nullOverlay = new NullOverlay();
final GeoPoint nullGeoPoint = new GeoPoint(0, 0);
String geocacheId = intent.getStringExtra("geocacheId");
if (geocacheId != null) {
Geocache selected = mDbFrontend.loadCacheFromId(geocacheId);
cacheItemFactory.setSelectedGeocache(selected);
}
mapOverlays.add(nullOverlay);
mapOverlays.add(mMyLocationOverlay);
final List<DensityPatch> densityPatches = new ArrayList<DensityPatch>();
final Toaster toaster = new Toaster(this, R.string.too_many_caches, Toast.LENGTH_SHORT);
final CachesProviderDb cachesProviderArea = new CachesProviderDb(mDbFrontend);
final IToaster densityOverlayToaster = new OneTimeToaster(toaster);
final PeggedCacheProvider peggedCacheProvider = new PeggedCacheProvider(
peggedCacheProviderToasterFactory.getToaster(toaster));
final CoordinateManager coordinateManager = new CoordinateManager(1.0);
final CachesProviderLazyArea lazyArea = new CachesProviderLazyArea(
cachesProviderArea, peggedCacheProvider, coordinateManager);
final DensityOverlayDelegate densityOverlayDelegate = DensityOverlay.createDelegate(
densityPatches, nullGeoPoint, lazyArea, densityOverlayToaster);
final DensityOverlay densityOverlay = new DensityOverlay(densityOverlayDelegate);
final CachePinsOverlay cachePinsOverlay = new CachePinsOverlay(cacheItemFactory, this,
defaultMarker, GeocacheListPrecomputed.EMPTY);
//Pin overlay and Density overlay can't share providers because the provider wouldn't report hasChanged() when switching between them
CachesProviderDb cachesProviderAreaPins = new CachesProviderDb(mDbFrontend);
final CoordinateManager coordinateManagerPins = new CoordinateManager(1.0);
final CachesProviderLazyArea lazyAreaPins = new CachesProviderLazyArea(
cachesProviderAreaPins, peggedCacheProvider,
coordinateManagerPins);
final CachePinsOverlayFactory cachePinsOverlayFactory = new CachePinsOverlayFactory(
mMapView, this, defaultMarker, cacheItemFactory, cachePinsOverlay, lazyAreaPins);
final GeoPoint center = new GeoPoint((int)(latitude * GeoUtils.MILLION),
(int)(longitude * GeoUtils.MILLION));
mapController.setCenter(center);
final OverlaySelector overlaySelector = new OverlaySelector();
mOverlayManager = new OverlayManager(mMapView, mapOverlays,
densityOverlay, cachePinsOverlayFactory, false,
cachesProviderArea, filterTypeCollection, overlaySelector );
mMapView.setScrollListener(mOverlayManager);
// *** BUILD MENU ***
final MenuActions menuActions = new MenuActions();
menuActions.add(new GeoMapActivityDelegate.MenuActionToggleSatellite(mMapView));
menuActions.add(new GeoMapActivityDelegate.MenuActionCenterLocation(resources, mapController, mMyLocationOverlay));
menuActions.add(new MenuActionCacheList(this, resources));
final List<CachesProviderDb> providers = new ArrayList<CachesProviderDb>();
providers.add(cachesProviderArea);
providers.add(cachesProviderAreaPins);
final CacheFilterUpdater cacheFilterUpdater =
new CacheFilterUpdater(filterTypeCollection, providers);
menuActions.add(new MenuActionEditFilter(this, cacheFilterUpdater,
mOverlayManager, filterTypeCollection, resources));
menuActions.add(new MenuActionFilterListPopup(this, cacheFilterUpdater,
mOverlayManager, filterTypeCollection, resources));
mGeoMapActivityDelegate = new GeoMapActivityDelegate(menuActions);
if (!fZoomed) {
mapController.setZoom(DEFAULT_ZOOM_LEVEL);
fZoomed = true;
}
mOverlayManager.selectOverlay();
}
public OverlayManager getOverlayManager() {
return mOverlayManager;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return mGeoMapActivityDelegate.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return mGeoMapActivityDelegate.onMenuOpened(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mGeoMapActivityDelegate.onOptionsItemSelected(item);
}
@Override
public void onPause() {
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
mDbFrontend.closeDatabase();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
mOverlayManager.forceRefresh(); //The cache filter might have changed
mMyLocationOverlay.enableMyLocation();
mMyLocationOverlay.enableCompass();
mDbFrontend.openDatabase();
}
}
| Java |
//http://www.spectrekking.com/download/FixedMyLocationOverlay.java
package com.google.code.geobeagle.activity.map;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.location.Location;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.R;
public class FixedMyLocationOverlay extends MyLocationOverlay {
private boolean bugged = false;
private Paint accuracyPaint;
private Point center;
private Point left;
private Drawable drawable;
private int width;
private int height;
public FixedMyLocationOverlay(Context context, MapView mapView) {
super(context, mapView);
}
@Override
protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLoc,
long when) {
if (!bugged) {
try {
super.drawMyLocation(canvas, mapView, lastFix, myLoc, when);
} catch (Exception e) {
bugged = true;
}
}
if (bugged) {
if (drawable == null) {
accuracyPaint = new Paint();
accuracyPaint.setAntiAlias(true);
accuracyPaint.setStrokeWidth(2.0f);
drawable = mapView.getContext().getResources().getDrawable(R.drawable.mylocation);
width = drawable.getIntrinsicWidth();
height = drawable.getIntrinsicHeight();
center = new Point();
left = new Point();
}
Projection projection = mapView.getProjection();
double latitude = lastFix.getLatitude();
double longitude = lastFix.getLongitude();
float accuracy = lastFix.getAccuracy();
float[] result = new float[1];
Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result);
float longitudeLineDistance = result[0];
GeoPoint leftGeo = new GeoPoint((int)(latitude * 1e6), (int)((longitude - accuracy
/ longitudeLineDistance) * 1e6));
projection.toPixels(leftGeo, left);
projection.toPixels(myLoc, center);
int radius = center.x - left.x;
accuracyPaint.setColor(0xff6666ff);
accuracyPaint.setStyle(Style.STROKE);
canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
accuracyPaint.setColor(0x186666ff);
accuracyPaint.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
drawable.setBounds(center.x - width / 2, center.y - height / 2, center.x + width / 2,
center.y + height / 2);
drawable.draw(canvas);
}
}
}
| Java |
/*
** 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.code.geobeagle.activity;
public enum ActivityType {
// These constants are persisted to the database. They are also used as
// indices in ActivityRestorer.
CACHE_LIST(1), NONE(0), SEARCH_ONLINE(2), VIEW_CACHE(3);
private final int mIx;
ActivityType(int i) {
mIx = i;
}
int toInt() {
return mIx;
}
}
| Java |
/*
** 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.code.geobeagle.activity;
import android.content.Context;
public class ActivityDI {
public static class ActivityTypeFactory {
private final ActivityType mActivityTypes[] = new ActivityType[ActivityType.values().length];
public ActivityTypeFactory() {
for (ActivityType activityType : ActivityType.values())
mActivityTypes[activityType.toInt()] = activityType;
}
public ActivityType fromInt(int i) {
return mActivityTypes[i];
}
}
public static ActivitySaver createActivitySaver(Context context) {
return new ActivitySaver(context.getSharedPreferences("GeoBeagle", Context.MODE_PRIVATE)
.edit());
}
}
| Java |
package com.google.code.geobeagle.activity.filterlist;
import com.google.code.geobeagle.activity.filterlist.FilterListActivityDelegate;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
/**
* A list of the pre-made filters which the user can choose between by tapping a list item
*
*/
public class FilterListActivity extends ListActivity {
private FilterListActivityDelegate mFiltersActivityDelegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.d("GeoBeagle", "CacheListActivity onCreate");
mFiltersActivityDelegate = new FilterListActivityDelegate();
//CacheListDelegateDI.create(this, getLayoutInflater());
mFiltersActivityDelegate.onCreate(this);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mFiltersActivityDelegate.onListItemClick(l, v, position, id);
}
}
| Java |
/*
** 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.code.geobeagle.activity.main;
import java.text.DateFormat;
import java.util.Date;
public class DateFormatter {
private static DateFormat mDateFormat;
public DateFormatter(DateFormat dateFormat) {
mDateFormat = dateFormat;
}
public String format(Date date) {
return mDateFormat.format(date);
}
} | Java |
/*
** 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.code.geobeagle.activity.main;
import android.net.Uri;
public class UriParser {
public Uri parse(String uriString) {
return Uri.parse(uriString);
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckButton;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckButtons;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckDetailsButton;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckWebPageButton;
import com.google.code.geobeagle.cachedetails.CacheDetailsLoader;
import com.google.code.geobeagle.cachedetails.CacheDetailsLoader.DetailsOpener;
import android.app.AlertDialog.Builder;
import android.view.LayoutInflater;
import android.view.View;
public class Misc {
public static CacheDetailsOnClickListener createCacheDetailsOnClickListener(
GeoBeagle geoBeagle, Builder alertDialogBuilder, LayoutInflater layoutInflater) {
final DetailsOpener detailsOpener = new DetailsOpener(geoBeagle);
final CacheDetailsLoader cacheDetailsLoader = new CacheDetailsLoader(detailsOpener);
return new CacheDetailsOnClickListener(geoBeagle, alertDialogBuilder, layoutInflater,
cacheDetailsLoader);
}
public static WebPageAndDetailsButtonEnabler create(GeoBeagle geoBeagle, View webPageButton,
View detailsButton) {
final CheckWebPageButton checkWebPageButton = new CheckWebPageButton(webPageButton);
final CheckDetailsButton checkDetailsButton = new CheckDetailsButton(detailsButton);
final CheckButtons checkButtons = new CheckButtons(new CheckButton[] {
checkWebPageButton, checkDetailsButton
});
return new WebPageAndDetailsButtonEnabler(geoBeagle, checkButtons);
}
}
| Java |
/*
** 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.code.geobeagle.activity.main;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.ErrorDisplayerDi;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GraphicsGenerator;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.R.id;
import com.google.code.geobeagle.actions.MenuActionSettings;
import com.google.code.geobeagle.actions.CacheActionEdit;
import com.google.code.geobeagle.actions.CacheActionMap;
import com.google.code.geobeagle.actions.CacheActionRadar;
import com.google.code.geobeagle.actions.CacheActionViewUri;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.actions.MenuActionCacheList;
import com.google.code.geobeagle.actions.CacheActionGoogleMaps;
import com.google.code.geobeagle.actions.MenuActionFromCacheAction;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.ActivityDI;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.main.fieldnotes.CacheLogger;
import com.google.code.geobeagle.activity.main.DateFormatter;
import com.google.code.geobeagle.activity.main.fieldnotes.DialogHelperCommon;
import com.google.code.geobeagle.activity.main.fieldnotes.DialogHelperFile;
import com.google.code.geobeagle.activity.main.fieldnotes.DialogHelperSms;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldnoteLogger;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldnoteStringsFVsDnf;
import com.google.code.geobeagle.activity.main.fieldnotes.FileLogger;
import com.google.code.geobeagle.activity.main.fieldnotes.SmsLogger;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldnoteLogger.OnClickCancel;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldnoteLogger.OnClickOk;import com.google.code.geobeagle.activity.main.GeoBeagleDelegate.LogFindClickListener;
import com.google.code.geobeagle.activity.main.GeoBeagleDelegate.OptionsMenu;
import com.google.code.geobeagle.activity.main.intents.GeocacheToCachePage;
import com.google.code.geobeagle.activity.main.intents.GeocacheToGoogleMap;
import com.google.code.geobeagle.activity.main.intents.IntentFactory;
import com.google.code.geobeagle.activity.main.view.CacheButtonOnClickListener;
import com.google.code.geobeagle.activity.main.view.CacheDetailsOnClickListener;
import com.google.code.geobeagle.activity.main.view.FavoriteView;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer;
import com.google.code.geobeagle.activity.main.view.Misc;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.AttributeViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.UnlabelledAttributeViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.LabelledAttributeViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.NameViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.ResourceImages;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.Toaster;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO: Rename to CompassActivity
/*
* Main Activity for GeoBeagle.
*/
public class GeoBeagle extends Activity {
private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm'Z'");
private GeoBeagleDelegate mGeoBeagleDelegate;
private DbFrontend mDbFrontend;
private FieldnoteLogger mFieldNoteSender;
private OptionsMenu mOptionsMenu;
private static final DateFormat mLocalDateFormat = DateFormat
.getTimeInstance(DateFormat.MEDIUM);
private GeocacheFactory mGeocacheFactory;
public Geocache getGeocache() {
return mGeoBeagleDelegate.getGeocache();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("GeoBeagle", "GeoBeagle.onActivityResult");
mGeocacheFactory.flushCache();
if (requestCode == GeoBeagleDelegate.ACTIVITY_REQUEST_TAKE_PICTURE) {
Log.d("GeoBeagle", "camera intent has returned.");
} else if (resultCode == 0)
setIntent(data);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("GeoBeagle", "GeoBeagle onCreate");
setContentView(R.layout.main);
final ErrorDisplayer errorDisplayer = ErrorDisplayerDi.createErrorDisplayer(this);
final WebPageAndDetailsButtonEnabler webPageButtonEnabler = Misc.create(this,
findViewById(R.id.cache_page), findViewById(R.id.cache_details));
final GeoFixProvider geoFixProvider = LocationControlDi.create(this);
mGeocacheFactory = new GeocacheFactory();
final TextView gcid = (TextView)findViewById(R.id.gcid);
final GraphicsGenerator graphicsGenerator = new GraphicsGenerator(
new GraphicsGenerator.RatingsGenerator(), null);
final Resources resources = this.getResources();
final Drawable[] pawDrawables = {
resources.getDrawable(R.drawable.paw_unselected_dark),
resources.getDrawable(R.drawable.paw_half_light),
resources.getDrawable(R.drawable.paw_selected_light)
};
final Drawable[] pawImages = graphicsGenerator.getRatings(pawDrawables, 10);
final Drawable[] ribbonDrawables = {
resources.getDrawable(R.drawable.ribbon_unselected_dark),
resources.getDrawable(R.drawable.ribbon_half_bright),
resources.getDrawable(R.drawable.ribbon_selected_bright)
};
final Drawable[] ribbonImages = graphicsGenerator.getRatings(ribbonDrawables, 10);
final ImageView difficultyImageView = (ImageView)findViewById(R.id.gc_difficulty);
final TextView terrainTextView = (TextView)findViewById(R.id.gc_text_terrain);
final ImageView terrainImageView = (ImageView)findViewById(R.id.gc_terrain);
final TextView difficultyTextView = (TextView)findViewById(R.id.gc_text_difficulty);
final ImageView containerImageView = (ImageView)findViewById(R.id.gccontainer);
final UnlabelledAttributeViewer ribbonImagesOnDifficulty = new UnlabelledAttributeViewer(
difficultyImageView, ribbonImages);
final AttributeViewer gcDifficulty = new LabelledAttributeViewer(
difficultyTextView, ribbonImagesOnDifficulty);
final UnlabelledAttributeViewer pawImagesOnTerrain = new UnlabelledAttributeViewer(
terrainImageView, pawImages);
final AttributeViewer gcTerrain = new LabelledAttributeViewer(terrainTextView,
pawImagesOnTerrain);
final ResourceImages containerImagesOnContainer = new ResourceImages(
containerImageView, GeocacheViewer.CONTAINER_IMAGES);
final NameViewer gcName = new NameViewer(
((TextView)findViewById(R.id.gcname)));
RadarView radar = (RadarView)findViewById(R.id.radarview);
radar.setUseImperial(false);
radar.setDistanceView((TextView)findViewById(R.id.radar_distance),
(TextView)findViewById(R.id.radar_bearing),
(TextView)findViewById(R.id.radar_accuracy),
(TextView)findViewById(R.id.radar_lag));
FavoriteView favorite = (FavoriteView) findViewById(R.id.gcfavorite);
final GeocacheViewer geocacheViewer = new GeocacheViewer(radar, gcid, gcName,
(ImageView)findViewById(R.id.gcicon),
gcDifficulty, gcTerrain, containerImagesOnContainer/*, favorite*/);
//geoFixProvider.onLocationChanged(null);
GeoBeagleDelegate.RadarViewRefresher radarViewRefresher =
new GeoBeagleDelegate.RadarViewRefresher(radar, geoFixProvider);
geoFixProvider.addObserver(radarViewRefresher);
final IntentFactory intentFactory = new IntentFactory(new UriParser());
final CacheActionViewUri intentStarterViewUri = new CacheActionViewUri(this,
intentFactory, new GeocacheToGoogleMap(this), resources);
final LayoutInflater layoutInflater = LayoutInflater.from(this);
final ActivitySaver activitySaver = ActivityDI.createActivitySaver(this);
mDbFrontend = new DbFrontend(this, mGeocacheFactory);
final GeocacheFromIntentFactory geocacheFromIntentFactory = new GeocacheFromIntentFactory(
mGeocacheFactory, mDbFrontend);
final IncomingIntentHandler incomingIntentHandler = new IncomingIntentHandler(
mGeocacheFactory, geocacheFromIntentFactory, mDbFrontend);
Geocache geocache = incomingIntentHandler.maybeGetGeocacheFromIntent(getIntent(), null, mDbFrontend);
final SharedPreferences defaultSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
mGeoBeagleDelegate = new GeoBeagleDelegate(activitySaver,
this, mGeocacheFactory, geocacheViewer,
incomingIntentHandler,
mDbFrontend, radar, defaultSharedPreferences,
webPageButtonEnabler, geoFixProvider, favorite);
final MenuAction[] menuActionArray = {
new MenuActionCacheList(this, resources),
new MenuActionFromCacheAction(new CacheActionEdit(this, resources), geocache),
// new MenuActionLogDnf(this), new MenuActionLogFind(this),
//new MenuActionSearchOnline(this),
new MenuActionSettings(this, resources),
new MenuActionFromCacheAction(new CacheActionGoogleMaps(intentStarterViewUri, resources), geocache),
//new MenuActionFromCacheAction(new CacheActionProximity(this, resources), geocache),
};
final MenuActions menuActions = new MenuActions(menuActionArray);
mOptionsMenu = new GeoBeagleDelegate.OptionsMenu(menuActions);
// see http://www.androidguys.com/2008/11/07/rotational-forces-part-two/
if (getLastNonConfigurationInstance() != null) {
setIntent((Intent)getLastNonConfigurationInstance());
}
final CacheActionMap cacheActionMap = new CacheActionMap(this, resources);
final CacheButtonOnClickListener mapsButtonOnClickListener =
new CacheButtonOnClickListener(cacheActionMap, this, "Map error", errorDisplayer);
findViewById(id.maps).setOnClickListener(mapsButtonOnClickListener);
final AlertDialog.Builder cacheDetailsBuilder = new AlertDialog.Builder(this);
final CacheDetailsOnClickListener cacheDetailsOnClickListener = Misc
.createCacheDetailsOnClickListener(this, cacheDetailsBuilder, layoutInflater);
findViewById(R.id.cache_details).setOnClickListener(cacheDetailsOnClickListener);
final GeocacheToCachePage geocacheToCachePage = new GeocacheToCachePage(getResources());
final CacheActionViewUri cachePageIntentStarter = new CacheActionViewUri(this,
intentFactory, geocacheToCachePage, resources);
final CacheButtonOnClickListener cacheButtonOnClickListener =
new CacheButtonOnClickListener(cachePageIntentStarter, this, "", errorDisplayer);
findViewById(id.cache_page).setOnClickListener(cacheButtonOnClickListener);
findViewById(id.radarview).setOnClickListener(new CacheButtonOnClickListener(
new CacheActionRadar(this, resources), this, "Please install the Radar application to use Radar.",
errorDisplayer));
findViewById(id.menu_log_find).setOnClickListener(
new LogFindClickListener(this, id.menu_log_find));
findViewById(id.menu_log_dnf).setOnClickListener(
new LogFindClickListener(this, id.menu_log_dnf));
}
@Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
final FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf = new FieldnoteStringsFVsDnf(
getResources());
final Toaster toaster = new Toaster(this, R.string.error_writing_cache_log,
Toast.LENGTH_LONG);
final DateFormatter dateFormatter = new DateFormatter(simpleDateFormat);
final FileLogger fileLogger = new FileLogger(fieldnoteStringsFVsDnf, dateFormatter, toaster);
final SmsLogger smsLogger = new SmsLogger(fieldnoteStringsFVsDnf, this);
final SharedPreferences defaultSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
final CacheLogger cacheLogger = new CacheLogger(defaultSharedPreferences, fileLogger,
smsLogger);
final OnClickCancel onClickCancel = new OnClickCancel();
final LayoutInflater layoutInflater = LayoutInflater.from(this);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
final View fieldNoteDialogView = layoutInflater.inflate(R.layout.fieldnote, null);
final TextView fieldnoteCaveat = (TextView)fieldNoteDialogView
.findViewById(R.id.fieldnote_caveat);
final CharSequence geocacheId = mGeoBeagleDelegate.getGeocache().getId();
final boolean fDnf = id == R.id.menu_log_dnf;
final EditText editText = (EditText)fieldNoteDialogView.findViewById(R.id.fieldnote);
final DialogHelperCommon dialogHelperCommon = new DialogHelperCommon(
fieldnoteStringsFVsDnf, editText, fDnf, fieldnoteCaveat);
final DialogHelperFile dialogHelperFile = new DialogHelperFile(fieldnoteCaveat, this);
final DialogHelperSms dialogHelperSms = new DialogHelperSms(geocacheId.length(),
fieldnoteStringsFVsDnf, editText, fDnf, fieldnoteCaveat);
mFieldNoteSender = new FieldnoteLogger(dialogHelperCommon, dialogHelperFile,
dialogHelperSms);
final OnClickOk onClickOk = new OnClickOk(geocacheId, editText, cacheLogger, mDbFrontend, fDnf);
builder.setTitle(R.string.field_note_title);
builder.setView(fieldNoteDialogView);
builder.setNegativeButton(R.string.cancel, onClickCancel);
builder.setPositiveButton(R.string.log_cache, onClickOk);
return builder.create();
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onCreateDialog(id);
final SharedPreferences defaultSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
mFieldNoteSender.onPrepareDialog(dialog, defaultSharedPreferences, mLocalDateFormat
.format(new Date()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return mOptionsMenu.onCreateOptionsMenu(menu);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mGeoBeagleDelegate.onKeyDown(keyCode, event))
return true;
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mOptionsMenu.onOptionsItemSelected(item);
}
@Override
public void onPause() {
super.onPause();
Log.d("GeoBeagle", "GeoBeagle onPause");
mGeoBeagleDelegate.onPause();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onRestoreInstanceState(android.os.Bundle)
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mGeoBeagleDelegate.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
Log.d("GeoBeagle", "GeoBeagle onResume");
mGeoBeagleDelegate.onResume();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onRetainNonConfigurationInstance()
*/
@Override
public Object onRetainNonConfigurationInstance() {
return getIntent();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mGeoBeagleDelegate.onSaveInstanceState(outState);
}
}
| Java |
/*
* Copyright (C) 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.code.geobeagle.activity.main;
/*
*
* 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.
*/
import com.google.code.geobeagle.GeoFix;
import com.google.code.geobeagle.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
public class RadarView extends View {
private Paint mGridPaint;
private Paint mErasePaint;
private float mOrientation;
private double mTargetLat;
private double mTargetLon;
private static float KM_PER_METERS = 0.001f;
private static float METERS_PER_KM = 1000f;
/**
* These are the list of choices for the radius of the outer circle on the
* screen when using metric units. All items are in kilometers. This array
* is used to choose the scale of the radar display.
*/
private static double mMetricScaleChoices[] = {
100 * KM_PER_METERS, 200 * KM_PER_METERS, 400 * KM_PER_METERS, 1, 2, 4, 8, 20, 40, 100,
200, 400, 1000, 2000, 4000, 10000, 20000, 40000, 80000
};
/**
* Once the scale is chosen, this array is used to convert the number of
* kilometers on the screen to an integer. (Note that for short distances we
* use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This
* array is for metric measurements.)
*/
private static float mMetricDisplayUnitsPerKm[] = {
METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f
};
/**
* This array holds the formatting string used to display the distance to
* the target. (This array is for metric measurements.)
*/
private static String mMetricDisplayFormats[] = {
"%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.1fkm", "%.1fkm", "%.0fkm", "%.0fkm",
"%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm",
"%.0fkm", "%.0fkm"
};
private static float KM_PER_FEET = 0.0003048f;
private static float KM_PER_MILES = 1.609344f;
private static float FEET_PER_KM = 3280.8399f;
private static float MILES_PER_KM = 0.621371192f;
/**
* These are the list of choices for the radius of the outer circle on the
* screen when using standard units. All items are in kilometers. This array
* is used to choose the scale of the radar display.
*/
private static double mEnglishScaleChoices[] = {
100 * KM_PER_FEET, 200 * KM_PER_FEET, 400 * KM_PER_FEET, 1000 * KM_PER_FEET,
1 * KM_PER_MILES, 2 * KM_PER_MILES, 4 * KM_PER_MILES, 8 * KM_PER_MILES,
20 * KM_PER_MILES, 40 * KM_PER_MILES, 100 * KM_PER_MILES, 200 * KM_PER_MILES,
400 * KM_PER_MILES, 1000 * KM_PER_MILES, 2000 * KM_PER_MILES, 4000 * KM_PER_MILES,
10000 * KM_PER_MILES, 20000 * KM_PER_MILES, 40000 * KM_PER_MILES, 80000 * KM_PER_MILES
};
/**
* Once the scale is chosen, this array is used to convert the number of
* kilometers on the screen to an integer. (Note that for short distances we
* use meters, so we multiply the distance by {@link #YARDS_PER_KM}. (This
* array is for standard measurements.)
*/
private static float mEnglishDisplayUnitsPerKm[] = {
FEET_PER_KM, FEET_PER_KM, FEET_PER_KM, FEET_PER_KM, MILES_PER_KM, MILES_PER_KM,
MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM,
MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM,
MILES_PER_KM, MILES_PER_KM
};
/**
* This array holds the formatting string used to display the distance to
* the target. (This array is for standard measurements.)
*/
private static String mEnglishDisplayFormats[] = {
"%.0fft", "%.0fft", "%.0fft", "%.0fft", "%.1fmi", "%.1fmi", "%.1fmi", "%.1fmi",
"%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi",
"%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi"
};
private boolean mHaveLocation = false; // True when we have our location
private TextView mDistanceView;
private double mDistance; // Distance to target, in KM
private double mBearing; // Bearing to target, in degrees
// Ratio of the distance to the target to the radius of the outermost ring
// on the radar screen
private float mDistanceRatio;
private Bitmap mBlip; // The bitmap used to draw the target
// True if the display should use metric units; false if the display should
// use standard units
private boolean mUseMetric;
private TextView mBearingView;
private TextView mAccuracyView;
private TextView mLagView;
private final String mDegreesSymbol;
private Path mCompassPath;
private final Paint mCompassPaint;
private final Paint mArrowPaint;
private final Path mArrowPath;
private GeoFix mMyLocation;
public RadarView(Context context) {
this(context, null);
}
public RadarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RadarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDegreesSymbol = context.getString(R.string.degrees_symbol);
// Paint used for the rings and ring text
mGridPaint = new Paint();
mGridPaint.setColor(0xFF00FF00);
mGridPaint.setAntiAlias(true);
mGridPaint.setStyle(Style.STROKE);
mGridPaint.setStrokeWidth(1.0f);
mGridPaint.setTextSize(10.0f);
mGridPaint.setTextAlign(Align.CENTER);
mCompassPaint = new Paint();
mCompassPaint.setColor(0xFF00FF00);
mCompassPaint.setAntiAlias(true);
mCompassPaint.setStyle(Style.STROKE);
mCompassPaint.setStrokeWidth(1.0f);
mCompassPaint.setTextSize(10.0f);
mCompassPaint.setTextAlign(Align.CENTER);
// Paint used to erase the rectangle behind the ring text
mErasePaint = new Paint();
mErasePaint.setColor(0xFF191919);
mErasePaint.setStyle(Style.FILL);
// Paint used for the arrow
mArrowPaint = new Paint();
mArrowPaint.setColor(Color.WHITE);
mArrowPaint.setAntiAlias(true);
mArrowPaint.setStyle(Style.STROKE);
mArrowPaint.setStrokeWidth(16);
mArrowPaint.setAlpha(228);
mArrowPath = new Path();
mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap();
mCompassPath = new Path();
}
/**
* Sets the target to track on the radar
*
* @param latE6 Latitude of the target, multiplied by 1,000,000
* @param lonE6 Longitude of the target, multiplied by 1,000,000
*/
public void setTarget(int latE6, int lonE6) {
mTargetLat = latE6 / (double)GeoUtils.MILLION;
mTargetLon = lonE6 / (double)GeoUtils.MILLION;
}
/**
* Sets the view that we will use to report distance
*
* @param t The text view used to report distance
*/
public void setDistanceView(TextView d, TextView b, TextView a,
TextView lag) {
mDistanceView = d;
mBearingView = b;
mAccuracyView = a;
mLagView = lag;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int center = Math.min(getHeight(), getWidth()) / 2;
int radius = center - 8;
// Draw the rings
final Paint gridPaint = mGridPaint;
gridPaint.setAlpha(100);
canvas.drawCircle(center, center, radius, gridPaint);
canvas.drawCircle(center, center, radius * 3 / 4, gridPaint);
canvas.drawCircle(center, center, radius >> 1, gridPaint);
canvas.drawCircle(center, center, radius >> 2, gridPaint);
int blipRadius = (int)(mDistanceRatio * radius);
// Draw horizontal and vertical lines
canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint);
canvas.drawLine(center, center + (radius >> 2) - 6, center, center + radius + 6, gridPaint);
canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint);
canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint);
if (mHaveLocation) {
double northAngle = Math.toRadians(-mOrientation) - (Math.PI / 2);
float northX = (float)Math.cos(northAngle);
float northY = (float)Math.sin(northAngle);
final int compassLength = radius >> 2;
float tipX = northX * compassLength, tipY = northY * compassLength;
float baseX = northY * 8, baseY = -northX * 8;
double bearingToTarget = mBearing - mOrientation;
double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2);
float cos = (float)Math.cos(drawingAngle);
float sin = (float)Math.sin(drawingAngle);
mArrowPath.reset();
mArrowPath.moveTo(center - cos * radius, center - sin * radius);
mArrowPath.lineTo(center + cos * radius, center + sin * radius);
final double arrowRight = drawingAngle + Math.PI / 2;
final double arrowLeft = drawingAngle - Math.PI / 2;
mArrowPath.moveTo(center + (float)Math.cos(arrowRight) * radius, center
+ (float)Math.sin(arrowRight) * radius);
mArrowPath.lineTo(center + cos * radius, center + sin * radius);
mArrowPath.lineTo(center + (float)Math.cos(arrowLeft) * radius, center
+ (float)Math.sin(arrowLeft) * radius);
canvas.drawPath(mArrowPath, mArrowPaint);
drawCompassArrow(canvas, center, mCompassPaint, tipX, tipY, baseX, baseY, Color.RED);
drawCompassArrow(canvas, center, mCompassPaint, -tipX, -tipY, baseX, baseY, Color.GRAY);
gridPaint.setAlpha(255);
canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8, center + (sin * blipRadius)
- 8, gridPaint);
}
}
private void drawCompassArrow(Canvas canvas, int center, final Paint gridPaint, float tipX,
float tipY, float baseX, float baseY, int color) {
gridPaint.setStyle(Paint.Style.FILL_AND_STROKE);
gridPaint.setColor(color);
gridPaint.setAlpha(255);
mCompassPath.reset();
mCompassPath.moveTo(center + baseX, center + baseY);
mCompassPath.lineTo(center + tipX, center + tipY);
mCompassPath.lineTo(center - baseX, center - baseY);
mCompassPath.close();
canvas.drawPath(mCompassPath, gridPaint);
gridPaint.setStyle(Paint.Style.STROKE);
}
public void setLocation(GeoFix location, float azimuth) {
// Log.d("GeoBeagle", "radarview::onLocationChanged");
mHaveLocation = true;
mMyLocation = location;
mOrientation = azimuth;
double lat = location.getLatitude();
double lon = location.getLongitude();
mDistance = GeoUtils.distanceKm(lat, lon, mTargetLat, mTargetLon);
mBearing = GeoUtils.bearing(lat, lon, mTargetLat, mTargetLon);
updateDistance(mDistance);
double bearingToTarget = mBearing - mOrientation;
updateBearing(bearingToTarget);
postInvalidate();
}
/**
* Called when we no longer have a valid location.
*/
public void handleUnknownLocation() {
mHaveLocation = false;
mDistanceView.setText("");
mAccuracyView.setText("");
mLagView.setText("");
mBearingView.setText("");
}
/**
* Update state to reflect whether we are using metric or standard units.
*
* @param useMetric True if the display should use metric units
*/
public void setUseImperial(boolean useImperial) {
mUseMetric = !useImperial;
if (mHaveLocation) {
updateDistance(mDistance);
}
invalidate();
}
private void updateBearing(double bearing) {
bearing = (bearing + 720) % 360;
if (mHaveLocation) {
final String sBearing = ((int)bearing / 5) * 5 + mDegreesSymbol;
mBearingView.setText(sBearing);
}
}
/**
* Update our state to reflect a new distance to the target. This may
* require choosing a new scale for the radar rings.
*
* @param distanceKm The new distance to the target
* @param bearing
*/
private void updateDistance(double distanceKm) {
final double[] scaleChoices;
final float[] displayUnitsPerKm;
final String[] displayFormats;
String distanceStr = null;
if (mUseMetric) {
scaleChoices = mMetricScaleChoices;
displayUnitsPerKm = mMetricDisplayUnitsPerKm;
displayFormats = mMetricDisplayFormats;
} else {
scaleChoices = mEnglishScaleChoices;
displayUnitsPerKm = mEnglishDisplayUnitsPerKm;
displayFormats = mEnglishDisplayFormats;
}
final int count = scaleChoices.length;
for (int i = 0; i < count; i++) {
if (distanceKm < scaleChoices[i] || i == (count - 1)) {
String format = displayFormats[i];
double distanceDisplay = distanceKm * displayUnitsPerKm[i];
mDistanceRatio = (float)(mDistance / scaleChoices[i]);
distanceStr = String.format(format, distanceDisplay);
break;
}
}
mDistanceView.setText(distanceStr);
String accuracyStr = formatDistance(mMyLocation.getAccuracy(), scaleChoices,
displayUnitsPerKm, displayFormats);
mAccuracyView.setText(accuracyStr);
mLagView.setText(mMyLocation.getLagString(System.currentTimeMillis()));
}
private static String formatDistance(float accuracy, final double[] scaleChoices,
final float[] displayUnitsPerKm, final String[] displayFormats) {
if (accuracy == 0.0)
return "";
int count = scaleChoices.length;
for (int i = 0; i < count; i++) {
final float myLocationAccuracyKm = accuracy / 1000;
if (myLocationAccuracyKm < scaleChoices[i] || i == (count - 1)) {
final String format = displayFormats[i];
return "+/-" + String.format(format, myLocationAccuracyKm * displayUnitsPerKm[i]);
}
}
return "";
}
}
| Java |
/*
** 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.code.geobeagle.activity;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.main.view.EditCache;
import com.google.code.geobeagle.database.DbFrontend;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
public class EditCacheActivity extends Activity {
private DbFrontend mDbFrontend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final EditCache.CancelButtonOnClickListener cancelButtonOnClickListener = new EditCache.CancelButtonOnClickListener(
this);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
mDbFrontend = new DbFrontend(this, geocacheFactory);
setContentView(R.layout.cache_edit);
final Intent intent = getIntent();
final EditCache editCache = new EditCache(geocacheFactory,
(EditText)findViewById(R.id.edit_id),
(EditText)findViewById(R.id.edit_name),
(EditText)findViewById(R.id.edit_latitude),
(EditText)findViewById(R.id.edit_longitude));
EditCache.CacheSaverOnClickListener cacheSaver = new EditCache.CacheSaverOnClickListener(
this, editCache, mDbFrontend);
((Button)findViewById(R.id.edit_set)).setOnClickListener(cacheSaver);
((Button)findViewById(R.id.edit_cancel))
.setOnClickListener(cancelButtonOnClickListener);
Geocache geocache = mDbFrontend.loadCacheFromId(intent.getStringExtra("geocacheId"));
editCache.set(geocache);
}
@Override
protected void onPause() {
super.onPause();
mDbFrontend.closeDatabase();
}
}
| Java |
package com.google.code.geobeagle.activity.prox;
import com.google.code.geobeagle.GeoFix;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.actions.CacheFilterUpdater;
import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection;
import com.google.code.geobeagle.database.CachesProviderDb;
import com.google.code.geobeagle.database.CachesProviderCount;
import com.google.code.geobeagle.database.DbFrontend;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import java.util.ArrayList;
import java.util.List;
public class ProximityActivity extends Activity implements SurfaceHolder.Callback {
class DataCollector implements Refresher {
@Override
public void forceRefresh() {
refresh();
}
@Override
public void refresh() {
mProximityPainter.setUserDirection(mGeoFixProvider.getAzimuth());
GeoFix location = mGeoFixProvider.getLocation();
mProximityPainter.setUserLocation(location.getLatitude(),
location.getLongitude(), location.getAccuracy());
}
}
private ProximityView mProximityView;
ProximityPainter mProximityPainter;
DataCollector mDataCollector;
private AnimatorThread mAnimatorThread;
private boolean mStartWhenSurfaceCreated = false; //TODO: Is mStartWhenSurfaceCreated needed?
private DbFrontend mDbFrontend;
private GeoFixProvider mGeoFixProvider;
private CacheFilterUpdater mCacheFilterUpdater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeocacheFactory geocacheFactory = new GeocacheFactory();
mDbFrontend = new DbFrontend(this, geocacheFactory);
final FilterTypeCollection filterTypeCollection = new FilterTypeCollection(this);
CachesProviderDb cachesProviderDb = new CachesProviderDb(mDbFrontend);
CachesProviderCount cachesProviderCount = new CachesProviderCount(cachesProviderDb, 5, 10);
List<CachesProviderDb> list = new ArrayList<CachesProviderDb>();
list.add(cachesProviderDb);
mCacheFilterUpdater = new CacheFilterUpdater(filterTypeCollection, list);
mProximityPainter = new ProximityPainter(cachesProviderCount);
mProximityView = new ProximityView(this);
setContentView(mProximityView);
}
@Override
protected void onStart() {
super.onStart();
SurfaceHolder holder = mProximityView.getHolder();
holder.addCallback(this);
mDataCollector = new DataCollector();
mGeoFixProvider = LocationControlDi.create(this);
mGeoFixProvider.addObserver(mDataCollector);
}
@Override
protected void onResume() {
super.onResume();
String id = getIntent().getStringExtra("geocacheId");
if (!id.equals("")) {
Geocache geocache = mDbFrontend.loadCacheFromId(id);
mProximityPainter.setSelectedGeocache(geocache);
}
mCacheFilterUpdater.loadActiveFilter();
mGeoFixProvider.onResume();
GeoFix location = mGeoFixProvider.getLocation();
mProximityPainter.setUserLocation(location.getLatitude(), location.getLongitude(), location.getAccuracy());
if (mAnimatorThread == null)
mStartWhenSurfaceCreated = true;
else
mAnimatorThread.start();
}
@Override
protected void onPause() {
super.onPause();
mGeoFixProvider.onPause();
if (mAnimatorThread != null) {
AnimatorThread.IThreadStoppedListener listener = new
AnimatorThread.IThreadStoppedListener() {
@Override
public void OnThreadStopped() {
mDbFrontend.closeDatabase();
}
};
mAnimatorThread.stop(listener);
}
}
// ***********************************
// ** Implement SurfaceHolder.Callback **
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d("GeoBeagle", "surfaceChanged called ("+width+"x"+height+")");
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d("GeoBeagle", "surfaceCreated called");
mAnimatorThread = new AnimatorThread(holder, mProximityPainter);
if (mStartWhenSurfaceCreated) {
mStartWhenSurfaceCreated = false;
mAnimatorThread.start();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d("GeoBeagle", "surfaceDestroyed called");
}
}
| Java |
package com.google.code.geobeagle.activity.prox;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceView;
public class ProximityView extends SurfaceView {
public ProximityView(Context context) {
super(context);
setFocusable(true);
}
public ProximityView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
}
public ProximityView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
}
}
| Java |
package com.google.code.geobeagle.activity.prox;
import android.graphics.Canvas;
import android.os.SystemClock;
import android.util.Log;
import android.view.SurfaceHolder;
public class AnimatorThread {
public interface IThreadStoppedListener {
void OnThreadStopped();
}
//////////////////////////////////////////////////////////////
// PRIVATE MEMBERS
/** Handle to the surface manager object we interact with */
private SurfaceHolder mSurfaceHolder;
/** If the thread should be running */
private boolean mShouldRun = false;
private boolean mIsRunning = false;
private Thread mThread;
private ProximityPainter mWorld;
/** Time in milliseconds of the start of this cycle */
private long mCurrentTimeMillis = 0;
/** Time in seconds between the last and this cycle */
private double mCurrentTickDelta = 0;
/** If non-zero, AdvanceTime will not be called until this time (msec) */
private long mResumeAtTime = 0;
void updateTime() {
long now = System.currentTimeMillis();
assert (now >= mCurrentTimeMillis);
mCurrentTickDelta = (now - mCurrentTimeMillis) / 1000.0;
mCurrentTimeMillis = now;
if (mCurrentTickDelta > 0.3) {
Log.w("GeoBeagle", "Elapsed time " + mCurrentTickDelta +
" capped at 0.3 sec");
mCurrentTickDelta = 0.3;
}
}
private class RealThread extends Thread {
public void run() {
mIsRunning = true;
while (mShouldRun) {
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
if (c == null) {
Log.w(this.getClass().getName(),
"run(): lockCanvas returned null");
continue;
}
synchronized (mSurfaceHolder) {
updateTime();
if (mCurrentTimeMillis >= mResumeAtTime) {
mWorld.advanceTime(mCurrentTickDelta);
}
mWorld.draw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
mIsRunning = false;
}
}
private double mSecsPerTick = 0;
private int mNextTickNo = 0;
private class TimingThread extends Thread {
private int mRemainingRuns;
public TimingThread(int remainingRuns) {
mRemainingRuns = remainingRuns;
}
public void run() {
mIsRunning = true;
int totalTicksCount = mRemainingRuns;
long mStartTimeMillis = SystemClock.uptimeMillis();
while (mShouldRun && mRemainingRuns > 0) {
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
if (c == null) {
Log.w("GeoBeagle",
"run(): lockCanvas returned null");
continue;
}
synchronized (mSurfaceHolder) {
mWorld.advanceTime(mSecsPerTick);
mWorld.draw(c);
mRemainingRuns -= 1;
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
mIsRunning = false;
long duration = SystemClock.uptimeMillis() - mStartTimeMillis;
int ticksDone = totalTicksCount - mRemainingRuns;
if (ticksDone == 1) {
Log.d("GeoBeagle", "Iterated tick #" + mNextTickNo +
" (@" + mSecsPerTick + "s)");
} else if (ticksDone > 0) {
Log.d("GeoBeagle", "Iterated " + ticksDone +
" ticks (@" + mSecsPerTick + "s) in " +
duration + "ms => " + (ticksDone*1000/duration) + "fps");
}
mNextTickNo += ticksDone;
}
}
//////////////////////////////////////////////////////////////
// PUBLIC MEMBERS
public AnimatorThread(SurfaceHolder surfaceHolder,
ProximityPainter painter) {
mSurfaceHolder = surfaceHolder;
mWorld = painter;
}
public void start() {
if (mShouldRun)
return;
Log.d("GeoBeagle", "AnimatorThread.start()");
mCurrentTimeMillis = System.currentTimeMillis() - 1;
mResumeAtTime = System.currentTimeMillis() + 200;
mShouldRun = true;
if (!mIsRunning) {
if (mThread == null)
mThread = new RealThread();
mThread.start();
}
}
/** Run the game loop a specific number of times, for testing purposes. */
public void setupTiming(int nrOfTicks, double secondsPerTick) {
assert (!mShouldRun && !mIsRunning);
assert (nrOfTicks > 0);
assert (secondsPerTick > 0);
Log.d("GeoBeagle", "setupTiming(" + secondsPerTick +
" sec/tick, ticks=" + nrOfTicks + ")");
mResumeAtTime = 0;
//mShouldRun = true;
mSecsPerTick = secondsPerTick;
mThread = new TimingThread(nrOfTicks);
//mThread.start();
}
/** @param listener is invoked after the thread has stopped or at once if
* the thread wasn't running */
public void stop(IThreadStoppedListener listener) {
if (!mIsRunning) {
if (listener != null)
listener.OnThreadStopped();
return;
}
boolean retry = true;
mShouldRun = false;
while (retry) {
try {
mThread.join();
retry = false;
mThread = null;
listener.OnThreadStopped();
} catch (InterruptedException e) {
}
}
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.formatting.DistanceFormatterImperial;
import com.google.code.geobeagle.formatting.DistanceFormatterMetric;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class DistanceFormatterManagerDi {
public static DistanceFormatterManager create(Context context) {
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
final DistanceFormatterMetric distanceFormatterMetric = new DistanceFormatterMetric();
final DistanceFormatterImperial distanceFormatterImperial = new DistanceFormatterImperial();
return new DistanceFormatterManager(sharedPreferences, distanceFormatterImperial,
distanceFormatterMetric);
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class CacheListActivity extends ListActivity {
private CacheListDelegate mCacheListDelegate;
// For testing.
public CacheListDelegate getCacheListDelegate() {
return mCacheListDelegate;
}
// This is the ctor that Android will use.
public CacheListActivity() {
}
// This is the ctor for testing.
public CacheListActivity(CacheListDelegate cacheListDelegate) {
mCacheListDelegate = cacheListDelegate;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return mCacheListDelegate.onContextItemSelected(item) || super.onContextItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.d("GeoBeagle", "CacheListActivity onCreate");
mCacheListDelegate = CacheListDelegateDI.create(this, getLayoutInflater());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return mCacheListDelegate.onCreateOptionsMenu(menu);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mCacheListDelegate.onListItemClick(l, v, position, id);
}
/*
* (non-Javadoc)
* @see android.app.Activity#onMenuOpened(int, android.view.Menu)
*/
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
super.onMenuOpened(featureId, menu);
return mCacheListDelegate.onMenuOpened(featureId, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mCacheListDelegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
//Log.d("GeoBeagle", "CacheListActivity onPause");
super.onPause();
mCacheListDelegate.onPause();
}
@Override
protected void onResume() {
super.onResume();
//Log.d("GeoBeagle", "CacheListActivity onResume");
mCacheListDelegate.onResume();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mCacheListDelegate.onActivityResult();
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GraphicsGenerator;
import com.google.code.geobeagle.IPausable;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.GraphicsGenerator.AttributePainter;
import com.google.code.geobeagle.GraphicsGenerator.IconRenderer;
import com.google.code.geobeagle.actions.CacheAction;
import com.google.code.geobeagle.actions.CacheActionAssignTags;
import com.google.code.geobeagle.actions.CacheActionConfirm;
import com.google.code.geobeagle.actions.CacheActionDelete;
import com.google.code.geobeagle.actions.CacheActionEdit;
import com.google.code.geobeagle.actions.CacheActionToggleFavorite;
import com.google.code.geobeagle.actions.CacheActionView;
import com.google.code.geobeagle.actions.CacheContextMenu;
import com.google.code.geobeagle.actions.CacheFilterUpdater;
import com.google.code.geobeagle.actions.MenuActionClearTagNew;
import com.google.code.geobeagle.actions.MenuActionConfirm;
import com.google.code.geobeagle.actions.MenuActionDeleteAll;
import com.google.code.geobeagle.actions.MenuActionEditFilter;
import com.google.code.geobeagle.actions.MenuActionFilterListPopup;
import com.google.code.geobeagle.actions.MenuActionMap;
import com.google.code.geobeagle.actions.MenuActionSearchOnline;
import com.google.code.geobeagle.actions.MenuActionSettings;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.ActivityDI;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegate.ImportIntentManager;
import com.google.code.geobeagle.activity.cachelist.actions.Abortable;
import com.google.code.geobeagle.activity.cachelist.actions.MenuActionMyLocation;
import com.google.code.geobeagle.activity.cachelist.actions.MenuActionSyncGpx;
import com.google.code.geobeagle.activity.cachelist.actions.MenuActionToggleFilter;
import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListPositionUpdater;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManagerDi;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheSummaryRowInflater;
import com.google.code.geobeagle.activity.cachelist.presenter.RelativeBearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheSummaryRowInflater.RowViews.CacheNameAttributes;
import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater.TextSelector;
import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection;
import com.google.code.geobeagle.database.CachesProviderCenterThread;
import com.google.code.geobeagle.database.CachesProviderCount;
import com.google.code.geobeagle.database.CachesProviderDb;
import com.google.code.geobeagle.database.CachesProviderSorted;
import com.google.code.geobeagle.database.CachesProviderToggler;
import com.google.code.geobeagle.database.CachesProviderWaitForInit;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.ICachesProviderCenter;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate;
import com.google.code.geobeagle.gpsstatuswidget.GpsWidgetAndUpdater;
import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusView;
import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class CacheListDelegateDI {
//TODO: Remove class Timing and replace uses by Clock
public static class Timing {
private long mStartTime;
public void lap(CharSequence msg) {
long finishTime = Calendar.getInstance().getTimeInMillis();
Log.d("GeoBeagle", "****** " + msg + ": " + (finishTime - mStartTime));
mStartTime = finishTime;
}
public void start() {
mStartTime = Calendar.getInstance().getTimeInMillis();
}
public long getTime() {
return Calendar.getInstance().getTimeInMillis();
}
}
public static CacheListDelegate create(ListActivity listActivity,
LayoutInflater layoutInflater) {
final OnClickListener onClickListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
};
final ErrorDisplayer errorDisplayer = new ErrorDisplayer(listActivity, onClickListener);
final GeoFixProvider geoFixProvider = LocationControlDi.create(listActivity);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final BearingFormatter relativeBearingFormatter = new RelativeBearingFormatter();
final DistanceFormatterManager distanceFormatterManager = DistanceFormatterManagerDi
.create(listActivity);
final XmlPullParserWrapper xmlPullParserWrapper = new XmlPullParserWrapper();
final DbFrontend dbFrontend = new DbFrontend(listActivity, geocacheFactory);
final GraphicsGenerator graphicsGenerator = new GraphicsGenerator(
new GraphicsGenerator.RatingsGenerator(), new IconRenderer(new AttributePainter(new Paint(), new Rect())));
final CacheNameAttributes cacheNameAttributes = new CacheNameAttributes();
final GeocacheSummaryRowInflater geocacheSummaryRowInflater = new GeocacheSummaryRowInflater(
distanceFormatterManager.getFormatter(), layoutInflater,
relativeBearingFormatter, listActivity.getResources(), graphicsGenerator, dbFrontend, cacheNameAttributes);
final InflatedGpsStatusView inflatedGpsStatusWidget = new InflatedGpsStatusView(
listActivity);
final LinearLayout gpsStatusWidget = new LinearLayout(listActivity);
gpsStatusWidget.addView(inflatedGpsStatusWidget, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
final GpsWidgetAndUpdater gpsWidgetAndUpdater = new GpsWidgetAndUpdater(listActivity,
gpsStatusWidget, geoFixProvider,
distanceFormatterManager.getFormatter());
final GpsStatusWidgetDelegate gpsStatusWidgetDelegate = gpsWidgetAndUpdater
.getGpsStatusWidgetDelegate();
inflatedGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate);
final UpdateGpsWidgetRunnable updateGpsWidgetRunnable = gpsWidgetAndUpdater
.getUpdateGpsWidgetRunnable();
updateGpsWidgetRunnable.run();
final FilterTypeCollection filterTypeCollection = new FilterTypeCollection(listActivity);
final CachesProviderDb cachesProviderDb = new CachesProviderDb(dbFrontend);
final ICachesProviderCenter cachesProviderCount = new CachesProviderWaitForInit(new CachesProviderCount(cachesProviderDb, 15, 30));
final CachesProviderSorted cachesProviderSorted = new CachesProviderSorted(cachesProviderCount);
//final CachesProviderLazy cachesProviderLazy = new CachesProviderLazy(cachesProviderSorted, 0.01, 2000, clock);
ICachesProviderCenter cachesProviderLazy = cachesProviderSorted;
final CachesProviderDb cachesProviderAll = new CachesProviderDb(dbFrontend);
final CachesProviderToggler cachesProviderToggler =
new CachesProviderToggler(cachesProviderLazy, cachesProviderAll);
CachesProviderCenterThread thread = new CachesProviderCenterThread(cachesProviderToggler);
final TextSelector textSelector = new TextSelector();
final TitleUpdater titleUpdater = new TitleUpdater(listActivity,
cachesProviderToggler, dbFrontend, textSelector);
distanceFormatterManager.addHasDistanceFormatter(geocacheSummaryRowInflater);
distanceFormatterManager.addHasDistanceFormatter(gpsStatusWidgetDelegate);
final CacheListAdapter cacheListAdapter = new CacheListAdapter(cachesProviderToggler,
cachesProviderSorted, geocacheSummaryRowInflater, titleUpdater, null);
final CacheListPositionUpdater cacheListPositionUpdater = new CacheListPositionUpdater(
geoFixProvider, cacheListAdapter, cachesProviderCount, thread /*cachesProviderSorted*/);
geoFixProvider.addObserver(cacheListPositionUpdater);
geoFixProvider.addObserver(gpsStatusWidgetDelegate);
final CacheListAdapter.ScrollListener scrollListener = new CacheListAdapter.ScrollListener(
cacheListAdapter);
final CacheTypeFactory cacheTypeFactory = new CacheTypeFactory();
final Aborter aborter = new Aborter();
final MessageHandler messageHandler = MessageHandler.create(listActivity);
final GpxImporterFactory gpxImporterFactory = new GpxImporterFactory(aborter,
errorDisplayer, geoFixProvider, listActivity,
messageHandler, xmlPullParserWrapper, cacheTypeFactory, geocacheFactory);
final Abortable nullAbortable = new Abortable() {
public void abort() {
}
};
// *** BUILD MENU ***
final Resources resources = listActivity.getResources();
final MenuActionSyncGpx menuActionSyncGpx = new MenuActionSyncGpx(nullAbortable,
cacheListAdapter, gpxImporterFactory, dbFrontend, resources);
final CacheActionEdit cacheActionEdit = new CacheActionEdit(listActivity, resources);
final MenuActions menuActions = new MenuActions();
final AlertDialog.Builder builder1 = new AlertDialog.Builder(listActivity);
final MenuActionDeleteAll deleteAll = new MenuActionDeleteAll(dbFrontend, resources,
cachesProviderAll, cacheListAdapter, titleUpdater, R.string.delete_all_caches);
menuActions.add(new MenuActionToggleFilter(cachesProviderToggler, cacheListAdapter, resources));
menuActions.add(new MenuActionSearchOnline(listActivity, resources));
List<CachesProviderDb> providers = new ArrayList<CachesProviderDb>();
providers.add(cachesProviderDb);
providers.add(cachesProviderAll);
final CacheFilterUpdater cacheFilterUpdater =
new CacheFilterUpdater(filterTypeCollection, providers);
menuActions.add(new MenuActionMap(listActivity, geoFixProvider, resources));
//menuActions.add(new MenuActionFilterList(listActivity));
menuActions.add(new MenuActionEditFilter(listActivity, cacheFilterUpdater,
cacheListAdapter, filterTypeCollection, resources));
menuActions.add(new MenuActionFilterListPopup(listActivity, cacheFilterUpdater,
cacheListAdapter, filterTypeCollection, resources));
menuActions.add(new MenuActionClearTagNew(dbFrontend, geocacheFactory, cacheListAdapter));
menuActions.add(new MenuActionMyLocation(errorDisplayer,
geocacheFactory, geoFixProvider, dbFrontend, resources, cacheActionEdit));
menuActions.add(menuActionSyncGpx);
menuActions.add(new MenuActionConfirm(listActivity, builder1, deleteAll,
resources.getString(R.string.delete_all_caches),
resources.getString(R.string.confirm_delete_all_caches)));
menuActions.add(new MenuActionSettings(listActivity, resources));
// *** BUILD CONTEXT MENU ***
final CacheActionView cacheActionView = new CacheActionView(listActivity, resources);
final CacheActionToggleFavorite cacheActionToggleFavorite =
new CacheActionToggleFavorite(dbFrontend, cacheListAdapter, cacheFilterUpdater);
//TODO: It is currently a bug to send cachesProviderDb since cachesProviderAll also need to be notified of db changes.
final CacheActionDelete cacheActionDelete =
new CacheActionDelete(cacheListAdapter, titleUpdater, dbFrontend, cachesProviderDb, resources);
final AlertDialog.Builder builder = new AlertDialog.Builder(listActivity);
CacheActionAssignTags cacheActionAssignTags =
new CacheActionAssignTags(listActivity, dbFrontend, cacheListAdapter);
final CacheActionConfirm cacheActionConfirmDelete =
new CacheActionConfirm(listActivity, builder, cacheActionDelete,
listActivity.getString(R.string.confirm_delete_title),
listActivity.getString(R.string.confirm_delete_body_text));
final CacheAction[] contextActions = new CacheAction[] {
cacheActionView, cacheActionToggleFavorite,
cacheActionEdit, cacheActionAssignTags,
cacheActionConfirmDelete
};
final ActivitySaver activitySaver = ActivityDI.createActivitySaver(listActivity);
final ImportIntentManager importIntentManager = new ImportIntentManager(listActivity);
final CacheContextMenu contextMenu =
new CacheContextMenu(cachesProviderToggler, contextActions);
final IPausable pausables[] = { geoFixProvider, thread };
final GeocacheListController geocacheListController =
new GeocacheListController(cacheListAdapter, menuActionSyncGpx,
menuActions, cacheActionView, cacheFilterUpdater);
//TODO: It is currently a bug to send cachesProviderDb since cachesProviderAll also need to be notified of db changes.
final CacheListDelegate cacheListDelegate = new CacheListDelegate(importIntentManager, activitySaver,
geocacheListController, dbFrontend, contextMenu, cacheListAdapter, geocacheSummaryRowInflater, listActivity,
distanceFormatterManager, cachesProviderDb, pausables);
listActivity.setContentView(R.layout.cache_list);
final ListView listView = listActivity.getListView();
listView.addHeaderView(gpsStatusWidget);
listActivity.setListAdapter(cacheListAdapter);
listView.setOnCreateContextMenuListener(contextMenu);
listView.setOnScrollListener(scrollListener);
updateGpsWidgetRunnable.run();
return cacheListDelegate;
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.database.CacheWriter;
import com.google.code.geobeagle.xmlimport.GpxImporter;
import com.google.code.geobeagle.xmlimport.GpxImporterDI;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import android.app.ListActivity;
public class GpxImporterFactory {
private final Aborter mAborter;
private final ErrorDisplayer mErrorDisplayer;
private final GeoFixProvider mGeoFixProvider;
private final ListActivity mListActivity;
private final MessageHandler mMessageHandler;
private final XmlPullParserWrapper mXmlPullParserWrapper;
private final CacheTypeFactory mCacheTypeFactory;
private final GeocacheFactory mGeocacheFactory;
public GpxImporterFactory(Aborter aborter,
ErrorDisplayer errorDisplayer,
GeoFixProvider geoFixProvider, ListActivity listActivity,
MessageHandler messageHandler, XmlPullParserWrapper xmlPullParserWrapper,
CacheTypeFactory cacheTypeFactory, GeocacheFactory geocacheFactory) {
mAborter = aborter;
mErrorDisplayer = errorDisplayer;
mGeoFixProvider = geoFixProvider;
mListActivity = listActivity;
mMessageHandler = messageHandler;
mXmlPullParserWrapper = xmlPullParserWrapper;
mCacheTypeFactory = cacheTypeFactory;
mGeocacheFactory = geocacheFactory;
}
public GpxImporter create(CacheWriter cacheWriter) {
return GpxImporterDI.create(mListActivity, mXmlPullParserWrapper, mErrorDisplayer,
mGeoFixProvider, mAborter, mMessageHandler,
cacheWriter, mCacheTypeFactory, mGeocacheFactory);
}
}
| Java |
/*
** 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.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.ActivityDI;
import com.google.code.geobeagle.activity.ActivityRestorer;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityDI.ActivityTypeFactory;
import com.google.code.geobeagle.activity.ActivityRestorer.CacheListRestorer;
import com.google.code.geobeagle.activity.ActivityRestorer.NullRestorer;
import com.google.code.geobeagle.activity.ActivityRestorer.Restorer;
import com.google.code.geobeagle.activity.ActivityRestorer.ViewCacheRestorer;
import com.google.code.geobeagle.activity.cachelist.CacheListActivity;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManagerDi;
import com.google.code.geobeagle.activity.searchonline.JsInterface.JsInterfaceHelper;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate;
import com.google.code.geobeagle.gpsstatuswidget.GpsWidgetAndUpdater;
import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
public class SearchOnlineActivity extends Activity {
private SearchOnlineActivityDelegate mSearchOnlineActivityDelegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("GeoBeagle", "SearchOnlineActivity onCreate");
setContentView(R.layout.search);
final GeoFixProvider mGeoFixProvider = LocationControlDi.create(this);
final InflatedGpsStatusView mGpsStatusWidget = (InflatedGpsStatusView)this
.findViewById(R.id.gps_widget_view);
final DistanceFormatterManager distanceFormatterManager = DistanceFormatterManagerDi
.create(this);
final GpsWidgetAndUpdater gpsWidgetAndUpdater = new GpsWidgetAndUpdater(this,
mGpsStatusWidget, mGeoFixProvider, distanceFormatterManager.getFormatter());
final GpsStatusWidgetDelegate gpsStatusWidgetDelegate = gpsWidgetAndUpdater
.getGpsStatusWidgetDelegate();
gpsWidgetAndUpdater.getUpdateGpsWidgetRunnable().run();
mGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate);
mGpsStatusWidget.setBackgroundColor(Color.BLACK);
distanceFormatterManager.addHasDistanceFormatter(gpsStatusWidgetDelegate);
final ActivitySaver activitySaver = ActivityDI.createActivitySaver(this);
final SharedPreferences sharedPreferences = getSharedPreferences("GeoBeagle",
Context.MODE_PRIVATE);
final ActivityTypeFactory activityTypeFactory = new ActivityTypeFactory();
final NullRestorer nullRestorer = new NullRestorer();
final CacheListRestorer cacheListRestorer = new CacheListRestorer(this);
final ViewCacheRestorer viewCacheRestorer = new ViewCacheRestorer(sharedPreferences, this);
final Restorer restorers[] = new Restorer[] {
nullRestorer, cacheListRestorer, nullRestorer,
viewCacheRestorer
};
final ActivityRestorer activityRestorer = new ActivityRestorer(activityTypeFactory,
sharedPreferences, restorers);
mSearchOnlineActivityDelegate = new SearchOnlineActivityDelegate(
((WebView)findViewById(R.id.help_contents)), mGeoFixProvider,
distanceFormatterManager, activitySaver);
final JsInterfaceHelper jsInterfaceHelper = new JsInterfaceHelper(this);
final JsInterface jsInterface = new JsInterface(mGeoFixProvider, jsInterfaceHelper);
mSearchOnlineActivityDelegate.configureWebView(jsInterface);
activityRestorer.restore(getIntent().getFlags());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_online_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
startActivity(new Intent(this, CacheListActivity.class));
return true;
}
@Override
protected void onResume() {
super.onResume();
Log.d("GeoBeagle", "SearchOnlineActivity onResume");
mSearchOnlineActivityDelegate.onResume();
}
@Override
protected void onPause() {
super.onPause();
Log.d("GeoBeagle", "SearchOnlineActivity onPause");
mSearchOnlineActivityDelegate.onPause();
}
}
| Java |
/*
** 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.code.geobeagle.activity.preferences;
import com.google.code.geobeagle.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class EditPreferences extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
| Java |
/*
** 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.code.geobeagle.gpx.zip;
import com.google.code.geobeagle.xmlimport.gpx.zip.GpxZipInputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipInputStream;
public class ZipInputStreamFactory {
public GpxZipInputStream create(String filename) throws IOException {
return new GpxZipInputStream(new ZipInputStream(new BufferedInputStream(
new FileInputStream(filename))));
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.xmlimport.CachePersisterFacade;
import com.google.code.geobeagle.xmlimport.GpxLoader;
import com.google.code.geobeagle.xmlimport.GpxToCache;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import android.os.PowerManager.WakeLock;
public class GpxLoaderDI {
public static GpxLoader create(CachePersisterFacade cachePersisterFacade,
XmlPullParserWrapper xmlPullParserFactory, Aborter aborter, ErrorDisplayer errorDisplayer, WakeLock wakeLock) {
final GpxToCache gpxToCache = new GpxToCache(xmlPullParserFactory, aborter);
return new GpxLoader(cachePersisterFacade, errorDisplayer, gpxToCache, wakeLock);
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.xmlimport.EventHandler;
import com.google.code.geobeagle.xmlimport.EventHelper;
import com.google.code.geobeagle.xmlimport.EventHelper.XmlPathBuilder;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
public class EventHelperDI {
public static class EventHelperFactory {
private final XmlPullParserWrapper mXmlPullParser;
public EventHelperFactory(XmlPullParserWrapper xmlPullParser) {
mXmlPullParser = xmlPullParser;
}
public EventHelper create(EventHandler eventHandler) {
final XmlPathBuilder xmlPathBuilder = new XmlPathBuilder();
return new EventHelper(xmlPathBuilder, eventHandler, mXmlPullParser);
}
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class GpxToCacheDI {
public static class XmlPullParserWrapper {
private String mSource;
private XmlPullParser mXmlPullParser;
public String getAttributeValue(String namespace, String name) {
return mXmlPullParser.getAttributeValue(namespace, name);
}
public int getEventType() throws XmlPullParserException {
return mXmlPullParser.getEventType();
}
public String getName() {
return mXmlPullParser.getName();
}
public String getSource() {
return mSource;
}
public String getText() {
return mXmlPullParser.getText();
}
public int next() throws XmlPullParserException, IOException {
return mXmlPullParser.next();
}
public void open(String path, Reader reader) throws XmlPullParserException {
final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
newPullParser.setInput(reader);
mSource = path;
mXmlPullParser = newPullParser;
}
}
public static XmlPullParser createPullParser(String path) throws FileNotFoundException,
XmlPullParserException {
final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
final Reader reader = new BufferedReader(new FileReader(path));
newPullParser.setInput(reader);
return newPullParser;
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import java.io.File;
public class FileFactory {
public File createFile(String path) {
return new File(path);
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import com.google.code.geobeagle.cachedetails.CacheDetailsWriter;
import com.google.code.geobeagle.cachedetails.HtmlWriter;
import com.google.code.geobeagle.cachedetails.WriterWrapper;
import com.google.code.geobeagle.database.CacheWriter;
import com.google.code.geobeagle.xmlimport.FileFactory;
import com.google.code.geobeagle.xmlimport.CachePersisterFacade.TextHandler;
import com.google.code.geobeagle.xmlimport.EventHelperDI.EventHelperFactory;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import com.google.code.geobeagle.xmlimport.ImportThreadDelegate.ImportThreadHelper;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.xmlimport.gpx.GpxFileIterAndZipFileIterFactory;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxAndZipFilenameFilter;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter;
import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener.ZipInputFileTester;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.widget.Toast;
import java.io.FilenameFilter;
import java.util.HashMap;
public class GpxImporterDI {
// Can't test this due to final methods in base.
public static class ImportThread extends Thread {
static ImportThread create(MessageHandler messageHandler, GpxLoader gpxLoader,
EventHandlers eventHandlers, XmlPullParserWrapper xmlPullParserWrapper,
ErrorDisplayer errorDisplayer, Aborter aborter,
GeocacheFactory geocacheFactory) {
final GpxFilenameFilter gpxFilenameFilter = new GpxFilenameFilter();
final FilenameFilter filenameFilter = new GpxAndZipFilenameFilter(gpxFilenameFilter);
final ZipInputFileTester zipInputFileTester = new ZipInputFileTester(gpxFilenameFilter);
final GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory = new GpxFileIterAndZipFileIterFactory(
zipInputFileTester, aborter);
final GpxAndZipFiles gpxAndZipFiles = new GpxAndZipFiles(filenameFilter,
gpxFileIterAndZipFileIterFactory);
final EventHelperFactory eventHelperFactory = new EventHelperFactory(
xmlPullParserWrapper);
final ImportThreadHelper importThreadHelper = new ImportThreadHelper(gpxLoader,
messageHandler, eventHelperFactory, eventHandlers, errorDisplayer,
geocacheFactory);
return new ImportThread(gpxAndZipFiles, importThreadHelper, errorDisplayer);
}
private final ImportThreadDelegate mImportThreadDelegate;
public ImportThread(GpxAndZipFiles gpxAndZipFiles, ImportThreadHelper importThreadHelper,
ErrorDisplayer errorDisplayer) {
mImportThreadDelegate = new ImportThreadDelegate(gpxAndZipFiles, importThreadHelper,
errorDisplayer);
}
@Override
public void run() {
mImportThreadDelegate.run();
}
}
// Wrapper so that containers can follow the "constructors do no work" rule.
public static class ImportThreadWrapper {
private final Aborter mAborter;
private ImportThread mImportThread;
private final MessageHandler mMessageHandler;
private final XmlPullParserWrapper mXmlPullParserWrapper;
public ImportThreadWrapper(MessageHandler messageHandler,
XmlPullParserWrapper xmlPullParserWrapper, Aborter aborter) {
mMessageHandler = messageHandler;
mXmlPullParserWrapper = xmlPullParserWrapper;
mAborter = aborter;
}
public boolean isAlive() {
if (mImportThread != null)
return mImportThread.isAlive();
return false;
}
public void join() {
if (mImportThread != null)
try {
mImportThread.join();
} catch (InterruptedException e) {
// Ignore; we are aborting anyway.
}
}
public void open(CacheListAdapter cacheList, GpxLoader gpxLoader,
EventHandlers eventHandlers, ErrorDisplayer mErrorDisplayer,
GeocacheFactory geocacheFactory) {
mMessageHandler.start(cacheList);
mImportThread = ImportThread.create(mMessageHandler, gpxLoader, eventHandlers,
mXmlPullParserWrapper, mErrorDisplayer, mAborter, geocacheFactory);
}
public void start() {
if (mImportThread != null)
mImportThread.start();
}
}
// Too hard to test this class due to final methods in base.
public static class MessageHandler extends Handler {
public static final String GEOBEAGLE = "GeoBeagle";
static final int MSG_DONE = 1;
static final int MSG_PROGRESS = 0;
public static MessageHandler create(ListActivity listActivity) {
final ProgressDialogWrapper progressDialogWrapper = new ProgressDialogWrapper(
listActivity);
return new MessageHandler(progressDialogWrapper);
}
private int mCacheCount;
private boolean mLoadAborted;
private CacheListAdapter mCacheList;
private final ProgressDialogWrapper mProgressDialogWrapper;
private String mSource;
private String mStatus;
private String mWaypointId;
public MessageHandler(ProgressDialogWrapper progressDialogWrapper) {
mProgressDialogWrapper = progressDialogWrapper;
}
public void abortLoad() {
mLoadAborted = true;
mProgressDialogWrapper.dismiss();
}
@Override
public void handleMessage(Message msg) {
// Log.d(GEOBEAGLE, "received msg: " + msg.what);
switch (msg.what) {
case MessageHandler.MSG_PROGRESS:
mProgressDialogWrapper.setMessage(mStatus);
break;
case MessageHandler.MSG_DONE:
if (!mLoadAborted) {
mProgressDialogWrapper.dismiss();
mCacheList.forceRefresh();
}
break;
default:
break;
}
}
public void loadComplete() {
sendEmptyMessage(MessageHandler.MSG_DONE);
}
public void start(CacheListAdapter cacheList) {
mCacheCount = 0;
mLoadAborted = false;
mCacheList = cacheList;
// TODO: move text into resource.
mProgressDialogWrapper.show("Syncing caches", "Please wait...");
}
public void updateName(String name) {
mStatus = mCacheCount++ + ": " + mSource + " - " + mWaypointId + " - " + name;
sendEmptyMessage(MessageHandler.MSG_PROGRESS);
}
public void updateSource(String text) {
mSource = text;
mStatus = "Opening: " + mSource + "...";
sendEmptyMessage(MessageHandler.MSG_PROGRESS);
}
public void updateWaypointId(String wpt) {
mWaypointId = wpt;
}
}
// Wrapper so that containers can follow the "constructors do no work" rule.
public static class ProgressDialogWrapper {
private final Context mContext;
private ProgressDialog mProgressDialog;
public ProgressDialogWrapper(Context context) {
mContext = context;
}
public void dismiss() {
if (mProgressDialog != null)
mProgressDialog.dismiss();
}
public void setMessage(CharSequence message) {
mProgressDialog.setMessage(message);
}
public void show(String title, String msg) {
mProgressDialog = ProgressDialog.show(mContext, title, msg);
}
}
public static class ToastFactory {
public void showToast(Context context, int resId, int duration) {
Toast.makeText(context, resId, duration).show();
}
}
public static GpxImporter create(ListActivity listActivity,
XmlPullParserWrapper xmlPullParserWrapper, ErrorDisplayer errorDisplayer,
GeoFixProvider geoFixProvider, Aborter aborter,
MessageHandler messageHandler,
CacheWriter cacheWriter, CacheTypeFactory cacheTypeFactory,
GeocacheFactory geocacheFactory) {
final PowerManager powerManager = (PowerManager)listActivity
.getSystemService(Context.POWER_SERVICE);
final WakeLock wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
"Importing");
FileFactory fileFactory = new FileFactory();
WriterWrapper writerWrapper = new WriterWrapper();
HtmlWriter htmlWriter = new HtmlWriter(writerWrapper);
CacheDetailsWriter cacheDetailsWriter = new CacheDetailsWriter(htmlWriter);
final CacheTagSqlWriter cacheTagSqlWriter = new CacheTagSqlWriter(cacheWriter, cacheTypeFactory);
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(listActivity);
final String username = sharedPreferences.getString("username", "");
final CachePersisterFacade cachePersisterFacade =
new CachePersisterFacade(cacheTagSqlWriter, fileFactory,
cacheDetailsWriter, messageHandler, wakeLock, username);
final GpxLoader gpxLoader = GpxLoaderDI.create(cachePersisterFacade, xmlPullParserWrapper,
aborter, errorDisplayer, wakeLock);
final ToastFactory toastFactory = new ToastFactory();
final ImportThreadWrapper importThreadWrapper = new ImportThreadWrapper(messageHandler,
xmlPullParserWrapper, aborter);
final HashMap<String, TextHandler> textHandlers = GpxImporterDI.initializeTextHandlers(cachePersisterFacade);
final EventHandlerGpx eventHandlerGpx = new EventHandlerGpx(cachePersisterFacade, textHandlers );
final EventHandlerLoc eventHandlerLoc = new EventHandlerLoc(cachePersisterFacade);
final EventHandlers eventHandlers = new EventHandlers();
eventHandlers.add(".gpx", eventHandlerGpx);
eventHandlers.add(".loc", eventHandlerLoc);
return new GpxImporter(geoFixProvider, gpxLoader, listActivity, importThreadWrapper,
messageHandler, toastFactory, eventHandlers, errorDisplayer,
geocacheFactory);
}
public static HashMap<String, TextHandler> initializeTextHandlers(CachePersisterFacade cachePersisterFacade) {
HashMap<String, TextHandler> textHandlers = new HashMap<String, TextHandler>();
textHandlers.put(EventHandlerGpx.XPATH_WPTNAME, cachePersisterFacade.wptName);
textHandlers.put(EventHandlerGpx.XPATH_WPTDESC, cachePersisterFacade.wptDesc);
textHandlers.put(EventHandlerGpx.XPATH_GROUNDSPEAKNAME, cachePersisterFacade.groundspeakName);
textHandlers.put(EventHandlerGpx.XPATH_GEOCACHENAME, cachePersisterFacade.groundspeakName);
textHandlers.put(EventHandlerGpx.XPATH_PLACEDBY, cachePersisterFacade.placedBy);
textHandlers.put(EventHandlerGpx.XPATH_LOGDATE, cachePersisterFacade.logDate);
textHandlers.put(EventHandlerGpx.XPATH_GEOCACHELOGDATE, cachePersisterFacade.logDate);
textHandlers.put(EventHandlerGpx.XPATH_HINT, cachePersisterFacade.hint);
textHandlers.put(EventHandlerGpx.XPATH_GEOCACHEHINT, cachePersisterFacade.hint);
textHandlers.put(EventHandlerGpx.XPATH_CACHE_TYPE, cachePersisterFacade.cacheType);
textHandlers.put(EventHandlerGpx.XPATH_GEOCACHE_TYPE, cachePersisterFacade.cacheType);
textHandlers.put(EventHandlerGpx.XPATH_WAYPOINT_TYPE, cachePersisterFacade.cacheType);
textHandlers.put(EventHandlerGpx.XPATH_CACHE_DIFFICULTY, cachePersisterFacade.difficulty);
textHandlers.put(EventHandlerGpx.XPATH_GEOCACHE_DIFFICULTY, cachePersisterFacade.difficulty);
textHandlers.put(EventHandlerGpx.XPATH_CACHE_TERRAIN, cachePersisterFacade.terrain);
textHandlers.put(EventHandlerGpx.XPATH_GEOCACHE_TERRAIN, cachePersisterFacade.terrain);
textHandlers.put(EventHandlerGpx.XPATH_CACHE_CONTAINER, cachePersisterFacade.container);
textHandlers.put(EventHandlerGpx.XPATH_GEOCACHE_CONTAINER, cachePersisterFacade.container);
return textHandlers;
}
}
| Java |
/*
** 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.code.geobeagle;
public enum CacheType {
NULL(0, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "null"),
MULTI(2, R.drawable.cache_multi, R.drawable.cache_multi_big,
R.drawable.pin_multi, "multi"),
TRADITIONAL(1, R.drawable.cache_tradi, R.drawable.cache_tradi_big,
R.drawable.pin_tradi, "traditional"),
UNKNOWN(3, R.drawable.cache_mystery, R.drawable.cache_mystery_big,
R.drawable.pin_mystery, "unknown"),
MY_LOCATION(4, R.drawable.blue_dot, R.drawable.blue_dot,
R.drawable.pin_default, "my location"),
//Caches without unique icons
EARTHCACHE(5, R.drawable.cache_earth, R.drawable.cache_earth_big,
R.drawable.pin_earth, "earth"),
VIRTUAL(6, R.drawable.cache_virtual, R.drawable.cache_virtual_big,
R.drawable.pin_virtual, "virtual"),
LETTERBOX_HYBRID(7, R.drawable.cache_letterbox, R.drawable.cache_letterbox_big,
R.drawable.pin_letter, "letterbox"),
EVENT(8, R.drawable.cache_event, R.drawable.cache_event_big,
R.drawable.pin_event, "event"),
WEBCAM(9, R.drawable.cache_webcam, R.drawable.cache_webcam_big,
R.drawable.pin_webcam, "webcam"),
//Caches without unique icons
CITO(10, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "cache in trash out"),
LOCATIONLESS(11, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "reverse"),
APE(12, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "project ape"),
MEGA(13, R.drawable.cache_mega, R.drawable.cache_mega_big,
R.drawable.pin_mega, "mega-event"),
WHERIGO(14, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "wherigo"),
//Waypoint types
WAYPOINT(20, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "waypoint"), //Not actually seen in GPX...
WAYPOINT_PARKING(21, R.drawable.cache_waypoint_p, R.drawable.cache_waypoint_p_big,
R.drawable.map_pin2_wp_p, "waypoint|parking area"),
WAYPOINT_REFERENCE(22, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big,
R.drawable.map_pin2_wp_r, "waypoint|reference point"),
WAYPOINT_STAGES(23, R.drawable.cache_waypoint_s, R.drawable.cache_waypoint_s_big,
R.drawable.map_pin2_wp_s, "waypoint|stages of a multicache"),
WAYPOINT_TRAILHEAD(24, R.drawable.cache_waypoint_t, R.drawable.cache_waypoint_t_big,
R.drawable.map_pin2_wp_t, "waypoint|trailhead"),
WAYPOINT_FINAL(25, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big,
R.drawable.map_pin2_wp_r, "waypoint|final location"); //TODO: Doesn't have unique graphics yet
private final int mIconId;
private final int mIconIdBig;
private final int mIx;
private final int mIconIdMap;
private final String mTag;
CacheType(int ix, int drawableId, int drawableIdBig, int drawableIdMap,
String tag) {
mIx = ix;
mIconId = drawableId;
mIconIdBig = drawableIdBig;
mIconIdMap = drawableIdMap;
mTag = tag;
}
public int icon() {
return mIconId;
}
public int iconBig() {
return mIconIdBig;
}
public int toInt() {
return mIx;
}
public int iconMap() {
return mIconIdMap;
}
public String getTag() {
return mTag;
}
}
| Java |
package com.google.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.GeoFix;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.Clock;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate.TimeProvider;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
public class GpsWidgetAndUpdater {
private static final class SystemTime implements TimeProvider {
@Override
public long getTime() {
return System.currentTimeMillis();
}
}
private final GpsStatusWidgetDelegate mGpsStatusWidgetDelegate;
private final UpdateGpsWidgetRunnable mUpdateGpsRunnable;
public GpsWidgetAndUpdater(Context context, View gpsWidgetView,
GeoFixProvider geoFixProvider,
DistanceFormatter distanceFormatterMetric) {
final Clock clock = new Clock();
final Handler handler = new Handler();
final MeterFormatter meterFormatter = new MeterFormatter(context);
final TextView locationViewer =
(TextView)gpsWidgetView.findViewById(R.id.location_viewer);
final MeterBars meterBars = new MeterBars(locationViewer, meterFormatter);
final TextView accuracyView = (TextView)gpsWidgetView.findViewById(R.id.accuracy);
final Meter meter = new Meter(meterBars, accuracyView);
final TextView lag = (TextView)gpsWidgetView.findViewById(R.id.lag);
final TextView status = (TextView)gpsWidgetView.findViewById(R.id.status);
final TextView provider = (TextView)gpsWidgetView.findViewById(R.id.provider);
final MeterFader meterFader = new MeterFader(gpsWidgetView, meterBars, clock);
TimeProvider timeProvider = new SystemTime();
mGpsStatusWidgetDelegate = new GpsStatusWidgetDelegate(geoFixProvider,
distanceFormatterMetric, meter, meterFader, provider, context,
status, lag, GeoFix.NO_FIX, timeProvider);
mUpdateGpsRunnable = new UpdateGpsWidgetRunnable(handler,
geoFixProvider, meter, mGpsStatusWidgetDelegate, timeProvider);
}
public GpsStatusWidgetDelegate getGpsStatusWidgetDelegate() {
return mGpsStatusWidgetDelegate;
}
public UpdateGpsWidgetRunnable getUpdateGpsWidgetRunnable() {
return mUpdateGpsRunnable;
}
}
| Java |
/*
** 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.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.R;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
/**
* Displays the GPS status (mAccuracy, availability, etc).
* @author sng
*/
public class InflatedGpsStatusView extends LinearLayout {
private GpsStatusWidgetDelegate mGpsStatusWidgetDelegate;
public InflatedGpsStatusView(Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true);
}
public InflatedGpsStatusView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
mGpsStatusWidgetDelegate.paint();
}
public void setDelegate(GpsStatusWidgetDelegate gpsStatusWidgetDelegate) {
mGpsStatusWidgetDelegate = gpsStatusWidgetDelegate;
}
}
| Java |
/*
** 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.code.geobeagle;
import com.google.code.geobeagle.Geocache.AttributeFormatter;
import com.google.code.geobeagle.Geocache.AttributeFormatterImpl;
import com.google.code.geobeagle.Geocache.AttributeFormatterNull;
import com.google.code.geobeagle.GeocacheFactory.Source.SourceFactory;
import com.google.code.geobeagle.database.SourceNameTranslator;
import android.database.Cursor;
import java.util.WeakHashMap;
//TODO: Make GeocacheFactory call DbFrontend and not the other way around.
//TODO: Make GeocacheFactory is a global object, common to all Activities of GeoBeagle. Solves GeocacheFactory flushing in other activites when a geocache is changed.
public class GeocacheFactory {
public static enum Provider {
ATLAS_QUEST(0, "LB"), GROUNDSPEAK(1, "GC"), MY_LOCATION(-1, "ML"), OPENCACHING(2, "OC");
private final int mIx;
private final String mPrefix;
Provider(int ix, String prefix) {
mIx = ix;
mPrefix = prefix;
}
public int toInt() {
return mIx;
}
public String getPrefix() {
return mPrefix;
}
}
public static Provider ALL_PROVIDERS[] = {
Provider.ATLAS_QUEST, Provider.GROUNDSPEAK, Provider.MY_LOCATION, Provider.OPENCACHING
};
public static enum Source {
GPX(0), LOC(3), MY_LOCATION(1), WEB_URL(2);
public final static int MIN_SOURCE = 0;
public final static int MAX_SOURCE = 3;
public static class SourceFactory {
private final Source mSources[] = new Source[values().length];
public SourceFactory() {
for (Source source : values())
mSources[source.mIx] = source;
}
public Source fromInt(int i) {
return mSources[i];
}
}
private final int mIx;
Source(int ix) {
mIx = ix;
}
public int toInt() {
return mIx;
}
}
static class AttributeFormatterFactory {
private AttributeFormatterImpl mAttributeFormatterImpl;
private AttributeFormatterNull mAttributeFormatterNull;
public AttributeFormatterFactory(AttributeFormatterImpl attributeFormatterImpl,
AttributeFormatterNull attributeFormatterNull) {
mAttributeFormatterImpl = attributeFormatterImpl;
mAttributeFormatterNull = attributeFormatterNull;
}
AttributeFormatter getAttributeFormatter(Source sourceType) {
if (sourceType == Source.GPX)
return mAttributeFormatterImpl;
return mAttributeFormatterNull;
}
}
private static CacheTypeFactory mCacheTypeFactory;
private static SourceFactory mSourceFactory;
private AttributeFormatterFactory mAttributeFormatterFactory;
public GeocacheFactory() {
mSourceFactory = new SourceFactory();
mCacheTypeFactory = new CacheTypeFactory();
mAttributeFormatterFactory = new AttributeFormatterFactory(new AttributeFormatterImpl(),
new AttributeFormatterNull());
}
public CacheType cacheTypeFromInt(int cacheTypeIx) {
return mCacheTypeFactory.fromInt(cacheTypeIx);
}
/** Mapping from cacheId to Geocache for all loaded geocaches */
private WeakHashMap<CharSequence, Geocache> mGeocaches =
new WeakHashMap<CharSequence, Geocache>();
/** @return the geocache if it is already loaded, otherwise null */
public Geocache getFromId(CharSequence id) {
return mGeocaches.get(id);
}
//TODO: This method should only be for creating a new geocache in the database
public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain,
int container) {
if (id.length() < 2) {
// ID is missing for waypoints imported from the browser; create a
// new id from the time.
id = String.format("WP%1$tk%1$tM%1$tS", System.currentTimeMillis());
}
if (name == null)
name = "";
Geocache cached = mGeocaches.get(id);
if (cached != null
&& cached.getName().equals(name)
&& cached.getLatitude() == latitude
&& cached.getLongitude() == longitude
&& cached.getSourceType().equals(sourceType)
&& cached.getSourceName().equals(sourceName)
&& cached.getCacheType() == cacheType
&& cached.getDifficulty() == difficulty
&& cached.getTerrain() == terrain
&& cached.getContainer() == container)
return cached;
final AttributeFormatter attributeFormatter = mAttributeFormatterFactory
.getAttributeFormatter(sourceType);
cached = new Geocache(id, name, latitude, longitude, sourceType, sourceName, cacheType,
difficulty, terrain, container, attributeFormatter);
mGeocaches.put(id, cached);
return cached;
}
public Source sourceFromInt(int sourceIx) {
return mSourceFactory.fromInt(sourceIx);
}
/** Remove all cached geocache instances. Future references will reload from the database. */
public void flushCache() {
mGeocaches.clear();
}
public void flushCacheIcons() {
for (Geocache geocache : mGeocaches.values()) {
geocache.flushIcons();
}
}
/** Forces the geocache to be reloaded from the database the next time it is needed. */
public void flushGeocache(CharSequence geocacheId) {
mGeocaches.remove(geocacheId.toString());
}
public Geocache fromCursor(Cursor cursor, SourceNameTranslator translator) {
String sourceName = cursor.getString(4);
CacheType cacheType = cacheTypeFromInt(Integer.parseInt(cursor
.getString(5)));
int difficulty = Integer.parseInt(cursor.getString(6));
int terrain = Integer.parseInt(cursor.getString(7));
int container = Integer.parseInt(cursor.getString(8));
return create(cursor.getString(2), cursor.getString(3), cursor
.getDouble(0), cursor.getDouble(1), translator
.sourceNameToSourceType(sourceName), sourceName, cacheType, difficulty, terrain,
container);
}
}
| Java |
/*
** 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.code.geobeagle;
public class Clock {
public long getCurrentTime() {
return System.currentTimeMillis();
}
} | Java |
package com.google.code.geobeagle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class ErrorDisplayerDi {
static public ErrorDisplayer createErrorDisplayer(Activity activity) {
final OnClickListener mOnClickListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
};
return new ErrorDisplayer(activity, mOnClickListener);
}
}
| Java |
/*
** 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.code.geobeagle.database;
/**
* Database version history:
* 12: Adds tables LABELS and CACHELABELS
* 13: Replace LABELS and CACHELABELS with TAGS and CACHETAGS
*/
public class Database {
public static final String DATABASE_NAME = "GeoBeagle.db";
public static final int DATABASE_VERSION = 13;
public static final String S0_COLUMN_CACHE_TYPE = "CacheType INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_CONTAINER = "Container INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_DELETE_ME = "DeleteMe BOOLEAN NOT NULL Default 1";
public static final String S0_COLUMN_DIFFICULTY = "Difficulty INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_TERRAIN = "Terrain INTEGER NOT NULL Default 0";
public static final String S0_INTENT = "intent";
public static final String SQL_CACHES_DONT_DELETE_ME = "UPDATE CACHES SET DeleteMe = 0 WHERE Source = ?";
public static final String SQL_CLEAR_CACHES = "DELETE FROM CACHES WHERE Source=?";
public static final String SQL_CREATE_CACHE_TABLE_V08 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR);";
public static final String SQL_CREATE_CACHE_TABLE_V10 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ");";
public static final String SQL_CREATE_CACHE_TABLE_V11 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ", "
+ S0_COLUMN_CACHE_TYPE + ", " + S0_COLUMN_CONTAINER + ", " + S0_COLUMN_DIFFICULTY
+ ", " + S0_COLUMN_TERRAIN + ");";
public static final String SQL_CREATE_GPX_TABLE_V10 = "CREATE TABLE GPX ("
+ "Name VARCHAR PRIMARY KEY NOT NULL, ExportTime DATETIME NOT NULL, DeleteMe BOOLEAN NOT NULL);";
//V12:
public static final String SQL_CREATE_TAGS_TABLE_V12 = "CREATE TABLE TAGS ("
+ "Id VARCHAR PRIMARY KEY NOT NULL, Name VARCHAR NOT NULL, Locked BOOLEAN NOT NULL);";
public static final String SQL_CREATE_CACHETAGS_TABLE_V12 = "CREATE TABLE CACHETAGS ("
+ "CacheId VARCHAR NOT NULL, TagId INTEGER NOT NULL);";
public static final String SQL_CREATE_IDX_CACHETAGS = "CREATE INDEX IDX_CACHETAGS on CACHETAGS (CacheId, TagId);";
public static final String SQL_CREATE_IDX_LATITUDE = "CREATE INDEX IDX_LATITUDE on CACHES (Latitude);";
public static final String SQL_CREATE_IDX_LONGITUDE = "CREATE INDEX IDX_LONGITUDE on CACHES (Longitude);";
public static final String SQL_CREATE_IDX_SOURCE = "CREATE INDEX IDX_SOURCE on CACHES (Source);";
public static final String SQL_DELETE_CACHE = "DELETE FROM CACHES WHERE Id=?";
public static final String SQL_DELETE_OLD_CACHES = "DELETE FROM CACHES WHERE DeleteMe = 1";
public static final String SQL_DELETE_OLD_GPX = "DELETE FROM GPX WHERE DeleteMe = 1";
public static final String SQL_DELETE_CACHETAG = "DELETE FROM CACHETAGS WHERE CacheId = ? AND TagId = ?";
public static final String SQL_DELETE_ALL_TAGS = "DELETE FROM CACHETAGS WHERE TagId = ?";
public static final String SQL_DELETE_ALL_CACHES = "DELETE FROM CACHES";
public static final String SQL_DELETE_ALL_GPX = "DELETE FROM GPX";
public static final String SQL_DROP_CACHE_TABLE = "DROP TABLE IF EXISTS CACHES";
public static final String SQL_GPX_DONT_DELETE_ME = "UPDATE GPX SET DeleteMe = 0 WHERE Name = ?";
public static final String SQL_MATCH_NAME_AND_EXPORTED_LATER = "Name = ? AND ExportTime >= ?";
public static final String SQL_REPLACE_CACHE = "REPLACE INTO CACHES "
+ "(Id, Description, Latitude, Longitude, Source, DeleteMe, CacheType, Difficulty, Terrain, Container) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?)";
public static final String SQL_REPLACE_GPX = "REPLACE INTO GPX (Name, ExportTime, DeleteMe) VALUES (?, ?, 0)";
public static final String SQL_REPLACE_TAG = "REPLACE INTO TAGS " + "(Id, Name, Locked) VALUES (?, ?, ?)";
public static final String SQL_REPLACE_CACHETAG = "REPLACE INTO CACHETAGS " + "(CacheId, TagId) VALUES (?, ?)";
public static final String SQL_RESET_DELETE_ME_CACHES = "UPDATE CACHES SET DeleteMe = 1 WHERE Source != '"
+ S0_INTENT + "'";
public static final String SQL_RESET_DELETE_ME_GPX = "UPDATE GPX SET DeleteMe = 1";
public static final String TBL_CACHES = "CACHES";
public static final String TBL_GPX = "GPX";
public static final String TBL_TAGS = "TAGS";
public static final String TBL_CACHETAGS = "CACHETAGS";
}
| Java |
/*
** 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.code.geobeagle.database;
import com.google.code.geobeagle.GeocacheFactory;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Arrays;
public class DatabaseDI {
public static class GeoBeagleSqliteOpenHelper extends SQLiteOpenHelper {
private final OpenHelperDelegate mOpenHelperDelegate;
public GeoBeagleSqliteOpenHelper(Context context) {
super(context, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
mOpenHelperDelegate = new OpenHelperDelegate();
}
public SQLiteWrapper getWritableSqliteWrapper() {
return new SQLiteWrapper(this.getWritableDatabase());
}
@Override
public void onCreate(SQLiteDatabase db) {
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db);
mOpenHelperDelegate.onCreate(sqliteWrapper);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db);
mOpenHelperDelegate.onUpgrade(sqliteWrapper, oldVersion);
}
}
public static class SQLiteWrapper implements ISQLiteDatabase {
private final SQLiteDatabase mSQLiteDatabase;
public SQLiteWrapper(SQLiteDatabase writableDatabase) {
mSQLiteDatabase = writableDatabase;
}
public void beginTransaction() {
mSQLiteDatabase.beginTransaction();
}
public int countResults(String table, String selection, String... selectionArgs) {
Log.d("GeoBeagle", "SQL count results: " + selection + ", "
+ Arrays.toString(selectionArgs));
Cursor cursor = mSQLiteDatabase.query(table, null, selection, selectionArgs, null,
null, null, null);
int count = cursor.getCount();
cursor.close();
return count;
}
public void endTransaction() {
mSQLiteDatabase.endTransaction();
}
public void execSQL(String sql) {
//Log.d("GeoBeagle", "SQL: " + sql);
mSQLiteDatabase.execSQL(sql);
}
public void execSQL(String sql, Object... bindArgs) {
//Log.d("GeoBeagle", "SQL: " + sql + ", " + Arrays.toString(bindArgs));
mSQLiteDatabase.execSQL(sql, bindArgs);
}
public Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs) {
final Cursor query = mSQLiteDatabase.query(table, columns, selection, selectionArgs,
groupBy, orderBy, having, limit);
//Log.d("GeoBeagle", "limit: " + limit + ", query: " + selection);
return query;
}
public Cursor rawQuery(String sql, String[] selectionArgs) {
return mSQLiteDatabase.rawQuery(sql, selectionArgs);
}
public void setTransactionSuccessful() {
mSQLiteDatabase.setTransactionSuccessful();
}
public void close() {
Log.d("GeoBeagle", "----------closing sqlite------");
mSQLiteDatabase.close();
}
public boolean isOpen() {
return mSQLiteDatabase.isOpen();
}
}
public static CacheWriter createCacheWriter(ISQLiteDatabase writableDatabase,
GeocacheFactory geocacheFactory, DbFrontend dbFrontend) {
final SourceNameTranslator dbToGeocacheAdapter = new SourceNameTranslator();
return new CacheWriter(writableDatabase, dbFrontend,
dbToGeocacheAdapter, geocacheFactory);
}
}
| Java |
package com.google.code.geobeagle;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
public class GraphicsGenerator {
private final RatingsGenerator mRatingsGenerator;
private final IconRenderer mIconRenderer;
public GraphicsGenerator(RatingsGenerator ratingsGenerator, IconRenderer iconRenderer) {
mRatingsGenerator = ratingsGenerator;
mIconRenderer = iconRenderer;
}
public static class RatingsGenerator {
public Drawable createRating(Drawable unselected, Drawable halfSelected, Drawable selected,
int rating) {
int width = unselected.getIntrinsicWidth();
int height = unselected.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(5 * width, 16, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
int i = 0;
while (i < rating / 2) {
draw(width, height, c, i++, selected);
}
if (rating % 2 == 1) {
draw(width, height, c, i++, halfSelected);
}
while (i < 5) {
draw(width, height, c, i++, unselected);
}
return new BitmapDrawable(bitmap);
}
private void draw(int width, int height, Canvas c, int i, Drawable drawable) {
drawable.setBounds(width * i, 0, width * (i + 1) - 1, height - 1);
drawable.draw(c);
}
}
public Drawable[] getRatings(Drawable drawables[], int maxRatings) {
Drawable[] ratings = new Drawable[maxRatings];
for (int i = 1; i <= maxRatings; i++) {
ratings[i - 1] = mRatingsGenerator.createRating(drawables[0], drawables[1],
drawables[2], i);
}
return ratings;
}
static interface BitmapCopier {
Bitmap copy(Bitmap source);
int getBottom();
}
static class ListViewBitmapCopier implements BitmapCopier {
public Bitmap copy(Bitmap source) {
int imageHeight = source.getHeight();
int imageWidth = source.getWidth();
Bitmap copy = Bitmap.createBitmap(imageWidth, imageHeight + 5,
Bitmap.Config.ARGB_8888);
int[] pixels = new int[imageWidth * imageHeight];
source.getPixels(pixels, 0, imageWidth, 0, 0, imageWidth, imageHeight);
copy.setPixels(pixels, 0, imageWidth, 0, 0, imageWidth, imageHeight);
return copy;
}
public int getBottom() {
return 0;
}
}
public static class MapViewBitmapCopier implements BitmapCopier {
public Bitmap copy(Bitmap source) {
return source.copy(Bitmap.Config.ARGB_8888, true);
}
public int getBottom() {
return 3;
}
}
public static class IconRenderer {
private final AttributePainter mAttributePainter;
public IconRenderer(AttributePainter attributePainter) {
mAttributePainter = attributePainter;
}
Drawable createOverlay(Geocache geocache, int backdropId, Drawable overlayIcon,
Resources resources, BitmapCopier bitmapCopier) {
Bitmap bitmap = BitmapFactory.decodeResource(resources, backdropId);
Bitmap copy = bitmapCopier.copy(bitmap);
int imageHeight = copy.getHeight();
int imageWidth = copy.getWidth();
int bottom = bitmapCopier.getBottom();
Canvas canvas = new Canvas(copy);
mAttributePainter.drawAttribute(1, bottom, imageHeight, imageWidth, canvas, geocache
.getDifficulty(), Color.argb(255, 0x20, 0x20, 0xFF));
mAttributePainter.drawAttribute(0, bottom, imageHeight, imageWidth, canvas, geocache
.getTerrain(), Color.argb(255, 0xDB, 0xA1, 0x09));
drawOverlay(overlayIcon, imageWidth, canvas);
return new BitmapDrawable(copy);
}
private void drawOverlay(Drawable overlayIcon, int imageWidth, Canvas canvas) {
if (overlayIcon != null) {
overlayIcon.setBounds(imageWidth-1-overlayIcon.getIntrinsicWidth(),
0, imageWidth-1, overlayIcon.getIntrinsicHeight()-1);
overlayIcon.draw(canvas);
}
}
}
public Drawable createIconListView(Geocache geocache, Drawable overlayIcon, Resources resources) {
return mIconRenderer.createOverlay(geocache, geocache.getCacheType().icon(), overlayIcon,
resources, new ListViewBitmapCopier());
}
public Drawable createIconMapView(Geocache geocache, Drawable overlayIcon, Resources resources) {
Drawable iconMap = mIconRenderer.createOverlay(geocache, geocache.getCacheType().iconMap(), overlayIcon, resources,
new MapViewBitmapCopier());
int width = iconMap.getIntrinsicWidth();
int height = iconMap.getIntrinsicHeight();
iconMap.setBounds(-width / 2, -height, width / 2, 0);
return iconMap;
}
public static class AttributePainter {
private final Paint mTempPaint;
private final Rect mTempRect;
public AttributePainter(Paint tempPaint, Rect tempRect) {
mTempPaint = tempPaint;
mTempRect = tempRect;
}
void drawAttribute(int position, int bottom, int imageHeight, int imageWidth,
Canvas canvas, double attribute, int color) {
final int diffWidth = (int)(imageWidth * (attribute / 10.0));
final int MARGIN = 1;
final int THICKNESS = 3;
final int base = imageHeight - bottom - MARGIN;
final int attributeBottom = base - position * (THICKNESS + 1);
final int attributeTop = attributeBottom - THICKNESS;
mTempPaint.setColor(color);
mTempRect.set(0, attributeTop, diffWidth, attributeBottom);
canvas.drawRect(mTempRect, mTempPaint);
}
}
/** Returns a new Drawable that is 'top' over 'bottom'.
* Top is assumed to be smaller and is centered over bottom. */
public Drawable superimpose(Drawable top, Drawable bottom) {
int width = bottom.getIntrinsicWidth();
int height = bottom.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
bottom.setBounds(0, 0, width-1, height-1);
int topWidth = top.getIntrinsicWidth();
int topHeight = top.getIntrinsicHeight();
top.setBounds(width/2 - topWidth/2, height/2 - topHeight/2,
width/2 - topWidth/2 + topWidth, height/2 - topHeight/2 + topHeight);
bottom.draw(c);
top.draw(c);
BitmapDrawable bd = new BitmapDrawable(bitmap);
bd.setBounds(-width/2, -height, width/2, 0); //Necessary!
return bd;
}
}
| Java |
/*
** 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.code.geobeagle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.preference.PreferenceManager;
public class LocationControlDi {
public static GeoFixProvider create(Activity activity) {
if (false) { //Set to true to use fake locations
//return new GeoFixProviderFake(GeoFixProviderFake.CAR_JOURNEY);
return new GeoFixProviderFake(GeoFixProviderFake.LINKOPING);
//return new GeoFixProviderFake(GeoFixProviderFake.TOKYO);
//return new GeoFixProviderFake(GeoFixProviderFake.YOKOHAMA);
} else {
final LocationManager locationManager = (LocationManager)activity
.getSystemService(Context.LOCATION_SERVICE);
final SensorManager sensorManager = (SensorManager)activity
.getSystemService(Context.SENSOR_SERVICE);
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(activity);
return new GeoFixProviderLive(locationManager, sensorManager,
sharedPreferences);
}
}
}
| Java |
/*
** 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.code.geobeagle.cachedetails;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class WriterWrapper {
Writer mWriter;
public void close() throws IOException {
mWriter.close();
}
public void open(String path) throws IOException {
mWriter = new BufferedWriter(new FileWriter(path), 4000);
}
public void write(String str) throws IOException {
try {
mWriter.write(str);
} catch (IOException e) {
throw new IOException("Error writing line '" + str + "'");
}
}
} | Java |
/*
** 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.code.geobeagle.activity;
import com.google.code.geobeagle.activity.ActivityDI.ActivityTypeFactory;
import com.google.code.geobeagle.activity.cachelist.CacheListActivity;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
/** Invoked from SearchOnlineActivity to restore the last GeoBeagle activity */
public class ActivityRestorer {
public static class CacheListRestorer implements Restorer {
private final Activity mActivity;
public CacheListRestorer(Activity activity) {
mActivity = activity;
}
@Override
public void restore() {
mActivity.startActivity(new Intent(mActivity, CacheListActivity.class));
mActivity.finish();
}
}
public static class NullRestorer implements Restorer {
@Override
public void restore() {
}
}
public interface Restorer {
void restore();
}
public static class ViewCacheRestorer implements Restorer {
private final Activity mActivity;
private final SharedPreferences mSharedPreferences;
public ViewCacheRestorer(SharedPreferences sharedPreferences, Activity activity) {
mSharedPreferences = sharedPreferences;
mActivity = activity;
}
@Override
public void restore() {
String id = mSharedPreferences.getString("geocacheId", "");
final Intent intent = new Intent(mActivity, GeoBeagle.class);
intent.putExtra("geocacheId", id).setAction(GeocacheListController.SELECT_CACHE);
mActivity.startActivity(intent);
mActivity.finish();
}
}
private final ActivityTypeFactory mActivityTypeFactory;
private final Restorer[] mRestorers;
private final SharedPreferences mSharedPreferences;
public ActivityRestorer(ActivityTypeFactory activityTypeFactory,
SharedPreferences sharedPreferences, Restorer[] restorers) {
mActivityTypeFactory = activityTypeFactory;
mSharedPreferences = sharedPreferences;
mRestorers = restorers;
}
public void restore(int flags) {
if ((flags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0)
return;
final int iLastActivity = mSharedPreferences.getInt(ActivitySaver.LAST_ACTIVITY,
ActivityType.NONE.toInt());
final ActivityType activityType = mActivityTypeFactory.fromInt(iLastActivity);
mRestorers[activityType.toInt()].restore();
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.Overlay;
import com.google.code.geobeagle.CacheFilter;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection;
import com.google.code.geobeagle.database.CachesProviderDb;
import java.util.List;
public class OverlayManager implements Refresher {
static final int DENSITY_MAP_ZOOM_THRESHOLD = 12;
private final CachePinsOverlayFactory mCachePinsOverlayFactory;
private final DensityOverlay mDensityOverlay;
private final GeoMapView mGeoMapView;
private final List<Overlay> mMapOverlays;
private boolean mUsesDensityMap;
private final CachesProviderDb mCachesProviderDb;
private final FilterTypeCollection mFilterTypeCollection;
private final OverlaySelector mOverlaySelector;
static class OverlaySelector {
boolean selectOverlay(OverlayManager overlayManager, int zoomLevel,
boolean fUsesDensityMap, List<Overlay> mapOverlays,
Overlay densityOverlay,
CachePinsOverlayFactory cachePinsOverlayFactory) {
// Log.d("GeoBeagle", "selectOverlay Zoom: " + zoomLevel);
boolean newZoomUsesDensityMap = zoomLevel < DENSITY_MAP_ZOOM_THRESHOLD;
if (newZoomUsesDensityMap && fUsesDensityMap)
return newZoomUsesDensityMap;
if (newZoomUsesDensityMap) {
mapOverlays.set(0, densityOverlay);
} else {
mapOverlays.set(0, cachePinsOverlayFactory
.getCachePinsOverlay());
}
return newZoomUsesDensityMap;
}
}
public OverlayManager(GeoMapView geoMapView, List<Overlay> mapOverlays,
DensityOverlay densityOverlay,
CachePinsOverlayFactory cachePinsOverlayFactory,
boolean usesDensityMap, CachesProviderDb cachesProviderArea,
FilterTypeCollection filterTypeCollection,
OverlaySelector overlaySelector) {
mGeoMapView = geoMapView;
mMapOverlays = mapOverlays;
mDensityOverlay = densityOverlay;
mCachePinsOverlayFactory = cachePinsOverlayFactory;
mUsesDensityMap = usesDensityMap;
mCachesProviderDb = cachesProviderArea;
mFilterTypeCollection = filterTypeCollection;
mOverlaySelector = overlaySelector;
}
public void selectOverlay() {
mUsesDensityMap = mOverlaySelector.selectOverlay(this, mGeoMapView
.getZoomLevel(), mUsesDensityMap, mMapOverlays,
mDensityOverlay, mCachePinsOverlayFactory);
}
public boolean usesDensityMap() {
return mUsesDensityMap;
}
@Override
public void forceRefresh() {
CacheFilter cacheFilter = mFilterTypeCollection.getActiveFilter();
mCachesProviderDb.setFilter(cacheFilter);
selectOverlay();
// Must be called from the GUI thread:
mGeoMapView.invalidate();
}
@Override
public void refresh() {
selectOverlay();
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI;
import com.google.code.geobeagle.database.CachesProviderLazyArea;
import android.content.Context;
import android.graphics.drawable.Drawable;
import java.util.AbstractList;
public class CachePinsOverlayFactory {
private final CacheItemFactory mCacheItemFactory;
private CachePinsOverlay mCachePinsOverlay;
private final Context mContext;
private final Drawable mDefaultMarker;
private final GeoMapView mGeoMapView;
private CachesProviderLazyArea mLazyArea;
public CachePinsOverlayFactory(GeoMapView geoMapView, Context context,
Drawable defaultMarker, CacheItemFactory cacheItemFactory,
CachePinsOverlay cachePinsOverlay, CachesProviderLazyArea lazyArea) {
mGeoMapView = geoMapView;
mContext = context;
mDefaultMarker = defaultMarker;
mCacheItemFactory = cacheItemFactory;
mCachePinsOverlay = cachePinsOverlay;
mLazyArea = lazyArea;
}
public CachePinsOverlay getCachePinsOverlay() {
//Log.d("GeoBeagle", "CachePinsOverlayFactory.getCachePinsOverlay()");
final CacheListDelegateDI.Timing timing = new CacheListDelegateDI.Timing();
Projection projection = mGeoMapView.getProjection();
GeoPoint newTopLeft = projection.fromPixels(0, 0);
GeoPoint newBottomRight = projection.fromPixels(mGeoMapView.getRight(), mGeoMapView
.getBottom());
timing.start();
double latLow = newBottomRight.getLatitudeE6() / 1.0E6;
double latHigh = newTopLeft.getLatitudeE6() / 1.0E6;
double lonLow = newTopLeft.getLongitudeE6() / 1.0E6;
double lonHigh = newBottomRight.getLongitudeE6() / 1.0E6;
mLazyArea.setBounds(latLow, lonLow, latHigh, lonHigh);
if (!mLazyArea.hasChanged())
return mCachePinsOverlay;
mLazyArea.showToastIfTooManyCaches();
AbstractList<Geocache> list = mLazyArea.getCaches();
mLazyArea.resetChanged();
mCachePinsOverlay = new CachePinsOverlay(mCacheItemFactory, mContext, mDefaultMarker, list);
timing.lap("getCachePinsOverlay took");
return mCachePinsOverlay;
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GraphicsGenerator;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.database.DbFrontend;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
class CacheItemFactory {
private final Resources mResources;
private Geocache mSelected;
private final GraphicsGenerator mGraphicsGenerator;
private final DbFrontend mDbFrontend;
CacheItemFactory(Resources resources, GraphicsGenerator graphicsGenerator,
DbFrontend dbFrontend) {
mResources = resources;
mGraphicsGenerator = graphicsGenerator;
mDbFrontend = dbFrontend;
}
void setSelectedGeocache(Geocache geocache) {
mSelected = geocache;
}
CacheItem createCacheItem(Geocache geocache) {
final CacheItem cacheItem = new CacheItem(geocache.getGeoPoint(), geocache);
Drawable marker = geocache.getIconMap(mResources, mGraphicsGenerator, mDbFrontend);
if (geocache == mSelected) {
marker = mGraphicsGenerator.superimpose(marker, mResources
.getDrawable(R.drawable.glow_40px));
}
cacheItem.setMarker(marker);
return cacheItem;
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.code.geobeagle.Geocache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class DensityMatrix {
public static class DensityPatch {
private int mCacheCount;
private final int mLatLowE6;
private final int mLonLowE6;
public DensityPatch(double latLow, double lonLow) {
mCacheCount = 0;
mLatLowE6 = (int)(latLow * 1E6);
mLonLowE6 = (int)(lonLow * 1E6);
}
public int getAlpha() {
return Math.min(210, 10 + 32 * mCacheCount);
}
public int getCacheCount() {
return mCacheCount;
}
public int getLatLowE6() {
return mLatLowE6;
}
public int getLonLowE6() {
return mLonLowE6;
}
public void setCacheCount(int count) {
mCacheCount = count;
}
}
/** Mapping lat -> (mapping lon -> cache count) */
private TreeMap<Integer, Map<Integer, DensityPatch>> mBuckets = new TreeMap<Integer, Map<Integer, DensityPatch>>();
private double mLatResolution;
private double mLonResolution;
public DensityMatrix(double latResolution, double lonResolution) {
mLatResolution = latResolution;
mLonResolution = lonResolution;
}
public void addCaches(Collection<Geocache> list) {
for (Geocache cache : list) {
incrementBucket(cache.getLatitude(), cache.getLongitude());
}
}
public List<DensityPatch> getDensityPatches() {
ArrayList<DensityPatch> result = new ArrayList<DensityPatch>();
for (Integer latBucket : mBuckets.keySet()) {
Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket);
result.addAll(lonMap.values());
}
return result;
}
private void incrementBucket(double lat, double lon) {
Integer latBucket = (int)Math.floor(lat / mLatResolution);
Integer lonBucket = (int)Math.floor(lon / mLonResolution);
Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket);
if (lonMap == null) {
// Key didn't exist in map
lonMap = new TreeMap<Integer, DensityPatch>();
mBuckets.put(latBucket, lonMap);
}
DensityPatch patch = lonMap.get(lonBucket);
if (patch == null) {
patch = new DensityPatch(latBucket * mLatResolution, lonBucket * mLonResolution);
lonMap.put(lonBucket, patch);
}
patch.setCacheCount(patch.getCacheCount() + 1);
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.IToaster;
import com.google.code.geobeagle.database.CachesProviderLazyArea;
import android.util.Log;
import java.util.AbstractList;
import java.util.List;
class DensityPatchManager {
private List<DensityMatrix.DensityPatch> mDensityPatches;
private final CachesProviderLazyArea mLazyArea;
public static final double RESOLUTION_LATITUDE = 0.01;
public static final double RESOLUTION_LONGITUDE = 0.02;
public static final int RESOLUTION_LATITUDE_E6 = (int)(RESOLUTION_LATITUDE * 1E6);
public static final int RESOLUTION_LONGITUDE_E6 = (int)(RESOLUTION_LONGITUDE * 1E6);
private final IToaster mToaster;
DensityPatchManager(List<DensityMatrix.DensityPatch> patches, CachesProviderLazyArea lazyArea,
IToaster densityOverlayToaster) {
mDensityPatches = patches;
mLazyArea = lazyArea;
mToaster = densityOverlayToaster;
}
public List<DensityMatrix.DensityPatch> getDensityPatches(MapView mMapView) {
Projection projection = mMapView.getProjection();
GeoPoint newTopLeft = projection.fromPixels(0, 0);
GeoPoint newBottomRight = projection.fromPixels(mMapView.getRight(), mMapView.getBottom());
double latLow = newBottomRight.getLatitudeE6() / 1.0E6;
double latHigh = newTopLeft.getLatitudeE6() / 1.0E6;
double lonLow = newTopLeft.getLongitudeE6() / 1.0E6;
double lonHigh = newBottomRight.getLongitudeE6() / 1.0E6;
mLazyArea.setBounds(latLow, lonLow, latHigh, lonHigh);
if (!mLazyArea.hasChanged()) {
return mDensityPatches;
}
AbstractList<Geocache> list = mLazyArea.getCaches();
mToaster.showToast(mLazyArea.tooManyCaches());
mLazyArea.resetChanged();
DensityMatrix densityMatrix = new DensityMatrix(DensityPatchManager.RESOLUTION_LATITUDE,
DensityPatchManager.RESOLUTION_LONGITUDE);
densityMatrix.addCaches(list);
mDensityPatches = densityMatrix.getDensityPatches();
Log.d("GeoBeagle", "Density patches:" + mDensityPatches.size());
return mDensityPatches;
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.ActionStaticLabel;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.actions.MenuActions;
import android.content.res.Resources;
import android.view.Menu;
import android.view.MenuItem;
public class GeoMapActivityDelegate {
public static class MenuActionCenterLocation extends ActionStaticLabel
implements MenuAction {
private final MapController mMapController;
private final MyLocationOverlay mMyLocationOverlay;
public MenuActionCenterLocation(Resources resources, MapController mapController,
MyLocationOverlay myLocationOverlay) {
super(resources, R.string.menu_center_location);
mMapController = mapController;
mMyLocationOverlay = myLocationOverlay;
}
@Override
public void act() {
GeoPoint geopoint = mMyLocationOverlay.getMyLocation();
if (geopoint != null)
mMapController.animateTo(geopoint);
}
}
public static class MenuActionToggleSatellite implements MenuAction {
private final MapView mMapView;
public MenuActionToggleSatellite(MapView mapView) {
mMapView = mapView;
}
@Override
public void act() {
mMapView.setSatellite(!mMapView.isSatellite());
}
@Override
public String getLabel() {
int stringId = mMapView.isSatellite() ? R.string.map_view : R.string.menu_toggle_satellite;
return mMapView.getResources().getString(stringId);
}
}
private final MenuActions mMenuActions;
public GeoMapActivityDelegate(MenuActions menuActions) {
mMenuActions = menuActions;
}
public boolean onCreateOptionsMenu(Menu menu) {
return mMenuActions.onCreateOptionsMenu(menu);
}
public boolean onMenuOpened(Menu menu) {
return mMenuActions.onMenuOpened(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
return mMenuActions.act(item.getItemId());
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI;
import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import java.util.List;
public class DensityOverlayDelegate {
private static final double RESOLUTION_LATITUDE_E6 = (DensityPatchManager.RESOLUTION_LATITUDE * 1E6);
private static final double RESOLUTION_LONGITUDE_E6 = (DensityPatchManager.RESOLUTION_LONGITUDE * 1E6);
private final Paint mPaint;
private final Rect mPatchRect;
private final Point mScreenBottomRight;
private final Point mScreenTopLeft;
private final CacheListDelegateDI.Timing mTiming;
private final DensityPatchManager mDensityPatchManager;
public DensityOverlayDelegate(Rect patchRect, Paint paint, Point screenLow, Point screenHigh,
DensityPatchManager densityPatchManager) {
mTiming = new CacheListDelegateDI.Timing();
mPatchRect = patchRect;
mPaint = paint;
mScreenTopLeft = screenLow;
mScreenBottomRight = screenHigh;
mDensityPatchManager = densityPatchManager;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (shadow)
return; // No shadow layer
// Log.d("GeoBeagle", ">>>>>>>>>>Starting draw");
List<DensityMatrix.DensityPatch> densityPatches = mDensityPatchManager
.getDensityPatches(mapView);
mTiming.start();
final Projection projection = mapView.getProjection();
final GeoPoint newGeoTopLeft = projection.fromPixels(0, 0);
final GeoPoint newGeoBottomRight = projection.fromPixels(mapView.getRight(), mapView
.getBottom());
projection.toPixels(newGeoTopLeft, mScreenTopLeft);
projection.toPixels(newGeoBottomRight, mScreenBottomRight);
final int topLatitudeE6 = newGeoTopLeft.getLatitudeE6();
final int leftLongitudeE6 = newGeoTopLeft.getLongitudeE6();
final int bottomLatitudeE6 = newGeoBottomRight.getLatitudeE6();
final int rightLongitudeE6 = newGeoBottomRight.getLongitudeE6();
final double pixelsPerLatE6Degrees = (double)(mScreenBottomRight.y - mScreenTopLeft.y)
/ (double)(bottomLatitudeE6 - topLatitudeE6);
final double pixelsPerLonE6Degrees = (double)(mScreenBottomRight.x - mScreenTopLeft.x)
/ (double)(rightLongitudeE6 - leftLongitudeE6);
int patchCount = 0;
for (DensityPatch patch : densityPatches) {
final int patchLatLowE6 = patch.getLatLowE6();
final int patchLonLowE6 = patch.getLonLowE6();
int xOffset = (int)((patchLonLowE6 - leftLongitudeE6) * pixelsPerLonE6Degrees);
int xEnd = (int)((patchLonLowE6 + RESOLUTION_LONGITUDE_E6 - leftLongitudeE6) * pixelsPerLonE6Degrees);
int yOffset = (int)((patchLatLowE6 - topLatitudeE6) * pixelsPerLatE6Degrees);
int yEnd = (int)((patchLatLowE6 + RESOLUTION_LATITUDE_E6 - topLatitudeE6) * pixelsPerLatE6Degrees);
mPatchRect.set(xOffset, yEnd, xEnd, yOffset);
// Log.d("GeoBeagle", "patchrect: " + mPatchRect.bottom + ", " +
// mPatchRect.left
// + ", " + mPatchRect.top + ", " + mPatchRect.right);
mPaint.setAlpha(patch.getAlpha());
canvas.drawRect(mPatchRect, mPaint);
patchCount++;
}
// mTiming.lap("Done drawing");
// Log.d("GeoBeagle", "patchcount: " + patchCount);
}
}
| Java |
package com.google.code.geobeagle.activity.filterlist;
import com.google.code.geobeagle.CacheFilter;
import com.google.code.geobeagle.Tags;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import java.util.ArrayList;
public class FilterTypeCollection {
private static final String FILTER_PREFS = "Filter";
private final Activity mActivity;
private ArrayList<CacheFilter> mFilterTypes = new ArrayList<CacheFilter>();
public FilterTypeCollection(Activity activity) {
mActivity = activity;
load();
}
/** Loads/reloads the list of filters from the Preferences */
private void load() {
mFilterTypes.clear();
SharedPreferences prefs = mActivity.getSharedPreferences(FILTER_PREFS, 0);
String ids = prefs.getString("FilterList", "");
String[] idArray = ids.split(", ");
if (idArray.length == 1 && idArray[0].equals("")) {
//No filters were registered. Setup the default ones
firstSetup();
} else {
for (String id : idArray) {
mFilterTypes.add(new CacheFilter(id, mActivity));
}
}
}
private void firstSetup() {
Log.i("GeoBeagle", "FilterTypeCollection first setup");
{ FilterPreferences pref = new FilterPreferences("All caches");
pref.setBoolean("Waypoints", false);
add(new CacheFilter("All", mActivity, pref));
}
{ FilterPreferences favoritesPref = new FilterPreferences("Favorites");
favoritesPref.setString("FilterTags",
Integer.toString(Tags.FAVORITES));
add(new CacheFilter("Favorites", mActivity, favoritesPref));
}
{ FilterPreferences pref = new FilterPreferences("Custom 1");
pref.setBoolean("Waypoints", false);
add(new CacheFilter("Filter1", mActivity, pref));
}
{ FilterPreferences pref = new FilterPreferences("Custom 2");
pref.setBoolean("Waypoints", false);
add(new CacheFilter("Filter2", mActivity, pref));
}
{ FilterPreferences pref = new FilterPreferences("Custom 3");
pref.setBoolean("Waypoints", false);
add(new CacheFilter("Filter3", mActivity, pref));
}
/*
{ FilterPreferences foundPref = new FilterPreferences("Found");
foundPref.setInteger("FilterTag", Tags.FOUND);
add(new CacheFilter("Found", mActivity, foundPref));
}
{ FilterPreferences dnfPref = new FilterPreferences("Did Not Find");
dnfPref.setInteger("FilterTag", Tags.DNF);
add(new CacheFilter("DNF", mActivity, dnfPref));
}
*/
String filterList = null;
for (CacheFilter cacheFilter : mFilterTypes) {
cacheFilter.saveToPreferences();
if (filterList == null)
filterList = cacheFilter.mId;
else
filterList = filterList + ", " + cacheFilter.mId;
}
SharedPreferences prefs = mActivity.getSharedPreferences(FILTER_PREFS, 0);
Editor editor = prefs.edit();
editor.putString("FilterList", filterList);
editor.commit();
}
private void add(CacheFilter cacheFilter) {
mFilterTypes.add(cacheFilter);
}
private CacheFilter getFromId(String id) {
for (CacheFilter cacheFilter : mFilterTypes)
if (cacheFilter.mId.equals(id))
return cacheFilter;
return null;
}
public CacheFilter getActiveFilter() {
SharedPreferences prefs = mActivity.getSharedPreferences(FILTER_PREFS, 0);
String id = prefs.getString("ActiveFilter", "All");
return getFromId(id);
}
public void setActiveFilter(CacheFilter cacheFilter) {
SharedPreferences prefs = mActivity.getSharedPreferences(FILTER_PREFS, 0);
Editor editor = prefs.edit();
editor.putString("ActiveFilter", cacheFilter.mId);
editor.commit();
}
public int getCount() {
return mFilterTypes.size();
}
public CacheFilter get(int position) {
return mFilterTypes.get(position);
}
public int getIndexOf(CacheFilter cacheFilter) {
return mFilterTypes.indexOf(cacheFilter);
}
}
| Java |
package com.google.code.geobeagle.activity.filterlist;
import com.google.code.geobeagle.CacheFilter;
import com.google.code.geobeagle.R;
//import com.google.code.geobeagle.R;
import android.app.ListActivity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FilterListActivityDelegate {
private static class FilterListAdapter extends BaseAdapter {
private final FilterTypeCollection mFilterTypeCollection;
private LayoutInflater mInflater;
private Bitmap mIconSelected;
private Bitmap mIconUnselected;
/** -1 means no row is selected */
private int mSelectionIndex = -1;
public FilterListAdapter(Context context, FilterTypeCollection filterTypeCollection) {
mFilterTypeCollection = filterTypeCollection;
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
Resources resources = context.getResources();
mIconSelected = BitmapFactory.decodeResource(resources,
R.drawable.btn_radio_on);
//android.R.drawable.radiobutton_on_background);
mIconUnselected = BitmapFactory.decodeResource(resources,
R.drawable.btn_radio_off);
//android.R.drawable.radiobutton_off_background);
}
@Override
public int getCount() {
return mFilterTypeCollection.getCount();
}
@Override
public Object getItem(int position) {
return mFilterTypeCollection.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = mInflater.inflate(R.layout.filterlist_row, null);
ImageView image = (ImageView) view.findViewById(R.id.icon);
if (position == mSelectionIndex)
image.setImageBitmap(mIconSelected);
else
image.setImageBitmap(mIconUnselected);
TextView text = (TextView) view.findViewById(R.id.txt_filter);
text.setText(mFilterTypeCollection.get(position).getName());
return view;
}
public void setSelection(int index) {
mSelectionIndex = index;
notifyDataSetChanged();
}
}
private FilterTypeCollection mFilterTypeCollection;
private FilterListAdapter mAdapter;
public void onCreate(ListActivity activity) {
mFilterTypeCollection = new FilterTypeCollection(activity);
mAdapter = new FilterListAdapter(activity, mFilterTypeCollection);
int ix = mFilterTypeCollection.getIndexOf(mFilterTypeCollection.getActiveFilter());
mAdapter.setSelection(ix);
activity.setListAdapter(mAdapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
CacheFilter cacheFilter = mFilterTypeCollection.get(position);
mFilterTypeCollection.setActiveFilter(cacheFilter);
mAdapter.setSelection(position);
}
}
| Java |
package com.google.code.geobeagle.activity.filterlist;
import android.content.SharedPreferences;
import java.util.HashMap;
import java.util.Map;
/** Used to simulate a SharedPreferences when initializing
* a FilterType for the first time. */
class FilterPreferences implements SharedPreferences {
private HashMap<String, Object> mValues;
public FilterPreferences(String filterName) {
mValues = new HashMap<String, Object>();
setString("FilterName", filterName);
};
public void setBoolean(String key, boolean value) {
mValues.put(key, new Boolean(value));
}
public void setString(String key, String value) {
mValues.put(key, value);
}
public void setInteger(String key, int value) {
mValues.put(key, new Integer(value));
}
@Override
public boolean contains(String key) {
return mValues.containsKey(key);
}
@Override
public Editor edit() {
return null;
}
@Override
public Map<String, ?> getAll() {
return mValues;
}
@Override
public boolean getBoolean(String key, boolean defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (Boolean)value;
}
@Override
public float getFloat(String key, float defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (Float)value;
}
@Override
public int getInt(String key, int defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (Integer)value;
}
@Override
public long getLong(String key, long defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (Long)value;
}
@Override
public String getString(String key, String defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (String)value;
}
@Override
public void registerOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
}
@Override
public void unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
}
}
| Java |
/*
** 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.code.geobeagle.activity.main;
import android.net.UrlQuerySanitizer;
import android.net.UrlQuerySanitizer.ValueSanitizer;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
static final double APPROX_EQUALS_PRECISION = 1.0e-9;
public static final String[] geocachingQueryParam = new String[] {
"q"
};
// #Wildwood Park, Saratoga, CA(The Nut Case #89882)
private static final Pattern PAT_ATLASQUEST = Pattern.compile(".*\\((.*)#(.*)\\)");
private static final Pattern PAT_ATSIGN_FORMAT = Pattern.compile("([^@]*)@(.*)");
private static final Pattern PAT_COORD_COMPONENT = Pattern.compile("([\\d.]+)[^\\d]*");
private static final Pattern PAT_LATLON = Pattern
.compile("([NS]?[^NSEW,]*[NS]?),?\\s*([EW]?.*)");
private static final Pattern PAT_LATLONDEC = Pattern.compile("([\\d.]+)\\s+([\\d.]+)");
private static final Pattern PAT_NEGSIGN = Pattern.compile("[-WS]");
private static final Pattern PAT_PAREN_FORMAT = Pattern.compile("([^(]*)\\(([^)]*).*");
private static final Pattern PAT_SIGN = Pattern.compile("[-EWNS]");
public static CharSequence formatDegreesAsDecimalDegreesString(double fDegrees) {
final double fAbsDegrees = Math.abs(fDegrees);
final int dAbsDegrees = (int)fAbsDegrees;
return String.format(Locale.US, (fDegrees < 0 ? "-" : "")
+ "%1$d %2$06.3f", dAbsDegrees,
60.0 * (fAbsDegrees - dAbsDegrees));
}
public static double parseCoordinate(CharSequence string) {
int sign = 1;
final Matcher negsignMatcher = PAT_NEGSIGN.matcher(string);
if (negsignMatcher.find()) {
sign = -1;
}
final Matcher signMatcher = PAT_SIGN.matcher(string);
string = signMatcher.replaceAll("");
final Matcher dmsMatcher = PAT_COORD_COMPONENT.matcher(string);
double degrees = 0.0;
for (double scale = 1.0; scale <= 3600.0 && dmsMatcher.find(); scale *= 60.0) {
degrees += Double.parseDouble(dmsMatcher.group(1)) / scale;
}
return sign * degrees;
}
public static CharSequence[] parseDescription(CharSequence string) {
Matcher matcher = PAT_ATLASQUEST.matcher(string);
if (matcher.matches())
return new CharSequence[] {
"LB" + matcher.group(2).trim(), matcher.group(1).trim()
};
return new CharSequence[] {
string, ""
};
}
public static CharSequence parseHttpUri(String query, UrlQuerySanitizer sanitizer,
ValueSanitizer valueSanitizer) {
sanitizer.registerParameters(geocachingQueryParam, valueSanitizer);
sanitizer.parseQuery(query);
return sanitizer.getValue("q");
}
public static CharSequence[] splitCoordsAndDescription(CharSequence location) {
Matcher matcher = PAT_ATSIGN_FORMAT.matcher(location);
if (matcher.matches()) {
return new CharSequence[] {
matcher.group(2).trim(), matcher.group(1).trim()
};
}
matcher = PAT_PAREN_FORMAT.matcher(location);
if (matcher.matches()) {
return new CharSequence[] {
matcher.group(1).trim(), matcher.group(2).trim()
};
}
// No description.
return new CharSequence[] {
location, ""
};
}
public static CharSequence[] splitLatLon(CharSequence string) {
Matcher matcherDecimal = PAT_LATLONDEC.matcher(string);
if (matcherDecimal.matches()) {
return new String[] {
matcherDecimal.group(1).trim(), matcherDecimal.group(2).trim()
};
}
Matcher matcher = PAT_LATLON.matcher(string);
matcher.matches();
return new String[] {
matcher.group(1).trim(), matcher.group(2).trim()
};
}
public static CharSequence[] splitLatLonDescription(CharSequence location) {
CharSequence coordsAndDescription[] = splitCoordsAndDescription(location);
CharSequence latLon[] = splitLatLon(coordsAndDescription[0]);
CharSequence[] parseDescription = parseDescription(coordsAndDescription[1]);
return new CharSequence[] {
latLon[0], latLon[1], parseDescription[0], parseDescription[1]
};
}
/** Rounding errors might make equal floating point numbers seem to differ. */
public static boolean approxEquals(double a, double b) {
return (Math.abs(a - b) < APPROX_EQUALS_PRECISION);
}
}
| Java |
/*
* Copyright (C) 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.code.geobeagle.activity.main;
/**
* Library for some use useful latitude/longitude math
*/
public class GeoUtils {
private static int EARTH_RADIUS_KM = 6371;
public static int MILLION = 1000000;
/**
* Computes the distance in kilometers between two points on Earth.
*
* @param lat1 Latitude of the first point
* @param lon1 Longitude of the first point
* @param lat2 Latitude of the second point
* @param lon2 Longitude of the second point
* @return Distance between the two points in kilometers.
*/
public static double distanceKm(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad)
* Math.cos(lat2Rad) * Math.cos(deltaLonRad))
* EARTH_RADIUS_KM;
}
/**
* Computes the distance in kilometers between two points on Earth.
*
* @param p1 First point
* @param p2 Second point
* @return Distance between the two points in kilometers.
*/
//
// public static double distanceKm(GeoPoint p1, GeoPoint p2) {
// double lat1 = p1.getLatitudeE6() / (double)MILLION;
// double lon1 = p1.getLongitudeE6() / (double)MILLION;
// double lat2 = p2.getLatitudeE6() / (double)MILLION;
// double lon2 = p2.getLongitudeE6() / (double)MILLION;
//
// return distanceKm(lat1, lon1, lat2, lon2);
// }
/**
* Computes the bearing in degrees between two points on Earth.
*
* @param p1 First point
* @param p2 Second point
* @return Bearing between the two points in degrees. A value of 0 means due
* north.
*/
// public static double bearing(GeoPoint p1, GeoPoint p2) {
// double lat1 = p1.getLatitudeE6() / (double) MILLION;
// double lon1 = p1.getLongitudeE6() / (double) MILLION;
// double lat2 = p2.getLatitudeE6() / (double) MILLION;
// double lon2 = p2.getLongitudeE6() / (double) MILLION;
//
// return bearing(lat1, lon1, lat2, lon2);
// }
/**
* Computes the bearing in degrees between two points on Earth.
*
* @param lat1 Latitude of the first point
* @param lon1 Longitude of the first point
* @param lat2 Latitude of the second point
* @param lon2 Longitude of the second point
* @return Bearing between the two points in degrees. A value of 0 means due
* north.
*/
public static double bearing(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad);
double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad)
* Math.cos(deltaLonRad);
return radToBearing(Math.atan2(y, x));
}
/**
* Converts an angle in radians to degrees
*/
public static double radToBearing(double rad) {
return (Math.toDegrees(rad) + 360) % 360;
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import android.content.SharedPreferences;
public class CacheLogger implements ICacheLogger {
private final FileLogger mFileLogger;
private final SharedPreferences mSharedPreferences;
private final SmsLogger mSmsLogger;
public CacheLogger(SharedPreferences sharedPreferences, FileLogger fileLogger,
SmsLogger smsLogger) {
mSharedPreferences = sharedPreferences;
mFileLogger = fileLogger;
mSmsLogger = smsLogger;
}
@Override
public void log(CharSequence geocacheId, CharSequence logText, boolean dnf) {
final boolean fFieldNoteTextFile = mSharedPreferences.getBoolean(
"field-note-text-file", false);
if (fFieldNoteTextFile)
mFileLogger.log(geocacheId, logText, dnf);
else
mSmsLogger.log(geocacheId, logText, dnf);
}
} | Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import android.app.Dialog;
public interface DialogHelper {
public abstract void configureEditor();
public abstract void configureDialogText(Dialog dialog);
}
| Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import android.content.res.Resources;
public class FieldnoteStringsFVsDnf {
private final Resources mResources;
public FieldnoteStringsFVsDnf(Resources resources) {
mResources = resources;
}
String getString(int id, boolean dnf) {
return mResources.getStringArray(id)[dnf ? 0 : 1];
}
} | Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.R;
import android.app.Dialog;
import android.content.Context;
import android.widget.TextView;
public class DialogHelperFile implements DialogHelper {
private Context mContext;
private final TextView mFieldnoteCaveat;
public DialogHelperFile(TextView fieldNoteCaveat, Context context) {
mFieldnoteCaveat = fieldNoteCaveat;
mContext = context;
}
@Override
public void configureEditor() {
}
@Override
public void configureDialogText(Dialog dialog) {
mFieldnoteCaveat.setText(String.format(mContext.getString(R.string.field_note_file_caveat),
FieldnoteLogger.FIELDNOTES_FILE));
dialog.setTitle(R.string.log_cache_to_file);
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.R;
import android.app.Dialog;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.widget.EditText;
import android.widget.TextView;
public class DialogHelperSms implements DialogHelper {
private final EditText mEditText;
private final boolean mFDnf;
private final TextView mFieldnoteCaveat;
private final FieldnoteStringsFVsDnf mFieldnoteStringsFVsDnf;
private final int mGeocacheIdLength;
public DialogHelperSms(int geocacheIdLength, FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf,
EditText editText, boolean dnf, TextView fieldnoteCaveat) {
mGeocacheIdLength = geocacheIdLength;
mFieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf;
mEditText = editText;
mFDnf = dnf;
mFieldnoteCaveat = fieldnoteCaveat;
}
@Override
public void configureEditor() {
final LengthFilter lengthFilter = new LengthFilter(
160 - (mGeocacheIdLength + 1 + mFieldnoteStringsFVsDnf.getString(
R.array.fieldnote_code, mFDnf).length()));
mEditText.setFilters(new InputFilter[] {
lengthFilter
});
}
@Override
public void configureDialogText(Dialog dialog) {
mFieldnoteCaveat.setText(R.string.sms_caveat);
dialog.setTitle(R.string.log_cache_with_sms);
}
} | Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Toaster;
import com.google.code.geobeagle.activity.main.DateFormatter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
/**
* Writes lines formatted like:
*
* <pre>
* GC1FX1A,2008-09-27T21:04Z, Found it,"log text"
* </pre>
*/
public class FileLogger implements ICacheLogger {
private final Toaster mErrorToaster;
private final FieldnoteStringsFVsDnf mFieldnoteStringsFVsDnf;
private final DateFormatter mSimpleDateFormat;
public FileLogger(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, DateFormatter simpleDateFormat,
Toaster errorToaster) {
mFieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf;
mSimpleDateFormat = simpleDateFormat;
mErrorToaster = errorToaster;
}
public void log(CharSequence geocacheId, CharSequence logText, boolean dnf) {
try {
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(
FieldnoteLogger.FIELDNOTES_FILE, true), "UTF-16");
final Date date = new Date();
final String formattedDate = mSimpleDateFormat.format(date);
final String logLine = String.format("%1$s,%2$s,%3$s,\"%4$s\"\n", geocacheId,
formattedDate, mFieldnoteStringsFVsDnf.getString(R.array.fieldnote_file_code,
dnf), logText.toString());
writer.write(logLine);
writer.close();
} catch (IOException e) {
mErrorToaster.showToast();
}
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
interface ICacheLogger {
public void log(CharSequence geocacheId, CharSequence logText, boolean dnf);
} | Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.R;
import android.content.Context;
import android.content.Intent;
public class SmsLogger implements ICacheLogger {
private final Context mContext;
private final FieldnoteStringsFVsDnf mFieldNoteStringsFoundVsDnf;
public SmsLogger(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, Context context) {
mFieldNoteStringsFoundVsDnf = fieldnoteStringsFVsDnf;
mContext = context;
}
@Override
public void log(CharSequence geocacheId, CharSequence logText, boolean dnf) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("address", "41411");
sendIntent.putExtra("sms_body", mFieldNoteStringsFoundVsDnf.getString(
R.array.fieldnote_code, dnf)
+ geocacheId + " " + logText);
sendIntent.setType("vnd.android-dir/mms-sms");
mContext.startActivity(sendIntent);
}
} | Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.Tags;
import com.google.code.geobeagle.database.DbFrontend;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.widget.EditText;
public class FieldnoteLogger {
// TODO: share one onClickCancel across app.
public static class OnClickCancel implements OnClickListener {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
public static class OnClickOk implements OnClickListener {
private final CacheLogger mCacheLogger;
private final boolean mDnf;
private final EditText mEditText;
private final DbFrontend mDbFrontend;
private final CharSequence mGeocacheId;
public OnClickOk(CharSequence geocacheId, EditText editText,
CacheLogger cacheLogger, DbFrontend dbFrontend, boolean dnf) {
mGeocacheId = geocacheId;
mEditText = editText;
mCacheLogger = cacheLogger;
mDbFrontend = dbFrontend;
mDnf = dnf;
}
@Override
public void onClick(DialogInterface arg0, int arg1) {
mCacheLogger.log(mGeocacheId, mEditText.getText(), mDnf);
mDbFrontend.setGeocacheTag(mGeocacheId, Tags.DNF, mDnf);
mDbFrontend.setGeocacheTag(mGeocacheId, Tags.FOUND, !mDnf);
}
}
static final String FIELDNOTES_FILE = "/sdcard/GeoBeagleFieldNotes.txt";
private final DialogHelperCommon mDialogHelperCommon;
private final DialogHelperFile mDialogHelperFile;
private final DialogHelperSms mDialogHelperSms;
public FieldnoteLogger(DialogHelperCommon dialogHelperCommon,
DialogHelperFile dialogHelperFile, DialogHelperSms dialogHelperSms) {
mDialogHelperSms = dialogHelperSms;
mDialogHelperFile = dialogHelperFile;
mDialogHelperCommon = dialogHelperCommon;
}
public void onPrepareDialog(Dialog dialog, SharedPreferences defaultSharedPreferences,
String localDate) {
final boolean fieldNoteTextFile = defaultSharedPreferences.getBoolean(
"field-note-text-file", false);
DialogHelper dialogHelper = fieldNoteTextFile ? mDialogHelperFile : mDialogHelperSms;
dialogHelper.configureDialogText(dialog);
mDialogHelperCommon.configureDialogText();
dialogHelper.configureEditor();
mDialogHelperCommon.configureEditor(localDate);
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.R;
import android.text.util.Linkify;
import android.widget.EditText;
import android.widget.TextView;
public class DialogHelperCommon {
private final boolean mDnf;
private final EditText mEditText;
private final TextView mFieldnoteCaveat;
private final FieldnoteStringsFVsDnf mFieldnoteStringsFVsDnf;
public DialogHelperCommon(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, EditText editText,
boolean dnf, TextView fieldnoteCaveat) {
mFieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf;
mDnf = dnf;
mEditText = editText;
mFieldnoteCaveat = fieldnoteCaveat;
}
public void configureDialogText() {
Linkify.addLinks(mFieldnoteCaveat, Linkify.WEB_URLS);
}
public void configureEditor(String localDate) {
final String defaultMessage = mFieldnoteStringsFVsDnf.getString(R.array.default_msg, mDnf);
final String msg = String.format("(%1$s/%2$s) %3$s", localDate, mFieldnoteStringsFVsDnf
.getString(R.array.geobeagle_sig, mDnf), defaultMessage);
mEditText.setText(msg);
final int len = msg.length();
mEditText.setSelection(len - defaultMessage.length(), len);
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Provider;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.view.View;
public class WebPageAndDetailsButtonEnabler {
interface CheckButton {
public void check(Geocache geocache);
}
public static class CheckButtons {
private final CheckButton[] mCheckButtons;
public CheckButtons(CheckButton[] checkButtons) {
mCheckButtons = checkButtons;
}
public void check(Geocache geocache) {
for (CheckButton checkButton : mCheckButtons) {
checkButton.check(geocache);
}
}
}
public static class CheckDetailsButton implements CheckButton {
private final View mDetailsButton;
public CheckDetailsButton(View checkDetailsButton) {
mDetailsButton = checkDetailsButton;
}
public void check(Geocache geocache) {
mDetailsButton.setEnabled(geocache.getSourceType() == Source.GPX);
}
}
public static class CheckWebPageButton implements CheckButton {
private final View mWebPageButton;
public CheckWebPageButton(View webPageButton) {
mWebPageButton = webPageButton;
}
public void check(Geocache geocache) {
final Provider contentProvider = geocache.getContentProvider();
mWebPageButton.setEnabled(contentProvider == Provider.GROUNDSPEAK
|| contentProvider == GeocacheFactory.Provider.ATLAS_QUEST
|| contentProvider == GeocacheFactory.Provider.OPENCACHING);
}
}
private final CheckButtons mCheckButtons;
private final GeoBeagle mGeoBeagle;
public WebPageAndDetailsButtonEnabler(GeoBeagle geoBeagle, CheckButtons checkButtons) {
mGeoBeagle = geoBeagle;
mCheckButtons = checkButtons;
}
public void check() {
mCheckButtons.check(mGeoBeagle.getGeocache());
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import com.google.code.geobeagle.cachedetails.CacheDetailsLoader;
import android.app.AlertDialog.Builder;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
public class CacheDetailsOnClickListener implements View.OnClickListener {
private final Builder mAlertDialogBuilder;
private final CacheDetailsLoader mCacheDetailsLoader;
private final LayoutInflater mEnv;
private final GeoBeagle mGeoBeagle;
public CacheDetailsOnClickListener(GeoBeagle geoBeagle, Builder alertDialogBuilder,
LayoutInflater env, CacheDetailsLoader cacheDetailsLoader) {
mAlertDialogBuilder = alertDialogBuilder;
mEnv = env;
mCacheDetailsLoader = cacheDetailsLoader;
mGeoBeagle = geoBeagle;
}
public void onClick(View v) {
View detailsView = mEnv.inflate(R.layout.cache_details, null);
CharSequence id = mGeoBeagle.getGeocache().getId();
mAlertDialogBuilder.setTitle(id);
mAlertDialogBuilder.setView(detailsView);
WebView webView = (WebView)detailsView.findViewById(R.id.webview);
webView.loadDataWithBaseURL(null, mCacheDetailsLoader.load(id), "text/html", "utf-8",
"about:blank");
mAlertDialogBuilder.create().show();
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.CacheAction;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.content.ActivityNotFoundException;
import android.view.View;
import android.view.View.OnClickListener;
public class CacheButtonOnClickListener implements OnClickListener {
private final CacheAction mCacheAction;
private final ErrorDisplayer mErrorDisplayer;
private final String mActivityNotFoundErrorMessage;
private final GeoBeagle mGeoBeagle;
public CacheButtonOnClickListener(CacheAction cacheAction,
GeoBeagle geoBeagle,
String errorMessage,
ErrorDisplayer errorDisplayer) {
mCacheAction = cacheAction;
mGeoBeagle = geoBeagle;
mErrorDisplayer = errorDisplayer;
mActivityNotFoundErrorMessage = errorMessage;
}
public void onClick(View view) {
Geocache geocache = mGeoBeagle.getGeocache();
try {
mCacheAction.act(geocache);
} catch (final ActivityNotFoundException e) {
mErrorDisplayer.displayError(R.string.error2, e.getMessage(),
mActivityNotFoundErrorMessage);
} catch (final Exception e) {
mErrorDisplayer.displayError(R.string.error1, e.getMessage());
}
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Tags;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.database.DbFrontend;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
/** Handles the star graphics showing if the geocache is a favorite */
public class FavoriteView extends ImageView {
public static class FavoriteState {
private final DbFrontend mDbFrontend;
private final CharSequence mGeocacheId;
private boolean mIsFavorite;
public FavoriteState(DbFrontend dbFrontend, CharSequence geocacheId) {
mDbFrontend = dbFrontend;
mGeocacheId = geocacheId;
mIsFavorite = dbFrontend.geocacheHasTag(geocacheId, Tags.FAVORITES);
}
public boolean isFavorite() {
return mIsFavorite;
}
public void toggleFavorite() {
mIsFavorite = !mIsFavorite;
mDbFrontend
.setGeocacheTag(mGeocacheId, Tags.FAVORITES, mIsFavorite);
}
}
public static class FavoriteViewDelegate {
private final FavoriteState mFavoriteState;
private final FavoriteView mFavoriteView;
public FavoriteViewDelegate(FavoriteView favoriteView,
FavoriteState favoriteState) {
mFavoriteView = favoriteView;
mFavoriteState = favoriteState;
}
void toggleFavorite() {
mFavoriteState.toggleFavorite();
updateImage();
}
void updateImage() {
mFavoriteView
.setImageResource(mFavoriteState.isFavorite() ? R.drawable.btn_rating_star_on_normal
: R.drawable.btn_rating_star_off_normal);
}
}
static class OnFavoriteClick implements OnClickListener {
private final FavoriteView mFavoriteView;
OnFavoriteClick(FavoriteView favoriteView) {
mFavoriteView = favoriteView;
}
@Override
public void onClick(View v) {
mFavoriteView.toggleFavorite();
}
}
private FavoriteViewDelegate mFavoriteViewDelegate;
public FavoriteView(Context context) {
super(context);
setOnClickListener(new OnFavoriteClick(this));
}
public FavoriteView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnClickListener(new OnFavoriteClick(this));
}
public FavoriteView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setOnClickListener(new OnFavoriteClick(this));
}
public void setGeocache(FavoriteViewDelegate favoriteViewDelegate) {
mFavoriteViewDelegate = favoriteViewDelegate;
mFavoriteViewDelegate.updateImage();
}
void toggleFavorite() {
mFavoriteViewDelegate.toggleFavorite();
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.main.GeoUtils;
import com.google.code.geobeagle.activity.main.RadarView;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class GeocacheViewer {
public interface AttributeViewer {
void setImage(int attributeValue);
}
public static class LabelledAttributeViewer implements AttributeViewer {
private final AttributeViewer mUnlabelledAttributeViewer;
private final TextView mLabel;
public LabelledAttributeViewer(TextView label, AttributeViewer unlabelledAttributeViewer) {
mUnlabelledAttributeViewer = unlabelledAttributeViewer;
mLabel = label;
}
@Override
public void setImage(int attributeValue) {
mUnlabelledAttributeViewer.setImage(attributeValue);
mLabel.setVisibility(attributeValue == 0 ? View.GONE : View.VISIBLE);
}
}
public static class UnlabelledAttributeViewer implements AttributeViewer {
private final Drawable[] mDrawables;
private final ImageView mImageView;
public UnlabelledAttributeViewer(ImageView imageView, Drawable[] drawables) {
mImageView = imageView;
mDrawables = drawables;
}
@Override
public void setImage(int attributeValue) {
if (attributeValue == 0) {
mImageView.setVisibility(View.GONE);
return;
}
mImageView.setImageDrawable(mDrawables[attributeValue-1]);
mImageView.setVisibility(View.VISIBLE);
}
}
public static class ResourceImages implements AttributeViewer {
private final int[] mResources;
private final ImageView mImageView;
public ResourceImages(ImageView imageView, int[] resources) {
mImageView = imageView;
mResources = resources;
}
@Override
public void setImage(int attributeValue) {
mImageView.setImageResource(mResources[attributeValue]);
}
}
public static class NameViewer {
private final TextView mName;
public NameViewer(TextView name) {
mName = name;
}
void set(CharSequence name) {
if (name.length() == 0) {
mName.setVisibility(View.GONE);
return;
}
mName.setText(name);
mName.setVisibility(View.VISIBLE);
}
}
public static final int CONTAINER_IMAGES[] = {
R.drawable.size_1, R.drawable.size_2, R.drawable.size_3, R.drawable.size_4
};
private final ImageView mCacheTypeImageView;
private final AttributeViewer mContainer;
private final AttributeViewer mDifficulty;
private final TextView mId;
private final NameViewer mName;
private final RadarView mRadarView;
private final AttributeViewer mTerrain;
public GeocacheViewer(RadarView radarView, TextView gcId, NameViewer gcName,
ImageView cacheTypeImageView, AttributeViewer gcDifficulty, AttributeViewer gcTerrain,
AttributeViewer gcContainer) {
mRadarView = radarView;
mId = gcId;
mName = gcName;
mCacheTypeImageView = cacheTypeImageView;
mDifficulty = gcDifficulty;
mTerrain = gcTerrain;
mContainer = gcContainer;
}
public void set(Geocache geocache) {
final double latitude = geocache.getLatitude();
final double longitude = geocache.getLongitude();
mRadarView.setTarget((int)(latitude * GeoUtils.MILLION),
(int)(longitude * GeoUtils.MILLION));
mId.setText(geocache.getId());
mCacheTypeImageView.setImageResource(geocache.getCacheType().iconBig());
mContainer.setImage(geocache.getContainer());
mDifficulty.setImage(geocache.getDifficulty());
mTerrain.setImage(geocache.getTerrain());
mName.set(geocache.getName());
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.Tags;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.activity.main.Util;
import com.google.code.geobeagle.database.DbFrontend;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
public class EditCache {
public static class CancelButtonOnClickListener implements OnClickListener {
private final Activity mActivity;
public CancelButtonOnClickListener(Activity activity) {
mActivity = activity;
}
public void onClick(View v) {
mActivity.setResult(Activity.RESULT_CANCELED, null);
mActivity.finish();
}
}
public static class CacheSaverOnClickListener implements OnClickListener {
private final Activity mActivity;
private final EditCache mGeocacheView;
private final DbFrontend mDbFrontend;
public CacheSaverOnClickListener(Activity activity, EditCache editCache,
DbFrontend dbFrontend) {
mActivity = activity;
mGeocacheView = editCache;
mDbFrontend = dbFrontend;
}
public void onClick(View v) {
final Geocache geocache = mGeocacheView.get();
if (geocache.saveToDbIfNeeded(mDbFrontend))
mDbFrontend.setGeocacheTag(geocache.getId(), Tags.LOCKED_FROM_OVERWRITING, true);
final Intent i = new Intent();
i.setAction(GeocacheListController.SELECT_CACHE);
i.putExtra("geocacheId", geocache.getId());
mActivity.setResult(Activity.RESULT_OK, i);
mActivity.finish();
}
}
private final GeocacheFactory mGeocacheFactory;
private final EditText mId;
private final EditText mLatitude;
private final EditText mLongitude;
private final EditText mName;
private Geocache mOriginalGeocache;
public EditCache(GeocacheFactory geocacheFactory, EditText id, EditText name,
EditText latitude, EditText longitude) {
mGeocacheFactory = geocacheFactory;
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
}
Geocache get() {
return mGeocacheFactory.create(mId.getText(), mName.getText(), Util
.parseCoordinate(mLatitude.getText()), Util.parseCoordinate(mLongitude
.getText()), mOriginalGeocache.getSourceType(), mOriginalGeocache
.getSourceName(), mOriginalGeocache.getCacheType(), mOriginalGeocache
.getDifficulty(), mOriginalGeocache.getTerrain(), mOriginalGeocache
.getContainer());
}
public void set(Geocache geocache) {
mOriginalGeocache = geocache;
mId.setText(geocache.getId());
mName.setText(geocache.getName());
mLatitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLatitude()));
mLongitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLongitude()));
//mLatitude.setText(Double.toString(geocache.getLatitude()));
//mLongitude.setText(Double.toString(geocache.getLongitude()));
mLatitude.requestFocus();
}
} | Java |
/*
** 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.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import android.content.SharedPreferences;
public class GeocacheFromPreferencesFactory {
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromPreferencesFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(SharedPreferences preferences) {
final int iSource = preferences.getInt(Geocache.SOURCE_TYPE, -1);
final Source source = mGeocacheFactory.sourceFromInt(Math.max(Source.MIN_SOURCE, Math.min(
iSource, Source.MAX_SOURCE)));
final int iCacheType = preferences.getInt(Geocache.CACHE_TYPE, 0);
final CacheType cacheType = mGeocacheFactory.cacheTypeFromInt(iCacheType);
return mGeocacheFactory.create(preferences.getString(Geocache.ID, "GCMEY7"), preferences
.getString(Geocache.NAME, "Google Falls"), preferences.getFloat(Geocache.LATITUDE, 0),
preferences.getFloat(Geocache.LONGITUDE, 0), source, preferences.getString(
Geocache.SOURCE_NAME, ""), cacheType, preferences.getInt(
Geocache.DIFFICULTY, 0), preferences.getInt(Geocache.TERRAIN, 0),
preferences.getInt(Geocache.CONTAINER, 0));
}
}
| Java |
/*
** 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.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.database.DbFrontend;
import android.content.Intent;
import android.net.UrlQuerySanitizer;
public class GeocacheFromIntentFactory {
private final GeocacheFactory mGeocacheFactory;
DbFrontend mDbFrontend;
GeocacheFromIntentFactory(GeocacheFactory geocacheFactory,
DbFrontend dbFrontend) {
mGeocacheFactory = geocacheFactory;
mDbFrontend = dbFrontend;
}
public Geocache viewCacheFromMapsIntent(Intent intent, Geocache defaultGeocache) {
final String query = intent.getData().getQuery();
final CharSequence sanitizedQuery = Util.parseHttpUri(query, new UrlQuerySanitizer(),
UrlQuerySanitizer.getAllButNulAndAngleBracketsLegal());
if (sanitizedQuery == null)
return defaultGeocache;
final CharSequence[] latlon = Util.splitLatLonDescription(sanitizedQuery);
final Geocache geocache = mGeocacheFactory.create(latlon[2], latlon[3], Util
.parseCoordinate(latlon[0]), Util.parseCoordinate(latlon[1]), Source.WEB_URL, null,
CacheType.NULL, 0, 0, 0);
geocache.saveToDb(mDbFrontend);
return geocache;
}
}
| Java |
/*
** 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.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.IPausable;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityType;
import com.google.code.geobeagle.activity.main.view.FavoriteView;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler;
import com.google.code.geobeagle.activity.main.view.FavoriteView.FavoriteState;
import com.google.code.geobeagle.activity.main.view.FavoriteView.FavoriteViewDelegate;
import com.google.code.geobeagle.database.DbFrontend;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import java.io.File;
public class GeoBeagleDelegate {
public static class LogFindClickListener implements OnClickListener {
private final GeoBeagle mGeoBeagle;
private final int mIdDialog;
public LogFindClickListener(GeoBeagle geoBeagle, int idDialog) {
mGeoBeagle = geoBeagle;
mIdDialog = idDialog;
}
public void onClick(View v) {
mGeoBeagle.showDialog(mIdDialog);
}
}
static class RadarViewRefresher implements Refresher {
private final RadarView mRadarView;
private final GeoFixProvider mGeoFixProvider;
public RadarViewRefresher(RadarView radarView,
GeoFixProvider geoFixProvider) {
mRadarView = radarView;
mGeoFixProvider = geoFixProvider;
}
@Override
public void forceRefresh() {
refresh();
}
@Override
public void refresh() {
if (mGeoFixProvider.isProviderEnabled())
mRadarView.setLocation(mGeoFixProvider.getLocation(),
mGeoFixProvider.getAzimuth());
else
mRadarView.handleUnknownLocation();
}
}
static class OptionsMenu {
private final MenuActions mMenuActions;
public OptionsMenu(MenuActions menuActions) {
mMenuActions = menuActions;
}
public boolean onCreateOptionsMenu(Menu menu) {
return mMenuActions.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
return mMenuActions.act(item.getItemId());
}
}
public static int ACTIVITY_REQUEST_TAKE_PICTURE = 1;
private final ActivitySaver mActivitySaver;
private Geocache mGeocache;
private final GeocacheFactory mGeocacheFactory;
private final GeocacheViewer mGeocacheViewer;
private final IncomingIntentHandler mIncomingIntentHandler;
private final DbFrontend mDbFrontend;
private final GeoBeagle mParent;
private final RadarView mRadarView;
private final SharedPreferences mSharedPreferences;
private final WebPageAndDetailsButtonEnabler mWebPageButtonEnabler;
private final IPausable mGeoFixProvider;
private final FavoriteView mFavoriteView;
public GeoBeagleDelegate(ActivitySaver activitySaver, GeoBeagle parent,
GeocacheFactory geocacheFactory, GeocacheViewer geocacheViewer,
IncomingIntentHandler incomingIntentHandler,
DbFrontend dbFrontend, RadarView radarView,
SharedPreferences sharedPreferences,
WebPageAndDetailsButtonEnabler webPageButtonEnabler,
IPausable geoFixProvider, FavoriteView favoriteView) {
mParent = parent;
mActivitySaver = activitySaver;
mSharedPreferences = sharedPreferences;
mRadarView = radarView;
mGeocacheViewer = geocacheViewer;
mWebPageButtonEnabler = webPageButtonEnabler;
mGeocacheFactory = geocacheFactory;
mIncomingIntentHandler = incomingIntentHandler;
mDbFrontend = dbFrontend;
mGeoFixProvider = geoFixProvider;
mFavoriteView = favoriteView;
}
public Geocache getGeocache() {
return mGeocache;
}
private void onCameraStart() {
String filename = "/sdcard/GeoBeagle/" + mGeocache.getId()
+ DateFormat.format(" yyyy-MM-dd kk.mm.ss.jpg", System.currentTimeMillis());
Log.d("GeoBeagle", "capturing image to " + filename);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filename)));
mParent.startActivityForResult(intent, GeoBeagleDelegate.ACTIVITY_REQUEST_TAKE_PICTURE);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CAMERA && event.getRepeatCount() == 0) {
onCameraStart();
return true;
}
return false;
}
public void onPause() {
mGeoFixProvider.onPause();
mActivitySaver.save(ActivityType.VIEW_CACHE, mGeocache);
mDbFrontend.closeDatabase();
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
CharSequence id = savedInstanceState.getCharSequence(Geocache.ID);
if (id == null || id.equals(""))
mGeocache = null;
else
mGeocache = mDbFrontend.loadCacheFromId(id.toString());
if (mGeocache == null)
mGeocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "",
CacheType.NULL, 0, 0, 0);
}
public void onResume() {
mRadarView.handleUnknownLocation();
mGeoFixProvider.onResume();
mRadarView.setUseImperial(mSharedPreferences.getBoolean("imperial", false));
mGeocache = mIncomingIntentHandler.maybeGetGeocacheFromIntent(mParent.getIntent(),
mGeocache, mDbFrontend);
// Possible fix for issue 53.
if (mGeocache == null) {
mGeocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "",
CacheType.NULL, 0, 0, 0);
}
mGeocacheViewer.set(mGeocache);
final FavoriteState favoriteState = new FavoriteState(mDbFrontend,
mGeocache.getId());
final FavoriteViewDelegate favoriteViewDelegate = new FavoriteViewDelegate(
mFavoriteView, favoriteState);
mFavoriteView.setGeocache(favoriteViewDelegate);
mWebPageButtonEnabler.check();
}
public void onSaveInstanceState(Bundle outState) {
// apparently there are cases where getGeocache returns null, causing
// crashes with 0.7.7/0.7.8.
if (mGeocache == null)
outState.putCharSequence(Geocache.ID, "");
else
outState.putCharSequence(Geocache.ID, mGeocache.getId());
}
public void setGeocache(Geocache geocache) {
mGeocache = geocache;
}
}
| Java |
/*
** 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.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.database.DbFrontend;
import android.content.Intent;
public class IncomingIntentHandler {
private GeocacheFactory mGeocacheFactory;
private GeocacheFromIntentFactory mGeocacheFromIntentFactory;
private final DbFrontend mDbFrontend;
public IncomingIntentHandler(GeocacheFactory geocacheFactory,
GeocacheFromIntentFactory geocacheFromIntentFactory,
DbFrontend dbFrontend) {
mGeocacheFactory = geocacheFactory;
mGeocacheFromIntentFactory = geocacheFromIntentFactory;
mDbFrontend = dbFrontend;
}
public Geocache maybeGetGeocacheFromIntent(Intent intent, Geocache defaultGeocache,
DbFrontend dbFrontend) {
if (intent == null) {
return defaultGeocache;
}
final String action = intent.getAction();
if (action == null) {
return defaultGeocache;
}
if (action.equals(Intent.ACTION_VIEW) && intent.getType() == null) {
return mGeocacheFromIntentFactory.viewCacheFromMapsIntent(intent, defaultGeocache);
} else if (action.equals(GeocacheListController.SELECT_CACHE)) {
String id = intent.getStringExtra("geocacheId");
Geocache geocache = mDbFrontend.loadCacheFromId(id);
if (geocache == null)
geocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "",
CacheType.NULL, 0, 0, 0);
return geocache;
} else {
return defaultGeocache;
}
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import android.content.Context;
import java.net.URLEncoder;
import java.util.Locale;
public class GeocacheToGoogleMap implements GeocacheToUri {
private final Context mContext;
public GeocacheToGoogleMap(Context context) {
mContext = context;
}
/*
* (non-Javadoc)
* @see
* com.google.code.geobeagle.activity.main.intents.GeocacheToUri#convert
* (com.google.code.geobeagle.Geocache)
*/
public String convert(Geocache geocache) {
// "geo:%1$.5f,%2$.5f?name=cachename"
String idAndName = geocache.getIdAndName().toString();
idAndName = idAndName.replace("(", "[");
idAndName = idAndName.replace(")", "]");
idAndName = URLEncoder.encode(idAndName);
final String format = String.format(Locale.US, mContext
.getString(R.string.map_intent), geocache.getLatitude(), geocache.getLongitude(),
idAndName);
return format;
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import android.content.res.Resources;
/*
* Convert a Geocache to the cache page url.
*/
public class GeocacheToCachePage implements GeocacheToUri {
private final Resources mResources;
public GeocacheToCachePage(Resources resources) {
mResources = resources;
}
// TODO: move strings into Provider enum.
public String convert(Geocache geocache) {
return String.format(mResources.getStringArray(R.array.cache_page_url)[geocache
.getContentProvider().toInt()], geocache.getShortId());
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.activity.main.UriParser;
import android.content.Intent;
public class IntentFactory {
private final UriParser mUriParser;
public IntentFactory(UriParser uriParser) {
mUriParser = uriParser;
}
public Intent createIntent(String action, String uri) {
return new Intent(action, mUriParser.parse(uri));
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.Geocache;
public interface GeocacheToUri {
public String convert(Geocache geocache);
}
| Java |
/*
** 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.code.geobeagle.activity;
import com.google.code.geobeagle.Geocache;
import android.content.SharedPreferences.Editor;
public class ActivitySaver {
private final Editor mEditor;
static final String LAST_ACTIVITY = "lastActivity";
ActivitySaver(Editor editor) {
mEditor = editor;
}
public void save(ActivityType activityType) {
mEditor.putInt("lastActivity", activityType.toInt());
mEditor.commit();
}
public void save(ActivityType activityType, Geocache geocache) {
mEditor.putInt("lastActivity", activityType.toInt());
mEditor.putString(Geocache.ID, geocache.getId().toString());
mEditor.commit();
}
}
| Java |
/**
*
*/
package com.google.code.geobeagle.activity.prox;
class ScalarParameter extends Parameter {
public ScalarParameter(double accelConst, double attenuation, double init) {
super(accelConst, attenuation, init);
}
public ScalarParameter(double accelConst, double attenuation) {
super(accelConst, attenuation);
}
public ScalarParameter(double init) {
super(init);
}
public ScalarParameter() {
super();
}
@Override
public void update(double deltaSec) {
if (!mIsInited || (mTargetValue == mValue && mChangePerSec == 0))
return;
//First update mChangePerSec, then update mValue
//There is an ideal mChangePerSec for every distance. Move towards it.
double distance = mTargetValue - mValue;
double accel = distance * mAccelConst;
mValue += mChangePerSec * deltaSec + accel*deltaSec*deltaSec/2.0;
mChangePerSec += accel * deltaSec;
mChangePerSec *= Math.pow(mAttenuation, deltaSec);
}
} | Java |
package com.google.code.geobeagle.activity.prox;
/** Represents an angle in degrees, knowing values 360 and 0 are the same */
class AngularParameter extends Parameter {
public AngularParameter(double accelConst, double attenuation, double init) {
super(accelConst, attenuation, init);
}
public AngularParameter(double accelConst, double attenuation) {
super(accelConst, attenuation);
}
public AngularParameter(double init) {
super(init);
}
public AngularParameter() {
super();
}
@Override
public void update(double deltaSec) {
double distance = mTargetValue - mValue;
if (distance > 180)
distance -= 360;
else if (distance < -180)
distance += 360;
double accel = distance * Math.abs(distance) * mAccelConst;
mValue += mChangePerSec * deltaSec + accel*deltaSec*deltaSec/2.0;
mChangePerSec += accel * deltaSec;
mChangePerSec *= Math.pow(mAttenuation, deltaSec);
}
} | Java |
package com.google.code.geobeagle.activity.prox;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheListPrecomputed;
import com.google.code.geobeagle.activity.main.GeoUtils;
import com.google.code.geobeagle.database.CachesProviderCount;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.Paint.Style;
import android.graphics.Shader.TileMode;
import android.util.Log;
import java.util.AbstractList;
public class ProximityPainter {
//private int mUserX;
/** Where on the display to show the user's location */
private int mUserY;
/* X center of display */
private int mCenterX;
/** Higher value means that big distances are compressed relatively more */
private double mLogScale = 1.25;
private final int mUserScreenRadius = 25;
private Paint mTextPaint;
private Paint mDistancePaint;
private Paint mMainDistancePaint;
private Paint mCachePaint;
private Paint mUserPaint;
private Paint mSpeedPaint;
private Paint mAccuracyPaint;
private Paint mCompassNorthPaint;
private Paint mCompassSouthPaint;
private Paint mGlowPaint;
private final CachesProviderCount mCachesProvider;
private Geocache mSelectedGeocache;
/** Which direction the device is pointed, in degrees */
private Parameter mDeviceDirection = new AngularParameter(0.03, 0.3);
/** Location reading accuracy in meters */
private Parameter mGpsAccuracy = new ScalarParameter(4.0);
private Parameter mScaleFactor = new ScalarParameter(12.0);
/** The speed of the user, measured using GPS */
private Parameter mUserSpeed = new ScalarParameter(0);
/** Which way the user is moving */
private Parameter mUserDirection = new AngularParameter(0.03, 0.3);
private Parameter mLatitude = new ScalarParameter();
private Parameter mLongitude = new ScalarParameter();
private Rect mTempBounds = new Rect();
private Parameter[] allParameters = { mDeviceDirection, mGpsAccuracy,
mScaleFactor, mUserSpeed, mUserDirection, mLatitude, mLongitude };
public ProximityPainter(CachesProviderCount cachesProvider) {
mCachesProvider = cachesProvider;
mUserY = 350;
//mUseImerial = mSharedPreferences.getBoolean("imperial", false);
mTextPaint = new Paint();
mTextPaint.setColor(Color.GREEN);
mDistancePaint = new Paint();
mDistancePaint.setARGB(255, 0, 96, 0);
mDistancePaint.setStyle(Style.STROKE);
mDistancePaint.setStrokeWidth(2);
mDistancePaint.setAntiAlias(true);
mMainDistancePaint = new Paint(mDistancePaint);
mMainDistancePaint.setARGB(255, 0, 200, 0);
mMainDistancePaint.setStrokeWidth(4);
mCachePaint = new Paint();
mCachePaint.setARGB(255, 200, 200, 248);
mCachePaint.setStyle(Style.STROKE);
mCachePaint.setStrokeWidth(2);
mCachePaint.setAntiAlias(true);
int userColor = Color.argb(255, 216, 176, 128);
//mGlowShader = new RadialGradient(0, 0,
// (int)mGpsAccuracy.get(), 0x2000ff00, 0xc000ff00, TileMode.CLAMP);
mAccuracyPaint = new Paint();
//mAccuracyPaint.setShader(mGlowShader);
mAccuracyPaint.setStrokeWidth(6);
mAccuracyPaint.setStyle(Style.STROKE);
mAccuracyPaint.setColor(userColor);
float[] intervals = { 20, 10};
mAccuracyPaint.setPathEffect(new DashPathEffect(intervals, 5));
mAccuracyPaint.setAntiAlias(true);
mUserPaint = new Paint();
mUserPaint.setColor(userColor);
mUserPaint.setStyle(Style.STROKE);
mUserPaint.setStrokeWidth(6);
mUserPaint.setAntiAlias(true);
mSpeedPaint = new Paint();
mSpeedPaint.setColor(userColor);
mSpeedPaint.setStrokeWidth(6);
mSpeedPaint.setStyle(Style.STROKE);
mSpeedPaint.setAntiAlias(true);
mCompassNorthPaint = new Paint();
mCompassNorthPaint.setARGB(255, 255, 0, 0);
mCompassNorthPaint.setStrokeWidth(3);
mCompassNorthPaint.setAntiAlias(true);
mCompassSouthPaint = new Paint();
mCompassSouthPaint.setARGB(255, 230, 230, 230);
mCompassSouthPaint.setStrokeWidth(3);
mCompassSouthPaint.setAntiAlias(true);
mGlowPaint = new Paint();
mGlowPaint.setStyle(Style.STROKE);
}
public void setUserLocation(double latitude, double longitude, float accuracy) {
mLatitude.set(latitude);
mLongitude.set(longitude);
mGpsAccuracy.set(accuracy);
mCachesProvider.setCenter(latitude, longitude);
}
public void setSelectedGeocache(Geocache geocache) {
mSelectedGeocache = geocache;
}
public void draw(Canvas canvas) {
canvas.drawColor(Color.BLACK); //Clear screen
mCenterX = canvas.getWidth() / 2;
//The maximum pixel distance from user point that's visible on screen
int maxScreenRadius = (int)Math.ceil(Math.sqrt(mCenterX*mCenterX + mUserY*mUserY));
int accuracyScreenRadius = transformDistanceToScreen(mGpsAccuracy.get());
double direction = mDeviceDirection.get();
//Draw accuracy blur field
if (accuracyScreenRadius > 0) {
//TODO: Wasting objects!
/*
mGlowShader = new RadialGradient(mCenterX, mUserY,
accuracyScreenRadius, 0x80ffff00, 0x20ffff00, TileMode.CLAMP);
mAccuracyPaint.setShader(mGlowShader);
*/
canvas.drawCircle(mCenterX, mUserY, accuracyScreenRadius, mAccuracyPaint);
}
//North
int x1 = xRelativeUser(maxScreenRadius, Math.toRadians(270-direction));
int y1 = yRelativeUser(maxScreenRadius, Math.toRadians(270-direction));
canvas.drawLine(mCenterX, mUserY, x1, y1, mCompassNorthPaint);
//South
int x2 = xRelativeUser(maxScreenRadius, Math.toRadians(90-direction));
int y2 = yRelativeUser(maxScreenRadius, Math.toRadians(90-direction));
canvas.drawLine(mCenterX, mUserY, x2, y2, mCompassSouthPaint);
//West-east
int x3 = xRelativeUser(maxScreenRadius, Math.toRadians(180-direction));
int y3 = yRelativeUser(maxScreenRadius, Math.toRadians(180-direction));
int x4 = xRelativeUser(maxScreenRadius, Math.toRadians(-direction));
int y4 = yRelativeUser(maxScreenRadius, Math.toRadians(-direction));
canvas.drawLine(x3, y3, x4, y4, mDistancePaint);
//Draw user speed vector
if (mUserSpeed.get() > 0) {
int speedRadius = transformDistanceToScreen(mUserSpeed.get()*3.6);
int x7 = xRelativeUser(speedRadius, Math.toRadians(mUserDirection.get()-direction-90));
int y7 = yRelativeUser(speedRadius, Math.toRadians(mUserDirection.get()-direction-90));
canvas.drawLine(mCenterX, mUserY, x7, y7, mSpeedPaint);
}
int[] distanceMarks = { 10, 20, 50, 100, 500, 1000, 5000, 10000, 50000, 100000, 1000000 };
String[] distanceTexts = { "10m", "20m", "50m", "100m", "500m", "1km", "5km", "10km", "50km", "100km", "1000km" };
int lastLeft = mCenterX;
for (int ix = 0; ix < distanceMarks.length; ix++) {
int distance = distanceMarks[ix];
String text = distanceTexts[ix];
int radius = transformDistanceToScreen(distance);
if (radius > maxScreenRadius)
//Not visible anywhere on screen
break;
if (distance == 100 || distance == 1000)
canvas.drawCircle(mCenterX, mUserY, radius, mMainDistancePaint);
else
canvas.drawCircle(mCenterX, mUserY, radius, mDistancePaint);
if (radius > mCenterX) {
int height = (int)Math.sqrt(radius*radius - mCenterX*mCenterX);
canvas.drawText(text, 5, mUserY-height-5, mTextPaint);
} else {
mTextPaint.getTextBounds(text, 0, text.length(), mTempBounds);
int left = mCenterX-radius-10;
if (left + mTempBounds.right > lastLeft)
continue; //Don't draw text that would overlap
lastLeft = left;
canvas.drawText(text, left, mUserY, mTextPaint);
}
}
AbstractList<Geocache> caches = mCachesProvider.getCaches();
//Draw all geocaches and lines to them
if (mCachesProvider.hasChanged()) {
Log.d("GeoBeagle", "ProximityPainter drawing " + caches.size() + " caches");
mCachesProvider.resetChanged();
}
if (mSelectedGeocache != null && !caches.contains(mSelectedGeocache)) {
caches = new GeocacheListPrecomputed(caches, mSelectedGeocache);
}
double maxDistanceM = 0;
for (Geocache geocache : caches) {
double angle = Math.toRadians(GeoUtils.bearing(mLatitude.get(), mLongitude.get(),
geocache.getLatitude(), geocache.getLongitude()) - direction - 90);
double distanceM = GeoUtils.distanceKm(mLatitude.get(), mLongitude.get(),
geocache.getLatitude(), geocache.getLongitude()) * 1000;
if (distanceM > maxDistanceM)
maxDistanceM = distanceM;
double screenDist = transformDistanceToScreen(distanceM);
int cacheScreenRadius = (int)(2*scaleFactorAtDistance(distanceM*2));
mCachePaint.setStrokeWidth((int)Math.ceil(0.5*scaleFactorAtDistance(distanceM)));
mCachePaint.setAlpha(255);
int x = mCenterX + (int)(screenDist * Math.cos(angle));
int y = mUserY + (int)(screenDist * Math.sin(angle));
if (geocache == mSelectedGeocache) {
int glowTh = (int)(mCachePaint.getStrokeWidth() * 2); //(1.0 + Math.abs(Math.sin(mTime))));
drawGlow(canvas, x, y, (int)(cacheScreenRadius+mCachePaint.getStrokeWidth()/2), glowTh);
}
canvas.drawCircle(x, y, cacheScreenRadius, mCachePaint);
//Lines to geocaches
if (screenDist > mUserScreenRadius + cacheScreenRadius) {
//Cache is outside accuracy circle
int x5 = xRelativeUser(mUserScreenRadius, angle);
int y5 = yRelativeUser(mUserScreenRadius, angle);
int x6 = xRelativeUser(screenDist-cacheScreenRadius, angle);
int y6 = yRelativeUser(screenDist-cacheScreenRadius, angle);
mCachePaint.setStrokeWidth(Math.min(8, cacheScreenRadius));
double closeness = 1 - (0.7*screenDist)/maxScreenRadius;
mCachePaint.setAlpha((int)Math.min(255, 256 * 1.5 * closeness));
canvas.drawLine(x5, y5, x6, y6, mCachePaint);
}
}
mScaleFactor.set(mUserY * Math.log(mLogScale) / Math.log(maxDistanceM/2f));
canvas.drawCircle(mCenterX, mUserY, mUserScreenRadius, mUserPaint);
}
/**
* @param radius The smallest radius that will glow
* @param thickness Thickness of glow
*/
private void drawGlow(Canvas c, int x, int y, int radius, int thickness) {
int color = Color.argb(255, 200, 200, 248);
int[] colors = { color, color, 0x00000000};
float[] positions = { 0, ((float)radius)/(radius+thickness), 1f };
//float[] positions = { 0, (radius + 0.5f*thickness)/(radius+thickness), 1f };
//float[] positions = { 0.5f, 0.9f, 1f };
//TODO: Wastes objects
Shader glowShader;
glowShader = new RadialGradient(x, y, radius+thickness*1.5f, colors, positions, TileMode.MIRROR);
mGlowPaint.setShader(glowShader);
mGlowPaint.setStrokeWidth(radius);
c.drawCircle(x, y, radius+thickness/2, mGlowPaint);
}
/** angle is in radians */
private int xRelativeUser(double distance, double angle) {
return mCenterX + (int)(distance * Math.cos(angle));
}
/** angle is in radians */
private int yRelativeUser(double distance, double angle) {
return mUserY + (int)(distance * Math.sin(angle));
}
/** Return the distance in pixels for a real-world distance in meters
* Argument must be positive */
private int transformDistanceToScreen(double meters) {
int distance = (int)(mScaleFactor.get() * myLog(meters));
return Math.max(20, distance - 40);
}
/** At distance 'meters', draw a meter as these many pixels */
private double scaleFactorAtDistance(double meters) {
if (meters < 6)
meters = 1;
else
meters -= 5;
return (int)(2000.0/(mScaleFactor.get() * myLog(meters)));
}
/** Returns logarithm of x in base mLogScale */
private double myLog(double x) {
return Math.log(x) / Math.log(mLogScale);
}
/** bearing 0 is north, bearing 90 is east */
public void setUserDirection(double degrees) {
mDeviceDirection.set(degrees);
}
/** bearing 0 is north, bearing 90 is east */
public void setUserMovement(double bearing, double speed) {
mUserSpeed.set(speed);
mUserDirection.set(bearing);
}
/** Seconds */
private double mTime;
/** Update animations timeDelta seconds (preferably much less than a sec) */
public void advanceTime(double timeDelta) {
mTime += timeDelta;
for (Parameter param : allParameters) {
param.update(timeDelta);
}
}
}
| Java |
package com.google.code.geobeagle.activity.prox;
/** Contains the value of a single parameter. This abstraction allows for
* animating arbitrary parameters smoothly to their current value. */
public class Parameter {
/** If an initial value has been set */
protected boolean mIsInited = false;
/** Max change in movement towards target value, in delta / (sec^2) */
protected double mValue;
protected double mTargetValue;
/** Delta per second for mValue. Updated to move mValue towards mTargetValue */
protected double mChangePerSec = 0;
/** How quickly the movement towards the correct value accelerates */
protected final double mAccelConst;
/** Part of the speed that is preserved after one second if otherwise unchanged. */
protected final double mAttenuation;
public Parameter(double accelConst, double attenuation, double init) {
mAccelConst = accelConst;
mAttenuation = attenuation;
mTargetValue = init;
mValue = init;
mIsInited = true;
}
public Parameter(double accelConst, double attenuation) {
mAccelConst = accelConst;
mAttenuation = attenuation;
mTargetValue = 0;
mValue = 0;
mIsInited = false;
}
public Parameter(double init) {
mAccelConst = 0.8;
mAttenuation = 0.3;
mTargetValue = init;
mValue = init;
mIsInited = true;
}
public Parameter() {
mAccelConst = 0.8;
mAttenuation = 0.3;
mTargetValue = 0;
mValue = 0;
mIsInited = false;
}
public double get() {
return mValue;
}
public void set(double value) {
if (mIsInited) {
mTargetValue = value;
} else {
mTargetValue = value;
mValue = value;
mIsInited = true;
}
}
//Override this!
/** Animate the value towards its goal given that deltaSec time
* elapsed since last update */
public void update(double deltaSec) { };
} | Java |
/*
** 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.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.IPausable;
import com.google.code.geobeagle.actions.CacheContextMenu;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityType;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheSummaryRowInflater;
import com.google.code.geobeagle.database.CachesProviderDb;
import com.google.code.geobeagle.database.DbFrontend;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class CacheListDelegate {
static class ImportIntentManager {
static final String INTENT_EXTRA_IMPORT_TRIGGERED = "com.google.code.geabeagle.import_triggered";
private final Activity mActivity;
ImportIntentManager(Activity activity) {
mActivity = activity;
}
boolean isImport() {
final Intent intent = mActivity.getIntent();
if (intent == null)
return false;
String action = intent.getAction();
if (action == null)
return false;
if (!action.equals("android.intent.action.VIEW"))
return false;
if (intent.getBooleanExtra(INTENT_EXTRA_IMPORT_TRIGGERED, false))
return false;
// Need to alter the intent so that the import isn't retriggered if
// pause/resume is a result of the phone going to sleep and then
// waking up again.
intent.putExtra(INTENT_EXTRA_IMPORT_TRIGGERED, true);
return true;
}
}
private final ActivitySaver mActivitySaver;
private final GeocacheListController mController;
private final DbFrontend mDbFrontend;
private final ImportIntentManager mImportIntentManager;
private final CacheContextMenu mContextMenu;
private final CacheListAdapter mCacheList;
private final ListActivity mListActivity;
private final DistanceFormatterManager mDistanceFormatterManager;
private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater;
private final CachesProviderDb mCachesToFlush;
private final IPausable[] mPausables;
public CacheListDelegate(ImportIntentManager importIntentManager, ActivitySaver activitySaver,
GeocacheListController geocacheListController,
DbFrontend dbFrontend,
CacheContextMenu menuCreator,
CacheListAdapter cacheList,
GeocacheSummaryRowInflater geocacheSummaryRowInflater,
ListActivity listActivity,
DistanceFormatterManager distanceFormatterManager,
CachesProviderDb cachesToFlush,
IPausable[] pausables) {
mActivitySaver = activitySaver;
mController = geocacheListController;
mImportIntentManager = importIntentManager;
mDbFrontend = dbFrontend;
mContextMenu = menuCreator;
mCacheList = cacheList;
mGeocacheSummaryRowInflater = geocacheSummaryRowInflater;
mListActivity = listActivity;
mDistanceFormatterManager = distanceFormatterManager;
mCachesToFlush = cachesToFlush;
mPausables = pausables;
}
public boolean onContextItemSelected(MenuItem menuItem) {
return mContextMenu.onContextItemSelected(menuItem);
}
public boolean onCreateOptionsMenu(Menu menu) {
return mController.onCreateOptionsMenu(menu);
}
public void onListItemClick(ListView l, View v, int position, long id) {
mController.onListItemClick(l, v, position, id);
}
public boolean onMenuOpened(int featureId, Menu menu) {
return mController.onMenuOpened(featureId, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
return mController.onOptionsItemSelected(item);
}
public void onPause() {
for (IPausable pausable : mPausables)
pausable.onPause();
mController.onPause();
mActivitySaver.save(ActivityType.CACHE_LIST);
mDbFrontend.closeDatabase();
}
public void onResume() {
Log.d("GeoBeagle", "CacheListDelegate.onResume()");
mDistanceFormatterManager.setFormatter();
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mListActivity);
final boolean absoluteBearing = sharedPreferences.getBoolean("absolute-bearing", false);
mGeocacheSummaryRowInflater.setBearingFormatter(absoluteBearing);
mController.onResume(mImportIntentManager.isImport());
for (IPausable pausable : mPausables)
pausable.onResume();
}
public void onActivityResult() {
Log.d("GeoBeagle", "CacheListDelegate.onActivityResult()");
mCachesToFlush.notifyOfDbChange();
mCacheList.forceRefresh();
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist.actions;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.GeoFix;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.actions.ActionStaticLabel;
import com.google.code.geobeagle.actions.CacheAction;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.database.DbFrontend;
import android.content.res.Resources;
public class MenuActionMyLocation extends ActionStaticLabel implements MenuAction {
private final ErrorDisplayer mErrorDisplayer;
private final DbFrontend mDbFrontend;
private final GeocacheFactory mGeocacheFactory;
private final GeoFixProvider mLocationControl;
private final CacheAction mCacheActionEdit;
public MenuActionMyLocation(ErrorDisplayer errorDisplayer,
GeocacheFactory geocacheFactory,
GeoFixProvider locationControl, DbFrontend dbFrontend,
Resources resources, CacheAction cacheActionEdit) {
super(resources, R.string.menu_add_my_location);
mErrorDisplayer = errorDisplayer;
mGeocacheFactory = geocacheFactory;
mLocationControl = locationControl;
mDbFrontend = dbFrontend;
mCacheActionEdit = cacheActionEdit;
}
@Override
public void act() {
GeoFix location = mLocationControl.getLocation();
if (location == null)
return;
long time = location.getTime();
final Geocache newCache = mGeocacheFactory.create(String.format("ML%1$tk%1$tM%1$tS", time), String.format(
"[%1$tk:%1$tM] My Location", time), location.getLatitude(),
location.getLongitude(), Source.MY_LOCATION, "mylocation", CacheType.MY_LOCATION, 0, 0, 0);
if (newCache == null) {
mErrorDisplayer.displayError(R.string.current_location_null);
return;
}
newCache.saveToDb(mDbFrontend);
mCacheActionEdit.act(newCache);
//Since the Edit activity will refresh the list, we don't need to do it
//mListRefresher.forceRefresh();
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist.actions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Tags;
import com.google.code.geobeagle.actions.ActionStaticLabel;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.activity.cachelist.GpxImporterFactory;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.xmlimport.GpxImporter;
import android.content.res.Resources;
public class MenuActionSyncGpx extends ActionStaticLabel implements MenuAction {
private Abortable mAbortable;
private final CacheListAdapter mCacheList;
private final GpxImporterFactory mGpxImporterFactory;
private final DbFrontend mDbFrontend;
public MenuActionSyncGpx(Abortable abortable, CacheListAdapter cacheList,
GpxImporterFactory gpxImporterFactory, DbFrontend dbFrontend,
Resources resources) {
super(resources, R.string.menu_sync);
mAbortable = abortable;
mCacheList = cacheList;
mGpxImporterFactory = gpxImporterFactory;
mDbFrontend = dbFrontend;
}
public void abort() {
mAbortable.abort();
}
@Override
public void act() {
//Only the most recent batch of caches is shown as 'new'
mDbFrontend.clearTagForAllCaches(Tags.NEW);
final GpxImporter gpxImporter = mGpxImporterFactory.create(mDbFrontend.getCacheWriter());
mAbortable = gpxImporter;
gpxImporter.importGpxs(mCacheList);
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist.actions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import com.google.code.geobeagle.database.CachesProviderToggler;
import android.content.res.Resources;
public class MenuActionToggleFilter implements MenuAction {
private final CachesProviderToggler mCachesProviderToggler;
private final CacheListAdapter mListRefresher;
private final Resources mResources;
public MenuActionToggleFilter(CachesProviderToggler cachesProviderToggler,
CacheListAdapter cacheListRefresh, Resources resources) {
mCachesProviderToggler = cachesProviderToggler;
mListRefresher = cacheListRefresh;
mResources = resources;
}
public void act() {
mCachesProviderToggler.toggle();
mListRefresher.forceRefresh();
}
@Override
public String getLabel() {
if (mCachesProviderToggler.isShowingNearest())
return mResources.getString(R.string.menu_show_all_caches);
else
return mResources.getString(R.string.menu_show_nearest_caches);
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.actions;
public interface Abortable {
public void abort();
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist.presenter;
public interface RefreshAction {
public void refresh();
} | Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.GeoFix;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.database.CachesProviderCenterThread;
import com.google.code.geobeagle.database.ICachesProviderCenter;
/** Sends location and azimuth updates to CacheList
* when the user position changes. */
public class CacheListPositionUpdater implements Refresher {
private final CacheListAdapter mCacheList;
private final GeoFixProvider mGeoFixProvider;
private final ICachesProviderCenter mSearchCenter;
private final CachesProviderCenterThread mSortCenterThread;
public CacheListPositionUpdater(GeoFixProvider geoFixProvider,
CacheListAdapter cacheList, ICachesProviderCenter searchCenter,
CachesProviderCenterThread sortCenter) {
mGeoFixProvider = geoFixProvider;
mCacheList = cacheList;
mSearchCenter = searchCenter;
mSortCenterThread = sortCenter;
}
public void refresh() {
final GeoFix location = mGeoFixProvider.getLocation();
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
mSearchCenter.setCenter(latitude, longitude);
mSortCenterThread.setCenter(latitude, longitude, mCacheList);
}
}
@Override
public void forceRefresh() {
refresh();
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
public interface BearingFormatter {
public abstract String formatBearing(float absBearing, float myHeading);
}
| Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.database.CachesProviderToggler;
import com.google.code.geobeagle.database.DistanceAndBearing;
import com.google.code.geobeagle.database.DistanceAndBearing.IDistanceAndBearingProvider;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.AbsListView.OnScrollListener;
import java.util.AbstractList;
/** Feeds the caches in a CachesProvider to the GUI list view */
public class CacheListAdapter extends BaseAdapter implements Refresher {
private final CachesProviderToggler mProvider;
private final IDistanceAndBearingProvider mDistances;
private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater;
private final TitleUpdater mTitleUpdater;
private AbstractList<Geocache> mListData;
private float mAzimuth;
private boolean mUpdatesEnabled = true;
public static class ScrollListener implements OnScrollListener {
private final CacheListAdapter mCacheListAdapter;
public ScrollListener(CacheListAdapter updateFlag) {
mCacheListAdapter = updateFlag;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mCacheListAdapter.enableUpdates(scrollState == SCROLL_STATE_IDLE);
}
}
public CacheListAdapter(CachesProviderToggler provider,
IDistanceAndBearingProvider distances,
GeocacheSummaryRowInflater inflater,
TitleUpdater titleUpdater, AbstractList<Geocache> listData) {
mProvider = provider;
mGeocacheSummaryRowInflater = inflater;
mTitleUpdater = titleUpdater;
mDistances = distances;
mListData = listData;
}
public void enableUpdates(boolean enable) {
mUpdatesEnabled = enable;
if (enable)
refresh();
}
public void setAzimuth (float azimuth) {
mAzimuth = azimuth;
}
/** Updates the GUI from the Provider if necessary */
@Override
public void refresh() {
if (!mUpdatesEnabled || !mProvider.hasChanged()) {
return;
}
forceRefresh();
}
public void forceRefresh() {
mListData = mProvider.getCaches();
mProvider.resetChanged();
mTitleUpdater.refresh();
notifyDataSetChanged();
}
public int getCount() {
if (mListData == null)
return 0;
return mListData.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/** Get the geocache for a certain row in the displayed list, starting with zero */
public Geocache getGeocacheAt(int position) {
if (mListData == null)
return null;
Geocache cache = mListData.get(position);
return cache;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (mListData == null)
return null; //What happens in this case?
View view = mGeocacheSummaryRowInflater.inflate(convertView);
Geocache cache = mListData.get(position);
DistanceAndBearing geocacheVector = mDistances.getDistanceAndBearing(cache);
mGeocacheSummaryRowInflater.setData(view, geocacheVector, mAzimuth);
return view;
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.formatting.DistanceFormatterImperial;
import com.google.code.geobeagle.formatting.DistanceFormatterMetric;
import android.content.SharedPreferences;
import java.util.ArrayList;
public class DistanceFormatterManager {
private ArrayList<HasDistanceFormatter> mHasDistanceFormatters;
private final DistanceFormatterMetric mDistanceFormatterMetric;
private final DistanceFormatterImperial mDistanceFormatterImperial;
private final SharedPreferences mDefaultSharedPreferences;
DistanceFormatterManager(SharedPreferences defaultSharedPreferences,
DistanceFormatterImperial distanceFormatterImperial,
DistanceFormatterMetric distanceFormatterMetric) {
mDistanceFormatterImperial = distanceFormatterImperial;
mDistanceFormatterMetric = distanceFormatterMetric;
mDefaultSharedPreferences = defaultSharedPreferences;
mHasDistanceFormatters = new ArrayList<HasDistanceFormatter>(2);
}
public void addHasDistanceFormatter(HasDistanceFormatter hasDistanceFormatter) {
mHasDistanceFormatters.add(hasDistanceFormatter);
}
public DistanceFormatter getFormatter() {
final boolean imperial = mDefaultSharedPreferences.getBoolean("imperial", false);
return imperial ? mDistanceFormatterImperial : mDistanceFormatterMetric;
}
public void setFormatter() {
final DistanceFormatter formatter = getFormatter();
for (HasDistanceFormatter hasDistanceFormatter : mHasDistanceFormatters) {
hasDistanceFormatter.setDistanceFormatter(formatter);
}
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
public class AbsoluteBearingFormatter implements BearingFormatter {
private static final String[] LETTERS = {
"N", "NE", "E", "SE", "S", "SW", "W", "NW"
};
public String formatBearing(float absBearing, float myHeading) {
return LETTERS[((((int)(absBearing) + 22 + 720) % 360) / 45)];
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.formatting.DistanceFormatter;
public interface HasDistanceFormatter {
public abstract void setDistanceFormatter(DistanceFormatter distanceFormatter);
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.database.CachesProviderToggler;
import com.google.code.geobeagle.database.DbFrontend;
import android.app.ListActivity;
import android.widget.TextView;
public class TitleUpdater implements RefreshAction {
private final CachesProviderToggler mCachesProviderToggler;
private final ListActivity mListActivity;
private final DbFrontend mDbFrontend;
private final TextSelector mTextSelector;
public static class TextSelector {
int getTitle(boolean isShowingNearest) {
return isShowingNearest ? R.string.cache_list_title
: R.string.cache_list_title_all;
}
int getNoNearbyCachesText(int allCachesCount) {
return allCachesCount > 0 ? R.string.no_nearby_caches
: R.string.no_caches;
}
}
public TitleUpdater(ListActivity listActivity, CachesProviderToggler cachesProviderToggler,
DbFrontend dbFrontend, TextSelector textSelector) {
mListActivity = listActivity;
mCachesProviderToggler = cachesProviderToggler;
mDbFrontend = dbFrontend;
mTextSelector = textSelector;
}
public void refresh() {
int sqlCount = mDbFrontend.count(null); // count all caches
int nearestCachesCount = mCachesProviderToggler.getCount();
int title = mTextSelector.getTitle(mCachesProviderToggler.isShowingNearest());
mListActivity.setTitle(mListActivity.getString(title,
nearestCachesCount, sqlCount));
if (0 == nearestCachesCount) {
final int noNearbyCachesText = mTextSelector
.getNoNearbyCachesText(sqlCount);
final TextView emptyTextView = (TextView)mListActivity
.findViewById(android.R.id.empty);
emptyTextView.setText(noNearbyCachesText);
}
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GraphicsGenerator;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Tags;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheSummaryRowInflater.RowViews.CacheNameAttributes;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.DistanceAndBearing;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class GeocacheSummaryRowInflater implements HasDistanceFormatter {
public static class RowViews {
private final TextView mAttributes;
private final TextView mCacheName;
private final TextView mDistance;
private final ImageView mIcon;
private final TextView mId;
private final Resources mResources;
private final CacheNameAttributes mCacheNameAttributes;
RowViews(TextView attributes, TextView cacheName, TextView distance, ImageView icon,
TextView id, Resources resources, CacheNameAttributes cacheNameAttributes) {
mAttributes = attributes;
mCacheName = cacheName;
mDistance = distance;
mIcon = icon;
mId = id;
mResources = resources;
mCacheNameAttributes = cacheNameAttributes;
}
public static class CacheNameAttributes {
void setTextColor(boolean fArchived, boolean fUnavailable,
TextView cacheName) {
if (fArchived)
cacheName.setTextColor(Color.DKGRAY);
else if (fUnavailable)
cacheName.setTextColor(Color.LTGRAY);
else
cacheName.setTextColor(Color.WHITE);
}
void setStrikethrough(boolean fArchived, boolean fUnavailable,
TextView cacheName) {
if (fArchived || fUnavailable)
cacheName.setPaintFlags(cacheName.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
else
cacheName.setPaintFlags(cacheName.getPaintFlags()
& ~Paint.STRIKE_THRU_TEXT_FLAG);
}
}
private CharSequence getFormattedDistance(
DistanceAndBearing distanceAndBearing, float azimuth,
DistanceFormatter distanceFormatter,
BearingFormatter relativeBearingFormatter) {
// Use the slower, more accurate distance for display.
double distance = distanceAndBearing.getDistance();
if (distance == -1) {
return "";
}
final CharSequence formattedDistance = distanceFormatter
.formatDistance((float)distance);
float bearing = distanceAndBearing.getBearing();
final String formattedBearing = relativeBearingFormatter.formatBearing(bearing,
azimuth);
return formattedDistance + " " + formattedBearing;
}
void set(DistanceAndBearing distanceAndBearing, float azimuth,
DistanceFormatter distanceFormatter,
BearingFormatter relativeBearingFormatter,
GraphicsGenerator graphicsGenerator, DbFrontend dbFrontend) {
//CacheType type = geocacheVector.getGeocache().getCacheType();
//mIcon.setImageResource(type.icon());
Geocache geocache = distanceAndBearing.getGeocache();
mIcon.setImageDrawable(geocache.getIcon(mResources, graphicsGenerator, dbFrontend));
CharSequence geocacheId = geocache.getId();
mId.setText(geocacheId);
mAttributes.setText(geocache.getFormattedAttributes());
mCacheName.setText(geocache.getName());
boolean fArchived = dbFrontend.geocacheHasTag(geocacheId,
Tags.ARCHIVED);
boolean fUnavailable = dbFrontend.geocacheHasTag(geocacheId,
Tags.UNAVAILABLE);
mCacheNameAttributes.setTextColor(fArchived, fUnavailable,
mCacheName);
mCacheNameAttributes.setStrikethrough(fArchived, fUnavailable,
mCacheName);
mDistance.setText(getFormattedDistance(distanceAndBearing, azimuth, distanceFormatter,
relativeBearingFormatter));
}
}
private BearingFormatter mBearingFormatter;
private DistanceFormatter mDistanceFormatter;
private final LayoutInflater mLayoutInflater;
private final Resources mResources;
private final GraphicsGenerator mGraphicsGenerator;
private final DbFrontend mDbFrontend;
private final CacheNameAttributes mCacheNameAttributes;
public GeocacheSummaryRowInflater(DistanceFormatter distanceFormatter,
LayoutInflater layoutInflater,
BearingFormatter relativeBearingFormatter, Resources resources,
GraphicsGenerator graphicsGenerator, DbFrontend dbFrontend,
CacheNameAttributes cacheNameAttributes) {
mLayoutInflater = layoutInflater;
mDistanceFormatter = distanceFormatter;
mBearingFormatter = relativeBearingFormatter;
mResources = resources;
mGraphicsGenerator = graphicsGenerator;
mDbFrontend = dbFrontend;
mCacheNameAttributes = cacheNameAttributes;
}
BearingFormatter getBearingFormatter() {
return mBearingFormatter;
}
public View inflate(View convertView) {
if (convertView != null)
return convertView;
// Log.d("GeoBeagle", "SummaryRow::inflate(" + convertView + ")");
View view = mLayoutInflater.inflate(R.layout.cache_row, null);
RowViews rowViews = new RowViews((TextView)view
.findViewById(R.id.txt_gcattributes), ((TextView)view
.findViewById(R.id.txt_cache)), ((TextView)view
.findViewById(R.id.distance)), ((ImageView)view
.findViewById(R.id.gc_row_icon)), ((TextView)view
.findViewById(R.id.txt_gcid)), mResources, mCacheNameAttributes);
view.setTag(rowViews);
return view;
}
public void setBearingFormatter(boolean absoluteBearing) {
mBearingFormatter = absoluteBearing ? new AbsoluteBearingFormatter()
: new RelativeBearingFormatter();
}
public void setData(View view, DistanceAndBearing geocacheVector, float azimuth) {
((RowViews)view.getTag()).set(geocacheVector, azimuth, mDistanceFormatter,
mBearingFormatter, mGraphicsGenerator, mDbFrontend);
}
public void setDistanceFormatter(DistanceFormatter distanceFormatter) {
mDistanceFormatter = distanceFormatter;
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist.presenter;
public class RelativeBearingFormatter implements BearingFormatter {
private static final String[] ARROWS = {
"^", ">", "v", "<",
};
public String formatBearing(float absBearing, float myHeading) {
return ARROWS[((((int)(absBearing - myHeading) + 45 + 720) % 360) / 90)];
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.actions.CacheAction;
import com.google.code.geobeagle.actions.CacheFilterUpdater;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.cachelist.actions.MenuActionSyncGpx;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class GeocacheListController {
public static final String SELECT_CACHE = "SELECT_CACHE";
private final CacheListAdapter mCacheListAdapter;
private final MenuActions mMenuActions;
private final MenuActionSyncGpx mMenuActionSyncGpx;
private final CacheAction mDefaultCacheAction;
private final CacheFilterUpdater mCacheFilterUpdater;
public GeocacheListController(CacheListAdapter cacheListAdapter,
MenuActionSyncGpx menuActionSyncGpx,
MenuActions menuActions,
CacheAction defaultCacheAction,
CacheFilterUpdater cacheFilterUpdater) {
mCacheListAdapter = cacheListAdapter;
mMenuActionSyncGpx = menuActionSyncGpx;
mMenuActions = menuActions;
mDefaultCacheAction = defaultCacheAction;
mCacheFilterUpdater = cacheFilterUpdater;
}
public boolean onCreateOptionsMenu(Menu menu) {
return mMenuActions.onCreateOptionsMenu(menu);
}
public void onListItemClick(ListView l, View v, int position, long id) {
if (position > 0) {
mDefaultCacheAction.act(mCacheListAdapter.getGeocacheAt(position - 1));
} else {
mCacheListAdapter.forceRefresh();
}
}
public boolean onMenuOpened(int featureId, Menu menu) {
return mMenuActions.onMenuOpened(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
return mMenuActions.act(item.getItemId());
}
public void onPause() {
mMenuActionSyncGpx.abort();
}
public void onResume(boolean fImport) {
mCacheFilterUpdater.loadActiveFilter();
mCacheListAdapter.forceRefresh();
if (fImport)
mMenuActionSyncGpx.act();
}
}
| Java |
package com.google.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.IPausable;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityType;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import android.graphics.Color;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class SearchOnlineActivityDelegate {
private final ActivitySaver mActivitySaver;
private final DistanceFormatterManager mDistanceFormatterManager;
private final IPausable mPausable;
private final WebView mWebView;
public SearchOnlineActivityDelegate(WebView webView,
IPausable pausable,
DistanceFormatterManager distanceFormatterManager,
ActivitySaver activitySaver) {
mPausable = pausable;
mWebView = webView;
mDistanceFormatterManager = distanceFormatterManager;
mActivitySaver = activitySaver;
}
public void configureWebView(JsInterface jsInterface) {
mWebView.loadUrl("file:///android_asset/search.html");
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
mWebView.setBackgroundColor(Color.BLACK);
mWebView.addJavascriptInterface(jsInterface, "gb");
}
public void onPause() {
mPausable.onPause();
mActivitySaver.save(ActivityType.SEARCH_ONLINE);
}
public void onResume() {
mPausable.onResume();
mDistanceFormatterManager.setFormatter();
}
}
| Java |
/*
** 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.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.GeoFix;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.R;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import java.util.Locale;
class JsInterface {
private final GeoFixProvider mGeoFixProvider;
private final JsInterfaceHelper mHelper;
static class JsInterfaceHelper {
private final Activity mActivity;
public JsInterfaceHelper(Activity activity) {
mActivity = activity;
}
public void launch(String uri) {
mActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
}
public String getTemplate(int ix) {
return mActivity.getResources().getStringArray(R.array.nearest_objects)[ix];
}
public String getNS(double latitude) {
return latitude > 0 ? "N" : "S";
}
public String getEW(double longitude) {
return longitude > 0 ? "E" : "W";
}
}
public JsInterface(GeoFixProvider geoFixProvider,
JsInterfaceHelper jsInterfaceHelper) {
mHelper = jsInterfaceHelper;
mGeoFixProvider = geoFixProvider;
}
public int atlasQuestOrGroundspeak(int ix) {
final GeoFix location = mGeoFixProvider.getLocation();
final String uriTemplate = mHelper.getTemplate(ix);
mHelper.launch(String.format(Locale.US, uriTemplate, location.getLatitude(), location
.getLongitude()));
return 0;
}
public int openCaching(int ix) {
final GeoFix location = mGeoFixProvider.getLocation();
final String uriTemplate = mHelper.getTemplate(ix);
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
final String NS = mHelper.getNS(latitude);
final String EW = mHelper.getEW(longitude);
final double abs_latitude = Math.abs(latitude);
final double abs_longitude = Math.abs(longitude);
final int lat_h = (int)abs_latitude;
final double lat_m = 60 * (abs_latitude - lat_h);
final int lon_h = (int)abs_longitude;
final double lon_m = 60 * (abs_longitude - lon_h);
mHelper.launch(String.format(Locale.US, uriTemplate, NS, lat_h, lat_m, EW, lon_h, lon_m));
return 0;
}
}
| Java |
/*
** 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.code.geobeagle;
import android.content.Context;
import android.widget.Toast;
public class Toaster {
static public class OneTimeToaster implements IToaster {
public static class OneTimeToasterFactory implements Toaster.ToasterFactory {
@Override
public IToaster getToaster(Toaster toaster) {
return new OneTimeToaster(toaster);
}
}
private boolean mHasShownToaster = false;
private final Toaster mToaster;
public OneTimeToaster(Toaster toaster) {
mToaster = toaster;
}
public void showToast(boolean fCondition) {
if (fCondition && !mHasShownToaster) {
mToaster.showToast();
mHasShownToaster = true;
}
}
}
public static interface ToasterFactory {
IToaster getToaster(Toaster toaster);
}
private final Context mContext;
private final int mDuration;
private final int mResId;
public Toaster(Context context, int resId, int duration) {
mContext = context;
mResId = resId;
mDuration = duration;
}
public void showToast() {
Toast.makeText(mContext, mResId, mDuration).show();
}
}
| Java |
/*
** 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.code.geobeagle;
public interface IToaster {
public void showToast(boolean fCondition);
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.