repo
string | commit
string | message
string | diff
string |
---|---|---|---|
cstim/carcomm
|
7d0bde65d29f31d9984d9ee9088a27c1fc5f3bb9
|
Minor notes.
|
diff --git a/cardroid/.gitignore b/cardroid/.gitignore
index 07eee84..479c192 100644
--- a/cardroid/.gitignore
+++ b/cardroid/.gitignore
@@ -1,3 +1,4 @@
bin
build.xml
-local.properties
\ No newline at end of file
+local.properties
+gen
diff --git a/cardroid/cmdline.txt b/cardroid/cmdline.txt
index 933936d..f56d3f5 100644
--- a/cardroid/cmdline.txt
+++ b/cardroid/cmdline.txt
@@ -1,41 +1,42 @@
## To have SUN java in path:
#export PATH=/usr/lib/jvm/java-6-sun-1.6.0.15/jre/bin:$PATH
# Creating the project:
ANDROIDROOT=$HOME/android-sdk-linux_86
+PATH=$PATH:$ANDROIDROOT/tools
cd $ANDROIDROOT/tools
./android list targets
./android create project \
--target android-3 \
--name carinfo \
--path /home/chs/carinfo \
--activity CarinfoActivity \
--package de.cstimming.carinfo
PROJDIR=$HOME/carinfo
cd $PROJDIR
# Building in debug mode
ant debug
# Starting an emulator
cd $ANDROIDROOT/tools
./android list avds
# I have one Android Virtual Device (AVD) named "test1"; start this
# AVD:
./emulator -avd test1
# Install the application on the currently running emulator
./adb install $PROJDIR/bin/carinfo-debug.apk
# Building my application and installing it to the currently running
# emulator in one step
cd $PROJDIR
ant install
# Compile with the java libraries
CLASSPATH=lib/httpmime-4.0-beta1.jar:lib/apache-mime4j-0.4.jar ant debug
# Uninstall
adb uninstall de.cstimming.carinfo
|
cstim/carcomm
|
1c3f2e127bfb6e4ad64afb02769754d4f3274f2c
|
Revert "Copy the osmdroid code to here..." - doesn't work due to the PNG pictures, somehow.
|
diff --git a/cardroid/.gitignore b/cardroid/.gitignore
index 479c192..07eee84 100644
--- a/cardroid/.gitignore
+++ b/cardroid/.gitignore
@@ -1,4 +1,3 @@
bin
build.xml
-local.properties
-gen
+local.properties
\ No newline at end of file
diff --git a/cardroid/AndroidManifest.xml b/cardroid/AndroidManifest.xml
index b53ec2a..314b76e 100644
--- a/cardroid/AndroidManifest.xml
+++ b/cardroid/AndroidManifest.xml
@@ -1,36 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.cstimming.carinfo"
android:versionCode="1"
android:versionName="1.0">
-
- <uses-sdk android:minSdkVersion="4" />
-
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-
<application android:label="@string/app_name">
<activity android:name=".CarinfoActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
-
- <!--
- If this service exists then the view will use it to get its tiles.
- If you remove this service then the view will use a tile provider directly.
- -->
- <service android:name=".services.OpenStreetMapTileProviderService"
- android:process=":remote"
- android:label="OpenStreetMapTileProviderService">
- <intent-filter>
- <action android:name="org.andnav.osm.services.IOpenStreetMapTileProviderService" />
- </intent-filter>
- </service>
-
</application>
</manifest>
diff --git a/cardroid/default.properties b/cardroid/default.properties
index 9d79b12..4513a1e 100644
--- a/cardroid/default.properties
+++ b/cardroid/default.properties
@@ -1,11 +1,11 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
-target=android-4
+target=android-3
diff --git a/cardroid/gen/de/cstimming/carinfo/R.java b/cardroid/gen/de/cstimming/carinfo/R.java
index 0fb7d2b..326ae46 100644
--- a/cardroid/gen/de/cstimming/carinfo/R.java
+++ b/cardroid/gen/de/cstimming/carinfo/R.java
@@ -1,49 +1,20 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package de.cstimming.carinfo;
public final class R {
public static final class attr {
}
- public static final class drawable {
- public static final int center=0x7f020000;
- public static final int direction_arrow=0x7f020001;
- public static final int icon=0x7f020002;
- public static final int marker_default=0x7f020003;
- public static final int marker_default_focused_base=0x7f020004;
- public static final int navto_small=0x7f020005;
- public static final int next=0x7f020006;
- public static final int person=0x7f020007;
- public static final int previous=0x7f020008;
- public static final int zoom_in=0x7f020009;
- public static final int zoom_out=0x7f02000a;
- }
public static final class layout {
- public static final int main=0x7f030000;
+ public static final int main=0x7f020000;
}
public static final class string {
- public static final int about=0x7f040010;
- public static final int about_message=0x7f040011;
- public static final int app_name=0x7f040009;
- public static final int app_name_itemizedoverlay=0x7f04000b;
- public static final int base=0x7f040004;
- public static final int cloudmade_small=0x7f040007;
- public static final int cloudmade_standard=0x7f040008;
- public static final int cyclemap=0x7f040002;
- public static final int hello=0x7f04000a;
- public static final int hills=0x7f040006;
- public static final int map_mode=0x7f04000d;
- public static final int mapnik=0x7f040001;
- public static final int my_location=0x7f04000e;
- public static final int openareal_sat=0x7f040003;
- public static final int osmarender=0x7f040000;
- public static final int samples=0x7f04000f;
- public static final int topo=0x7f040005;
- public static final int unknown=0x7f04000c;
+ public static final int app_name=0x7f030000;
+ public static final int hello=0x7f030001;
}
}
diff --git a/cardroid/lib/apache-mime4j-0.4.jar b/cardroid/lib/apache-mime4j-0.4.jar
deleted file mode 100644
index b5fe9bf..0000000
Binary files a/cardroid/lib/apache-mime4j-0.4.jar and /dev/null differ
diff --git a/cardroid/lib/httpmime-4.0-beta1.jar b/cardroid/lib/httpmime-4.0-beta1.jar
deleted file mode 100644
index 2564dcf..0000000
Binary files a/cardroid/lib/httpmime-4.0-beta1.jar and /dev/null differ
diff --git a/cardroid/res/drawable/center.png b/cardroid/res/drawable/center.png
deleted file mode 100644
index 025bdad..0000000
Binary files a/cardroid/res/drawable/center.png and /dev/null differ
diff --git a/cardroid/res/drawable/direction_arrow.png b/cardroid/res/drawable/direction_arrow.png
deleted file mode 100644
index e69291f..0000000
Binary files a/cardroid/res/drawable/direction_arrow.png and /dev/null differ
diff --git a/cardroid/res/drawable/icon.png b/cardroid/res/drawable/icon.png
deleted file mode 100644
index b74f1ea..0000000
Binary files a/cardroid/res/drawable/icon.png and /dev/null differ
diff --git a/cardroid/res/drawable/marker_default.png b/cardroid/res/drawable/marker_default.png
deleted file mode 100644
index e161c69..0000000
Binary files a/cardroid/res/drawable/marker_default.png and /dev/null differ
diff --git a/cardroid/res/drawable/marker_default_focused_base.png b/cardroid/res/drawable/marker_default_focused_base.png
deleted file mode 100644
index e9d775d..0000000
Binary files a/cardroid/res/drawable/marker_default_focused_base.png and /dev/null differ
diff --git a/cardroid/res/drawable/navto_small.png b/cardroid/res/drawable/navto_small.png
deleted file mode 100644
index 76518bf..0000000
Binary files a/cardroid/res/drawable/navto_small.png and /dev/null differ
diff --git a/cardroid/res/drawable/next.png b/cardroid/res/drawable/next.png
deleted file mode 100644
index 30560f2..0000000
Binary files a/cardroid/res/drawable/next.png and /dev/null differ
diff --git a/cardroid/res/drawable/person.png b/cardroid/res/drawable/person.png
deleted file mode 100644
index 9f9db93..0000000
Binary files a/cardroid/res/drawable/person.png and /dev/null differ
diff --git a/cardroid/res/drawable/previous.png b/cardroid/res/drawable/previous.png
deleted file mode 100644
index 0fdbc52..0000000
Binary files a/cardroid/res/drawable/previous.png and /dev/null differ
diff --git a/cardroid/res/drawable/zoom_in.png b/cardroid/res/drawable/zoom_in.png
deleted file mode 100644
index 36845e7..0000000
Binary files a/cardroid/res/drawable/zoom_in.png and /dev/null differ
diff --git a/cardroid/res/drawable/zoom_out.png b/cardroid/res/drawable/zoom_out.png
deleted file mode 100644
index e327d96..0000000
Binary files a/cardroid/res/drawable/zoom_out.png and /dev/null differ
diff --git a/cardroid/res/values-de/renderers.xml b/cardroid/res/values-de/renderers.xml
deleted file mode 100644
index 2208825..0000000
--- a/cardroid/res/values-de/renderers.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-<string name="base">OSM Basislayer</string>
-<string name="topo">Topographisch</string><string name="hills">Relief</string><string name="cyclemap">Fahrradkarte</string>
-
-
-
-</resources>
diff --git a/cardroid/res/values-de/strings.xml b/cardroid/res/values-de/strings.xml
index b1e5fe5..c69c781 100644
--- a/cardroid/res/values-de/strings.xml
+++ b/cardroid/res/values-de/strings.xml
@@ -1,9 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">CarDroid Prototyp</string>
<string name="hello">Hallo Welt, CarinfoActivity</string>
-
-<string name="map_mode">Kartenmodus</string>
-<string name="my_location">Standort</string>
-<string name="about">Ãber</string>
-<string name="about_message">Diese Software benutzt Kartenmaterial von OpenStreetMap.org</string></resources>
+</resources>
diff --git a/cardroid/res/values/renderers.xml b/cardroid/res/values/renderers.xml
deleted file mode 100644
index cab3c47..0000000
--- a/cardroid/res/values/renderers.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <string name="osmarender">OsmaRender</string>
- <string name="mapnik">Mapnik</string>
- <string name="cyclemap">Cycle Map</string>
- <string name="openareal_sat">OpenArialMap</string>
- <string name="base">OSM base layer</string>
- <string name="topo">Topographic</string>
- <string name="hills">Hills</string>
- <string name="cloudmade_small">Cloudmade (small tiles)</string>
- <string name="cloudmade_standard">Cloudmade (Standard tiles)</string>
-</resources>
diff --git a/cardroid/res/values/strings.xml b/cardroid/res/values/strings.xml
index 802bdc6..25f2db9 100644
--- a/cardroid/res/values/strings.xml
+++ b/cardroid/res/values/strings.xml
@@ -1,13 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">CarDroid Prototype</string>
<string name="hello">Hello World, CarinfoActivity</string>
-
-<string name="app_name_itemizedoverlay">OSMViewer ItemizedOverlay</string>
-<string name="unknown">Unknown</string>
-<string name="map_mode">Map mode</string>
-<string name="my_location">My location</string>
-<string name="samples">Samples</string>
-<string name="about">About</string>
-<string name="about_message">This software uses map data provided by <b>OpenStreetMap.org</b></string>
</resources>
diff --git a/cardroid/src/org/andnav/osm/R.java b/cardroid/src/org/andnav/osm/R.java
deleted file mode 100644
index 0a3903e..0000000
--- a/cardroid/src/org/andnav/osm/R.java
+++ /dev/null
@@ -1,31 +0,0 @@
-// Dummy R.java to redirect to a generated one
-
-package org.andnav.osm;
-
-public final class R {
-
- public static final class drawable {
- public static final int center = de.cstimming.carinfo.R.drawable.center;
- public static final int direction_arrow = de.cstimming.carinfo.R.drawable.direction_arrow;
- public static final int marker_default = de.cstimming.carinfo.R.drawable.marker_default;
- public static final int marker_default_focused_base = de.cstimming.carinfo.R.drawable.marker_default_focused_base;
- public static final int navto_small = de.cstimming.carinfo.R.drawable.navto_small;
- public static final int next = de.cstimming.carinfo.R.drawable.next;
- public static final int person = de.cstimming.carinfo.R.drawable.person;
- public static final int previous = de.cstimming.carinfo.R.drawable.previous;
- }
-
- public static final class string {
- public static final int osmarender = de.cstimming.carinfo.R.string.osmarender;
- public static final int mapnik = de.cstimming.carinfo.R.string.mapnik;
- public static final int cyclemap = de.cstimming.carinfo.R.string.cyclemap;
- public static final int openareal_sat = de.cstimming.carinfo.R.string.openareal_sat;
- public static final int hills = de.cstimming.carinfo.R.string.hills;
- public static final int base = de.cstimming.carinfo.R.string.base;
- public static final int topo = de.cstimming.carinfo.R.string.topo;
- public static final int unknown = de.cstimming.carinfo.R.string.unknown;
- public static final int cloudmade_small = de.cstimming.carinfo.R.string.cloudmade_small;
- public static final int cloudmade_standard = de.cstimming.carinfo.R.string.cloudmade_standard;
- }
-
-}
diff --git a/cardroid/src/org/andnav/osm/contributor/GpxToPHPUploader.java b/cardroid/src/org/andnav/osm/contributor/GpxToPHPUploader.java
deleted file mode 100644
index a7d2c36..0000000
--- a/cardroid/src/org/andnav/osm/contributor/GpxToPHPUploader.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package org.andnav.osm.contributor;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.util.ArrayList;
-
-import org.andnav.osm.contributor.util.RecordedGeoPoint;
-import org.andnav.osm.contributor.util.RecordedRouteGPXFormatter;
-import org.andnav.osm.contributor.util.Util;
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.mime.MultipartEntity;
-import org.apache.http.entity.mime.content.InputStreamBody;
-import org.apache.http.impl.client.DefaultHttpClient;
-
-import android.util.Log;
-
-
-public class GpxToPHPUploader {
-
- protected static final String UPLOADSCRIPT_URL = "http://www.PLACEYOURDOMAINHERE.com/anyfolder/gpxuploader/upload.php";
-
- public static void uploadAsync(final ArrayList<RecordedGeoPoint> recordedGeoPoints){
- new Thread(new Runnable(){
- @Override
- public void run() {
- try{
- if(!Util.isSufficienDataForUpload(recordedGeoPoints)) return;
-
- final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes());
- final HttpClient httpClient = new DefaultHttpClient();
-
- final HttpPost request = new HttpPost(UPLOADSCRIPT_URL);
-
- // create the multipart request and add the parts to it
- final MultipartEntity requestEntity = new MultipartEntity();
- requestEntity.addPart("gpxfile", new InputStreamBody(gpxInputStream, "" + System.currentTimeMillis() + ".gpx"));
-
- httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
-
- request.setEntity(requestEntity);
-
- final HttpResponse response = httpClient.execute(request);
- final int status = response.getStatusLine().getStatusCode();
-
- if (status != HttpStatus.SC_OK) {
- Log.e("GPXUploader", "status != HttpStatus.SC_OK");
- } else {
- final Reader r = new InputStreamReader(new BufferedInputStream(response.getEntity().getContent()));
- // see above
- final char[] buf = new char[8 * 1024];
- int read;
- final StringBuilder sb = new StringBuilder();
- while((read = r.read(buf)) != -1)
- sb.append(buf, 0, read);
-
- Log.d("GPXUploader", "Response: " + sb.toString());
- }
- }catch (Exception e){
-// Log.e(DEBUGTAG, "OSMUpload Error", e);
- }
- }
- }).start();
- }
-}
diff --git a/cardroid/src/org/andnav/osm/contributor/OSMUploader.java b/cardroid/src/org/andnav/osm/contributor/OSMUploader.java
deleted file mode 100644
index 5737018..0000000
--- a/cardroid/src/org/andnav/osm/contributor/OSMUploader.java
+++ /dev/null
@@ -1,223 +0,0 @@
-package org.andnav.osm.contributor;
-
-/**
- * Copyright by Christof Dallermassl
- * This program is free software and licensed under GPL.
- *
- * Original JAVA-Code ported for Android compatibility by Nicolas 'plusminus' Gramlich.
- */
-
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.GregorianCalendar;
-
-import org.andnav.osm.contributor.util.RecordedGeoPoint;
-import org.andnav.osm.contributor.util.RecordedRouteGPXFormatter;
-import org.andnav.osm.contributor.util.Util;
-import org.andnav.osm.contributor.util.constants.OpenStreetMapContributorConstants;
-import org.andnav.osm.util.constants.OpenStreetMapConstants;
-
-
-/**
- * Small java class that allows to upload gpx files to www.openstreetmap.org via its api call.
- *
- * @author cdaller
- * @author Nicolas Gramlich
- */
-public class OSMUploader implements OpenStreetMapConstants, OpenStreetMapContributorConstants{
- // ===========================================================
- // Constants
- // ===========================================================
-
- public static final String API_VERSION = "0.5";
- private static final int BUFFER_SIZE = 65535;
- private static final String BASE64_ENC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- private static final String BOUNDARY = "----------------------------d10f7aa230e8";
- private static final String LINE_END = "\r\n";
-
- private static final String DEFAULT_DESCRIPTION = "AndNav - automatically created route.";
- private static final String DEFAULT_TAGS = "AndNav";
-
- public static final SimpleDateFormat pseudoFileNameFormat = new SimpleDateFormat("yyyyMMdd'_'HHmmss'_'SSS");
- private static final SimpleDateFormat autoTagFormat = new SimpleDateFormat("MMMM yyyy");
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- /**
- * Uses OSMConstants.OSM_USERNAME and OSMConstants.OSM_PASSWORD as username/password.
- * Description will be <code>DEFAULT_DESCRIPTION</code>, tags will be automatically generated (i.e. "<code>October 2008</code>")
- * NOTE: This method is not blocking!
- * @param gpxInputStream the InputStream containing the gpx-data.
- * @throws IOException
- */
- public static void uploadAsync(final ArrayList<RecordedGeoPoint> recordedGeoPoints) {
- uploadAsync( DEFAULT_DESCRIPTION, DEFAULT_TAGS, true, recordedGeoPoints);
- }
-
- /**
- * Uses OSMConstants.OSM_USERNAME and OSMConstants.OSM_PASSWORD as username/password.
- * The 'filename' will be the current <code>timestamp.gpx</code> (i.e. "20081231_234815_912.gpx")
- * NOTE: This method is not blocking!
- * @param description <code>not null</code>
- * @param tags <code>not null</code>
- * @param addDateTags adds Date Tags to the existing Tags (i.e. "October 2008")
- * @param gpxInputStreaman the InputStream containing the gpx-data.
- * @throws IOException
- */
- public static void uploadAsync(final String description, final String tags, final boolean addDateTags, final ArrayList<RecordedGeoPoint> recordedGeoPoints) {
- uploadAsync(OSM_USERNAME, OSM_PASSWORD, description, tags, addDateTags, recordedGeoPoints, pseudoFileNameFormat.format(new GregorianCalendar().getTime()) + "_" + OSM_USERNAME + ".gpx");
- }
-
-
- /**
- * NOTE: This method is not blocking! (Code runs in thread)
- * @param username <code>not null</code> and <code>not empty</code>. Valid OSM-username
- * @param password <code>not null</code> and <code>not empty</code>. Valid password to the OSM-username.
- * @param description <code>not null</code>
- * @param tags if <code>null</code> addDateTags is treated as <code>true</code>
- * @param addDateTags adds Date Tags to the existing Tags (i.e. "<code>October 2008</code>")
- * @param gpxInputStream the InputStream containing the gpx-data.
- * @param pseudoFileName ending with "<code>.gpx</code>"
- * @throws IOException
- */
- public static void uploadAsync(final String username, final String password, final String description, final String tags, final boolean addDateTags, final ArrayList<RecordedGeoPoint> recordedGeoPoints, final String pseudoFileName) {
- if(username == null || username.length() == 0) return;
- if(password == null || password.length() == 0) return;
- if(description == null || description.length() == 0) return;
- if(tags == null || tags.length() == 0) return;
- if(pseudoFileName == null || pseudoFileName.endsWith(".gpx")) return;
-
- new Thread(new Runnable(){
- @Override
- public void run() {
- if(!Util.isSufficienDataForUpload(recordedGeoPoints)) return;
-
- final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes());
-
- String tagsToUse = tags;
- if(addDateTags || tagsToUse == null)
- if(tagsToUse == null)
- tagsToUse = autoTagFormat.format(new GregorianCalendar().getTime());
- else
- tagsToUse = tagsToUse + " " + autoTagFormat.format(new GregorianCalendar().getTime());
-
-// Log.d(DEBUGTAG, "Uploading " + pseudoFileName + " to openstreetmap.org");
- try {
- //String urlGpxName = URLEncoder.encode(gpxName.replaceAll("\\.;&?,/","_"), "UTF-8");
- final String urlDesc = (description == null) ? DEFAULT_DESCRIPTION : description.replaceAll("\\.;&?,/","_");
- final String urlTags = (tagsToUse == null) ? DEFAULT_TAGS : tagsToUse.replaceAll("\\\\.;&?,/","_");
- final URL url = new URL("http://www.openstreetmap.org/api/" + API_VERSION + "/gpx/create");
-// Log.d(DEBUGTAG, "Destination Url: " + url);
- final HttpURLConnection con = (HttpURLConnection) url.openConnection();
- con.setConnectTimeout(15000);
- con.setRequestMethod("POST");
- con.setDoOutput(true);
- con.addRequestProperty("Authorization", "Basic "+encodeBase64(username+":"+password));
- con.addRequestProperty("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
- con.addRequestProperty("Connection", "close"); // counterpart of keep-alive
- con.addRequestProperty("Expect", "");
-
- con.connect();
- DataOutputStream out = new DataOutputStream(new BufferedOutputStream(con.getOutputStream()));
- // DataOutputStream out = new DataOutputStream(System.out);
-
- writeContentDispositionFile(out, "file", gpxInputStream, pseudoFileName);
- writeContentDisposition(out, "description", urlDesc);
- writeContentDisposition(out, "tags", urlTags);
-
- writeContentDisposition(out, "public", "1");
-
- out.writeBytes("--" + BOUNDARY + "--" + LINE_END);
- out.flush();
-
- final int retCode = con.getResponseCode();
- String retMsg = con.getResponseMessage();
-// Log.d(DEBUGTAG, "\nreturn code: "+retCode + " " + retMsg);
- if (retCode != 200) {
- // Look for a detailed error message from the server
- if (con.getHeaderField("Error") != null)
- retMsg += "\n" + con.getHeaderField("Error");
- con.disconnect();
- throw new RuntimeException(retCode+" "+retMsg);
- }
- out.close();
- con.disconnect();
- } catch(Exception e) {
-// Log.e(DEBUGTAG, "OSMUpload Error", e);
- }
- }
-
- }, "OSMUpload-Thread").start();
- }
-
- public static void upload(final String username, final String password, final String description, final String tags, final boolean addDateTags, final ArrayList<RecordedGeoPoint> recordedGeoPoints, final String pseudoFileName) throws IOException{
- uploadAsync(username, password, description, tags, addDateTags, recordedGeoPoints, pseudoFileName);
- }
-
- /**
- * @param out
- * @param string
- * @param gpxFile
- * @throws IOException
- */
- private static void writeContentDispositionFile(final DataOutputStream out, final String name, final InputStream gpxInputStream, final String pseudoFileName) throws IOException {
- out.writeBytes("--" + BOUNDARY + LINE_END);
- out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + pseudoFileName + "\"" + LINE_END);
- out.writeBytes("Content-Type: application/octet-stream" + LINE_END);
- out.writeBytes(LINE_END);
-
- final byte[] buffer = new byte[BUFFER_SIZE];
- //int fileLen = (int)gpxFile.length();
- int read;
- int sumread = 0;
- final InputStream in = new BufferedInputStream(gpxInputStream);
-// Log.d(DEBUGTAG, "Transferring data to server");
- while((read = in.read(buffer)) >= 0) {
- out.write(buffer, 0, read);
- out.flush();
- sumread += read;
- }
- in.close();
- out.writeBytes(LINE_END);
- }
-
- /**
- * @param string
- * @param urlDesc
- * @throws IOException
- */
- private static void writeContentDisposition(final DataOutputStream out, final String name, final String value) throws IOException {
- out.writeBytes("--" + BOUNDARY + LINE_END);
- out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + LINE_END);
- out.writeBytes(LINE_END);
- out.writeBytes(value + LINE_END);
- }
-
- private static String encodeBase64(final String s) {
- StringBuilder out = new StringBuilder();
- for (int i = 0; i < (s.length()+2)/3; ++i) {
- int l = Math.min(3, s.length()-i*3);
- final String buf = s.substring(i*3, i*3+l);
- out.append(BASE64_ENC.charAt(buf.charAt(0)>>2));
- out.append(BASE64_ENC.charAt((buf.charAt(0) & 0x03) << 4 | (l==1?0:(buf.charAt(1) & 0xf0) >> 4)));
- out.append(l>1 ? BASE64_ENC.charAt((buf.charAt(1) & 0x0f) << 2 | (l==2 ? 0 : (buf.charAt(2) & 0xc0) >> 6)) : '=');
- out.append(l>2 ? BASE64_ENC.charAt(buf.charAt(2) & 0x3f) : '=');
- }
- return out.toString();
- }
-}
\ No newline at end of file
diff --git a/cardroid/src/org/andnav/osm/contributor/RouteRecorder.java b/cardroid/src/org/andnav/osm/contributor/RouteRecorder.java
deleted file mode 100644
index 0c953c3..0000000
--- a/cardroid/src/org/andnav/osm/contributor/RouteRecorder.java
+++ /dev/null
@@ -1,66 +0,0 @@
-// Created by plusminus on 12:28:16 - 21.09.2008
-package org.andnav.osm.contributor;
-
-import java.util.ArrayList;
-
-import org.andnav.osm.contributor.util.RecordedGeoPoint;
-import org.andnav.osm.util.GeoPoint;
-
-import android.location.Location;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class RouteRecorder {
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final ArrayList<RecordedGeoPoint> mRecords = new ArrayList<RecordedGeoPoint>();
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public ArrayList<RecordedGeoPoint> getRecordedGeoPoints() {
- return this.mRecords;
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- public void add(final Location aLocation, final int aNumSatellites){
- this.mRecords.add(new RecordedGeoPoint(
- (int)(aLocation.getLatitude() * 1E6),
- (int)(aLocation.getLongitude() * 1E6),
- System.currentTimeMillis(),
- aNumSatellites));
- }
-
- public void add(final GeoPoint aGeoPoint, final int aNumSatellites){
- this.mRecords.add(new RecordedGeoPoint(
- aGeoPoint.getLatitudeE6(),
- aGeoPoint.getLongitudeE6(),
- System.currentTimeMillis(),
- aNumSatellites));
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/contributor/util/RecordedGeoPoint.java b/cardroid/src/org/andnav/osm/contributor/util/RecordedGeoPoint.java
deleted file mode 100644
index 6240adb..0000000
--- a/cardroid/src/org/andnav/osm/contributor/util/RecordedGeoPoint.java
+++ /dev/null
@@ -1,69 +0,0 @@
-// Created by plusminus on 12:29:23 - 21.09.2008
-package org.andnav.osm.contributor.util;
-
-import org.andnav.osm.util.GeoPoint;
-import org.andnav.osm.util.constants.OpenStreetMapConstants;
-
-/**
- * Extends the {@link GeoPoint} with a timeStamp.
- * @author Nicolas Gramlich
- */
-public class RecordedGeoPoint extends GeoPoint implements OpenStreetMapConstants {
-
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final long mTimeStamp;
- protected final int mNumSatellites;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public RecordedGeoPoint(final int latitudeE6, final int longitudeE6) {
- this(latitudeE6, longitudeE6, System.currentTimeMillis(), NOT_SET);
- }
-
- public RecordedGeoPoint(final int latitudeE6, final int longitudeE6, final long aTimeStamp, final int aNumSatellites) {
- super(latitudeE6, longitudeE6);
- this.mTimeStamp = aTimeStamp;
- this.mNumSatellites = aNumSatellites;
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public long getTimeStamp() {
- return this.mTimeStamp;
- }
-
- public double getLatitudeAsDouble(){
- return this.getLatitudeE6() / 1E6;
- }
-
- public double getLongitudeAsDouble(){
- return this.getLongitudeE6() / 1E6;
- }
-
- public int getNumSatellites(){
- return this.mNumSatellites;
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/contributor/util/RecordedRouteGPXFormatter.java b/cardroid/src/org/andnav/osm/contributor/util/RecordedRouteGPXFormatter.java
deleted file mode 100644
index abb34b9..0000000
--- a/cardroid/src/org/andnav/osm/contributor/util/RecordedRouteGPXFormatter.java
+++ /dev/null
@@ -1,118 +0,0 @@
-// Created by plusminus on 13:23:45 - 21.09.2008
-package org.andnav.osm.contributor.util;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Formatter;
-import java.util.List;
-
-import org.andnav.osm.contributor.util.constants.OpenStreetMapContributorConstants;
-import org.andnav.osm.util.constants.OpenStreetMapConstants;
-
-/**
- * Class capable of formatting a List of Points to the GPX 1.1 format.
- * @author Nicolas Gramlich
- *
- */
-public class RecordedRouteGPXFormatter implements OpenStreetMapContributorConstants, OpenStreetMapConstants{
- // ===========================================================
- // Constants
- // ===========================================================
-
- private static final String XML_VERSION = "<?xml version=\"1.0\"?>";
- private static final String GPX_VERSION = "1.1";
- private static final String GPX_TAG = "<gpx version=\"" + GPX_VERSION + "\" creator=\"%s\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/1\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">";
- private static final String GPX_TAG_CLOSE = "</gpx>";
- private static final String GPX_TAG_TIME = "<time>%s</time>";
- private static final String GPX_TAG_TRACK = "<trk>";
- private static final String GPX_TAG_TRACK_CLOSE = "</trk>";
- private static final String GPX_TAG_TRACK_NAME = "<name>%s</name>";
- private static final String GPX_TAG_TRACK_SEGMENT = "<trkseg>";
- private static final String GPX_TAG_TRACK_SEGMENT_CLOSE = "</trkseg>";
- private static final String GPX_TAG_TRACK_SEGMENT_POINT = "<trkpt lat=\"%f\" lon=\"%f\">";
- private static final String GPX_TAG_TRACK_SEGMENT_POINT_CLOSE = "</trkpt>";
- private static final String GPX_TAG_TRACK_SEGMENT_POINT_TIME = "<time>%s</time>";
- private static final String GPX_TAG_TRACK_SEGMENT_POINT_SAT = "<sat>%d</sat>";
-
-
- private static final SimpleDateFormat formatterCompleteDateTime = new SimpleDateFormat("yyyyMMdd'_'HHmmss");
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
- /**
- * Creates a String in the following XML format:
- * <PRE><?xml version="1.0"?>
- * <gpx version="1.1" creator="AndNav - http://www.andnav.org - Android Navigation System" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
- * <time>2008-09-22T00:46:20Z</time>
- * <trk>
- * <name>plusminus--yyyyMMdd_HHmmss-yyyyMMdd_HHmmss</name>
- * <trkseg>
- * <trkpt lat="49.472767" lon="8.654174">
- * <time>2008-09-22T00:46:20Z</time>
- * </trkpt>
- * <trkpt lat="49.472797" lon="8.654102">
- * <time>2008-09-22T00:46:35Z</time>
- * </trkpt>
- * <trkpt lat="49.472802" lon="8.654185">
- * <time>2008-09-22T00:46:50Z</time>
- * </trkpt>
- * </trkseg>
- * </trk>
- * </gpx></PRE>
- *
- */
- public static String create(final List<RecordedGeoPoint> someRecords) throws IllegalArgumentException {
- if(someRecords == null)
- throw new IllegalArgumentException("Records may not be null.");
-
- if(someRecords.size() == 0)
- throw new IllegalArgumentException("Records size == 0");
-
- final StringBuilder sb = new StringBuilder();
- final Formatter f = new Formatter(sb);
- sb.append(XML_VERSION);
- f.format(GPX_TAG, OSM_CREATOR_INFO);
- f.format(GPX_TAG_TIME, Util.convertTimestampToUTCString(System.currentTimeMillis()));
- sb.append(GPX_TAG_TRACK);
- f.format(GPX_TAG_TRACK_NAME, OSM_USERNAME + "--"
- + formatterCompleteDateTime.format(new Date(someRecords.get(0).getTimeStamp()).getTime())
- + "-"
- + formatterCompleteDateTime.format(new Date(someRecords.get(someRecords.size() - 1).getTimeStamp()).getTime()));
- sb.append(GPX_TAG_TRACK_SEGMENT);
-
- for (RecordedGeoPoint rgp : someRecords) {
- f.format(GPX_TAG_TRACK_SEGMENT_POINT, rgp.getLatitudeAsDouble(), rgp.getLongitudeAsDouble());
- f.format(GPX_TAG_TRACK_SEGMENT_POINT_TIME, Util.convertTimestampToUTCString(rgp.getTimeStamp()));
- if(rgp.mNumSatellites != NOT_SET)
- f.format(GPX_TAG_TRACK_SEGMENT_POINT_SAT, rgp.mNumSatellites);
- sb.append(GPX_TAG_TRACK_SEGMENT_POINT_CLOSE);
- }
-
- sb.append(GPX_TAG_TRACK_SEGMENT_CLOSE)
- .append(GPX_TAG_TRACK_CLOSE)
- .append(GPX_TAG_CLOSE);
-
- return sb.toString();
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/contributor/util/Util.java b/cardroid/src/org/andnav/osm/contributor/util/Util.java
deleted file mode 100644
index 10dc0e1..0000000
--- a/cardroid/src/org/andnav/osm/contributor/util/Util.java
+++ /dev/null
@@ -1,69 +0,0 @@
-// Created by plusminus on 13:24:05 - 21.09.2008
-package org.andnav.osm.contributor.util;
-
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.TimeZone;
-
-import org.andnav.osm.contributor.util.constants.OpenStreetMapContributorConstants;
-import org.andnav.osm.util.BoundingBoxE6;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class Util implements OpenStreetMapContributorConstants{
- // ===========================================================
- // Constants
- // ===========================================================
-
- public static final SimpleDateFormat UTCSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
- {
- UTCSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
- }
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- public static final String convertTimestampToUTCString(final long aTimestamp){
- return UTCSimpleDateFormat.format(new Date(aTimestamp));
- }
-
- public static boolean isSufficienDataForUpload(final ArrayList<RecordedGeoPoint> recordedGeoPoints){
- if(recordedGeoPoints == null)
- return false;
-
- if(recordedGeoPoints.size() < MINGEOPOINTS_FOR_OSM_CONTRIBUTION)
- return false;
-
- final BoundingBoxE6 bb = BoundingBoxE6.fromGeoPoints(recordedGeoPoints);
- final int diagMeters = bb.getDiagonalLengthInMeters();
- if(diagMeters < MINDIAGONALMETERS_FOR_OSM_CONTRIBUTION)
- return false;
-
- return true;
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/contributor/util/constants/OpenStreetMapContributorConstants.java b/cardroid/src/org/andnav/osm/contributor/util/constants/OpenStreetMapContributorConstants.java
deleted file mode 100644
index 016b2fb..0000000
--- a/cardroid/src/org/andnav/osm/contributor/util/constants/OpenStreetMapContributorConstants.java
+++ /dev/null
@@ -1,27 +0,0 @@
-// Created by plusminus on 14:11:09 - 21.09.2008
-package org.andnav.osm.contributor.util.constants;
-
-/**
- *
- * This class contains constants used by the contributor package.
- *
- * @author Nicolas Gramlich
- *
- */
-public interface OpenStreetMapContributorConstants {
- // ===========================================================
- // Final Fields
- // ===========================================================
-
- public static final String OSM_USERNAME = "PUT_YOUR_USERNAME_HERE";
- public static final String OSM_PASSWORD = "PUT_YOUR_PASSWORD_HERE";
-
- public static final int MINGEOPOINTS_FOR_OSM_CONTRIBUTION = 100;
- public static final int MINDIAGONALMETERS_FOR_OSM_CONTRIBUTION = 300;
-
- public static final String OSM_CREATOR_INFO = "AndNav - http://www.andnav.org - Android Navigation System";
-
- // ===========================================================
- // Methods
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderService.aidl b/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderService.aidl
deleted file mode 100644
index 52502cd..0000000
--- a/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderService.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.andnav.osm.services;
-
-import org.andnav.osm.services.IOpenStreetMapTileProviderServiceCallback;
-
-interface IOpenStreetMapTileProviderService {
-
-/**
- * Set the callback for tile completions.
- * @param callback the callback to notify when the request completes
- */
-void setCallback(in IOpenStreetMapTileProviderServiceCallback callback);
-
-/**
- * Initiate a request for a map tile.
- * When the request has completed it will call the callback previously set in setCallback.
- * @param rendererID
- * @param zoomLevel
- * @param tileX
- * @param tileY
- * @param callback the callback to notify when the request completes
- */
-void requestMapTile(in int rendererID, in int zoomLevel, in int tileX, in int tileY);
-
-}
diff --git a/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderServiceCallback.aidl b/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderServiceCallback.aidl
deleted file mode 100644
index f465a8b..0000000
--- a/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderServiceCallback.aidl
+++ /dev/null
@@ -1,15 +0,0 @@
-package org.andnav.osm.services;
-
-interface IOpenStreetMapTileProviderServiceCallback {
-
-/**
- * The map tile request has completed.
- * @param rendererID
- * @param zoomLevel
- * @param tileX
- * @param tileY
- * @param aTilePath the path of the requested tile, or null if request has completed without returning a tile path
- */
-void mapTileRequestCompleted(in int rendererID, in int zoomLevel, in int tileX, in int tileY, in String aTilePath);
-
-}
diff --git a/cardroid/src/org/andnav/osm/services/OpenStreetMapTileProviderService.java b/cardroid/src/org/andnav/osm/services/OpenStreetMapTileProviderService.java
deleted file mode 100644
index 0c0be65..0000000
--- a/cardroid/src/org/andnav/osm/services/OpenStreetMapTileProviderService.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package org.andnav.osm.services;
-
-import org.andnav.osm.services.constants.OpenStreetMapServiceConstants;
-import org.andnav.osm.tileprovider.IOpenStreetMapTileProviderCallback;
-import org.andnav.osm.tileprovider.OpenStreetMapTile;
-import org.andnav.osm.tileprovider.OpenStreetMapTileFilesystemProvider;
-
-import android.app.Service;
-import android.content.Intent;
-import android.content.res.Configuration;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.util.Log;
-
-/**
- * The OpenStreetMapTileProviderService can download map tiles from a server
- * and stores them in a file system cache.
- * @author Manuel Stahl
- */
-public class OpenStreetMapTileProviderService extends Service implements OpenStreetMapServiceConstants, IOpenStreetMapTileProviderCallback {
-
- private static final String DEBUGTAG = "OSM_TILE_PROVIDER_SERVICE";
-
- private OpenStreetMapTileFilesystemProvider mFileSystemProvider;
- private IOpenStreetMapTileProviderServiceCallback mCallback;
-
- @Override
- public void onCreate() {
- super.onCreate();
- mFileSystemProvider = new OpenStreetMapTileFilesystemProvider(this);
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return mBinder;
- }
-
- @Override
- public void onConfigurationChanged(Configuration pNewConfig) {
- if(DEBUGMODE)
- Log.d(DEBUGTAG, "onConfigurationChanged");
- super.onConfigurationChanged(pNewConfig);
- }
-
- @Override
- public void onDestroy() {
- if(DEBUGMODE)
- Log.d(DEBUGTAG, "onDestroy");
- mFileSystemProvider.stopWorkers();
- super.onDestroy();
- }
-
- @Override
- public void onLowMemory() {
- if(DEBUGMODE)
- Log.d(DEBUGTAG, "onLowMemory");
- super.onLowMemory();
- }
-
- @Override
- public void onRebind(Intent pIntent) {
- if(DEBUGMODE)
- Log.d(DEBUGTAG, "onRebind");
- super.onRebind(pIntent);
- }
-
- @Override
- public void onStart(Intent pIntent, int pStartId) {
- if(DEBUGMODE)
- Log.d(DEBUGTAG, "onStart");
- super.onStart(pIntent, pStartId);
- }
-
- @Override
- public boolean onUnbind(Intent pIntent) {
- if(DEBUGMODE)
- Log.d(DEBUGTAG, "onUnbind");
- return super.onUnbind(pIntent);
- }
-
- @Override
- public void mapTileRequestCompleted(final OpenStreetMapTile pTile, final String pTilePath) {
- try {
- mCallback.mapTileRequestCompleted(pTile.getRendererId(), pTile.getZoomLevel(), pTile.getX(), pTile.getY(), pTilePath);
- } catch (final RemoteException e) {
- Log.e(DEBUGTAG, "Error invoking callback", e);
- }
- }
-
- /**
- * The IRemoteInterface is defined through IDL
- */
- private final IOpenStreetMapTileProviderService.Stub mBinder = new IOpenStreetMapTileProviderService.Stub() {
- @Override
- public void setCallback(final IOpenStreetMapTileProviderServiceCallback pCallback) throws RemoteException {
- mCallback = pCallback;
- }
- @Override
- public void requestMapTile(int rendererID, int zoomLevel, int tileX, int tileY) throws RemoteException {
- OpenStreetMapTile tile = new OpenStreetMapTile(rendererID, zoomLevel, tileX, tileY);
- mFileSystemProvider.loadMapTileAsync(tile);
- }
- };
-
-}
diff --git a/cardroid/src/org/andnav/osm/services/constants/OpenStreetMapServiceConstants.java b/cardroid/src/org/andnav/osm/services/constants/OpenStreetMapServiceConstants.java
deleted file mode 100644
index 07a8a47..0000000
--- a/cardroid/src/org/andnav/osm/services/constants/OpenStreetMapServiceConstants.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.andnav.osm.services.constants;
-
-
-/**
- *
- * This class contains constants used by the service.
- *
- * @author Neil Boyd
- *
- */
-public interface OpenStreetMapServiceConstants {
- // ===========================================================
- // Final Fields
- // ===========================================================
-
- public static final boolean DEBUGMODE = false;
-
- // ===========================================================
- // Methods
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/IOpenStreetMapTileProviderCallback.java b/cardroid/src/org/andnav/osm/tileprovider/IOpenStreetMapTileProviderCallback.java
deleted file mode 100644
index 0aac24e..0000000
--- a/cardroid/src/org/andnav/osm/tileprovider/IOpenStreetMapTileProviderCallback.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package org.andnav.osm.tileprovider;
-
-public interface IOpenStreetMapTileProviderCallback {
-
- /**
- * The map tile request has completed.
- * @param pTile the tile request that has completed
- * @param aTilePath the path of the requested tile, or null if request has completed without returning a tile path
- */
- void mapTileRequestCompleted(OpenStreetMapTile pTile, String aTilePath);
-
-}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapAsyncTileProvider.java b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapAsyncTileProvider.java
deleted file mode 100644
index 08dfd48..0000000
--- a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapAsyncTileProvider.java
+++ /dev/null
@@ -1,171 +0,0 @@
-package org.andnav.osm.tileprovider;
-
-import java.util.ConcurrentModificationException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-
-import org.andnav.osm.tileprovider.constants.OpenStreetMapTileProviderConstants;
-
-import android.util.Log;
-
-public abstract class OpenStreetMapAsyncTileProvider implements OpenStreetMapTileProviderConstants {
-
- private final int mThreadPoolSize;
- private final ThreadGroup mThreadPool = new ThreadGroup(debugtag());
- private final HashMap<OpenStreetMapTile, Object> mWorking;
- final LinkedHashMap<OpenStreetMapTile, Object> mPending;
- private static final Object PRESENT = new Object();
-
- protected final IOpenStreetMapTileProviderCallback mCallback;
-
- public OpenStreetMapAsyncTileProvider(final IOpenStreetMapTileProviderCallback pCallback, final int aThreadPoolSize, final int aPendingQueueSize) {
- mCallback = pCallback;
- mThreadPoolSize = aThreadPoolSize;
- mWorking = new HashMap<OpenStreetMapTile, Object>();
- mPending = new LinkedHashMap<OpenStreetMapTile, Object>(aPendingQueueSize + 2, 0.1f, true) {
- private static final long serialVersionUID = 6455337315681858866L;
- @Override
- protected boolean removeEldestEntry(Entry<OpenStreetMapTile, Object> pEldest) {
- return size() > aPendingQueueSize;
- }
- };
- }
-
- public void loadMapTileAsync(final OpenStreetMapTile aTile) {
-
- final int activeCount = mThreadPool.activeCount();
-
- // sanity check
- if (activeCount == 0 && !mPending.isEmpty()) {
- Log.w(debugtag(), "Unexpected - no active threads but pending queue not empty");
- clearQueue();
- }
-
- // this will put the tile in the queue, or move it to the front of the
- // queue if it's already present
- mPending.put(aTile, PRESENT);
-
- if (DEBUGMODE)
- Log.d(debugtag(), activeCount + " active threads");
- if (activeCount < mThreadPoolSize) {
- final Thread t = new Thread(mThreadPool, getTileLoader());
- t.start();
- }
- }
-
- private void clearQueue() {
- mPending.clear();
- mWorking.clear();
- }
-
- /**
- * Stops all workers, the service is shutting down.
- */
- public void stopWorkers()
- {
- this.clearQueue();
- this.mThreadPool.interrupt();
- }
-
- /**
- * The debug tag.
- * Because the tag of the abstract class is not so interesting.
- * @return
- */
- protected abstract String debugtag();
-
- protected abstract Runnable getTileLoader();
-
- protected interface TileLoaderCallback {
- /**
- * A tile has loaded.
- * @param aTile the tile that has loaded
- * @param aTilePath the path of the file. May be null.
- * @param aRefresh whether to redraw the screen so that new tiles will be used
- */
- void tileLoaded(OpenStreetMapTile aTile, String aTilePath, boolean aRefresh);
- }
-
- protected abstract class TileLoader implements Runnable, TileLoaderCallback {
- /**
- * Load the requested tile.
- * @param aTile the tile to load
- * @throws CantContinueException if it is not possible to continue with processing the queue
- */
- protected abstract void loadTile(OpenStreetMapTile aTile) throws CantContinueException;
-
- private OpenStreetMapTile nextTile() {
-
- synchronized (mPending) {
- OpenStreetMapTile result = null;
-
- // get the most recently accessed tile
- // - the last item in the iterator that's not already being processed
- Iterator<OpenStreetMapTile> iterator = mPending.keySet().iterator();
-
- // TODO this iterates the whole list, make this faster...
- while (iterator.hasNext()) {
- try {
- final OpenStreetMapTile tile = iterator.next();
- if (!mWorking.containsKey(tile)) {
- result = tile;
- }
- } catch (final ConcurrentModificationException e) {
- if (DEBUGMODE)
- Log.w(debugtag(), "ConcurrentModificationException break: " + (result != null));
-
- // if we've got a result return it, otherwise try again
- if (result != null) {
- break;
- } else {
- iterator = mPending.keySet().iterator();
- }
- }
- }
-
- if (result != null)
- {
- mWorking.put(result, PRESENT);
- }
-
- return result;
- }
- }
-
- @Override
- public void tileLoaded(final OpenStreetMapTile aTile, final String aTilePath, final boolean aRefresh) {
-
- mPending.remove(aTile);
- mWorking.remove(aTile);
-
- if (aRefresh) {
- mCallback.mapTileRequestCompleted(aTile, aTilePath);
- }
- }
-
- @Override
- final public void run() {
-
- OpenStreetMapTile tile;
- while ((tile = nextTile()) != null) {
- if (DEBUGMODE)
- Log.d(debugtag(), "Next tile: " + tile);
- try {
- loadTile(tile);
- } catch (final CantContinueException e) {
- Log.i(debugtag(), "Tile loader can't continue");
- clearQueue();
- } catch (final Throwable e) {
- Log.e(debugtag(), "Error downloading tile: " + tile, e);
- }
- }
- if (DEBUGMODE)
- Log.d(debugtag(), "No more tiles");
- }
- }
-
- protected class CantContinueException extends Exception {
- private static final long serialVersionUID = 146526524087765133L;
- }
-}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTile.java b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTile.java
deleted file mode 100644
index 85f732a..0000000
--- a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTile.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package org.andnav.osm.tileprovider;
-
-public class OpenStreetMapTile {
-
- public static final int MAPTILE_SUCCESS_ID = 0;
- public static final int MAPTILE_FAIL_ID = MAPTILE_SUCCESS_ID + 1;
-
- private final int rendererId;
- private final int x;
- private final int y;
- private final int zoomLevel;
-
- public OpenStreetMapTile(int rendererId, int zoomLevel, int tileX, int tileY) {
- this.rendererId = rendererId;
- this.zoomLevel = zoomLevel;
- this.x = tileX;
- this.y = tileY;
- }
-
- public int getRendererId() {
- return rendererId;
- }
-
- public int getZoomLevel() {
- return zoomLevel;
- }
-
- public int getX() {
- return x;
- }
-
- public int getY() {
- return y;
- }
-
- @Override
- public String toString() {
- return rendererId + "/" + zoomLevel + "/" + x + "/" + y;
- }
-
- @Override
- public boolean equals(Object o) {
- if (o instanceof OpenStreetMapTile) {
- OpenStreetMapTile t = (OpenStreetMapTile) o;
- return zoomLevel == t.zoomLevel && x == t.x && y == t.y && rendererId == t.rendererId;
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- int code = 17;
- code *= 37 + rendererId;
- code *= 37 + zoomLevel;
- code *= 37 + x;
- code *= 37 + y;
- return code;
- }
-
-}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileDownloader.java b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileDownloader.java
deleted file mode 100644
index 8cbc1d1..0000000
--- a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileDownloader.java
+++ /dev/null
@@ -1,139 +0,0 @@
-// Created by plusminus on 21:31:36 - 25.09.2008
-package org.andnav.osm.tileprovider;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URL;
-import java.net.UnknownHostException;
-
-import org.andnav.osm.views.util.OpenStreetMapRendererInfo;
-
-import android.util.Log;
-
-/**
- * The OpenStreetMapTileDownloader loads tiles from a server and passes them to
- * a OpenStreetMapTileFilesystemProvider.
- * @author Nicolas Gramlich
- * @author Manuel Stahl
- *
- */
-public class OpenStreetMapTileDownloader extends OpenStreetMapAsyncTileProvider {
-
- // ===========================================================
- // Constants
- // ===========================================================
-
- private static final String DEBUGTAG = "OSM_DOWNLOADER";
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- private final OpenStreetMapTileFilesystemProvider mMapTileFSProvider;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public OpenStreetMapTileDownloader(final IOpenStreetMapTileProviderCallback pCallback, final OpenStreetMapTileFilesystemProvider aMapTileFSProvider){
- super(pCallback, NUMBER_OF_TILE_DOWNLOAD_THREADS, TILE_DOWNLOAD_MAXIMUM_QUEUE_SIZE);
- this.mMapTileFSProvider = aMapTileFSProvider;
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- protected String debugtag() {
- return DEBUGTAG;
- }
-
- @Override
- protected Runnable getTileLoader() {
- return new TileLoader();
- };
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- private String buildURL(final OpenStreetMapTile tile) {
- OpenStreetMapRendererInfo renderer = OpenStreetMapRendererInfo.values()[tile.getRendererId()];
- return renderer.getTileURLString(tile);
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-
- private class TileLoader extends OpenStreetMapAsyncTileProvider.TileLoader {
-
- @Override
- public void loadTile(final OpenStreetMapTile aTile) throws CantContinueException {
-
- InputStream in = null;
- OutputStream out = null;
-
- final File outputFile = mMapTileFSProvider.getOutputFile(aTile);
- final String tileURLString = buildURL(aTile);
-
- try {
- if(DEBUGMODE)
- Log.d(DEBUGTAG, "Downloading Maptile from url: " + tileURLString);
-
- in = new BufferedInputStream(new URL(tileURLString).openStream(), StreamUtils.IO_BUFFER_SIZE);
-
- final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
- out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
- StreamUtils.copy(in, out);
- out.flush();
-
- final byte[] data = dataStream.toByteArray();
-
- // sanity check - don't save an empty file
- if (data.length == 0) {
- Log.i(DEBUGTAG, "Empty maptile not saved: " + aTile);
- } else {
- mMapTileFSProvider.saveFile(aTile, outputFile, data);
- if(DEBUGMODE)
- Log.d(DEBUGTAG, "Maptile saved " + data.length + " bytes : " + aTile);
- }
- } catch (final UnknownHostException e) {
- // no network connection so empty the queue
- Log.w(DEBUGTAG, "UnknownHostException downloading MapTile: " + aTile + " : " + e);
- throw new CantContinueException();
- } catch(final FileNotFoundException e){
- Log.w(DEBUGTAG, "Url not found: " + aTile+ " : " + e);
- } catch (final IOException e) {
- Log.w(DEBUGTAG, "IOException downloading MapTile: " + aTile + " : " + e);
- } catch(final Throwable e) {
- Log.e(DEBUGTAG, "Error downloading MapTile: " + aTile, e);
- } finally {
- StreamUtils.closeStream(in);
- StreamUtils.closeStream(out);
- }
-
- /* Don't immediately send the tile back.
- * If we're moving, and the internet is a bit patchy, then by the time
- * the download has finished we don't need this tile any more.
- * If we still do need it then the file system provider will get it
- * again next time it's needed.
- * That should be immediately because the view is redrawn when it
- * receives this completion event.
- */
- tileLoaded(aTile, null, true);
- }
- };
-
-}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileFilesystemProvider.java b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileFilesystemProvider.java
deleted file mode 100644
index 88343da..0000000
--- a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileFilesystemProvider.java
+++ /dev/null
@@ -1,135 +0,0 @@
-// Created by plusminus on 21:46:41 - 25.09.2008
-package org.andnav.osm.tileprovider;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-import org.andnav.osm.views.util.OpenStreetMapRendererInfo;
-
-import android.util.Log;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class OpenStreetMapTileFilesystemProvider extends OpenStreetMapAsyncTileProvider {
- // ===========================================================
- // Constants
- // ===========================================================
-
- final static String DEBUGTAG = "OSM_FS_PROVIDER";
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- /** online provider */
- protected OpenStreetMapTileDownloader mTileDownloader;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- /**
- * @param ctx
- * @param aCache to load fs-tiles to.
- */
- public OpenStreetMapTileFilesystemProvider(final IOpenStreetMapTileProviderCallback pCallback) {
- super(pCallback, NUMBER_OF_TILE_FILESYSTEM_THREADS, TILE_FILESYSTEM_MAXIMUM_QUEUE_SIZE);
- this.mTileDownloader = new OpenStreetMapTileDownloader(pCallback, this);
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- protected String debugtag() {
- return DEBUGTAG;
- }
-
- @Override
- protected Runnable getTileLoader() {
- return new TileLoader();
- };
-
-
- /**
- * Stops all workers, the service is shutting down.
- */
- @Override
- public void stopWorkers()
- {
- super.stopWorkers();
- this.mTileDownloader.stopWorkers();
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- private String buildPath(final OpenStreetMapTile tile) {
- final OpenStreetMapRendererInfo renderer = OpenStreetMapRendererInfo.values()[tile.getRendererId()];
- return TILE_PATH_BASE + renderer.name() + "/" + tile.getZoomLevel() + "/"
- + tile.getX() + "/" + tile.getY() + renderer.IMAGE_FILENAMEENDING + TILE_PATH_EXTENSION;
- }
-
- /**
- * Get the file location for the tile.
- * @param tile
- * @return
- * @throws CantContinueException if the directory containing the file doesn't exist
- * and can't be created
- */
- File getOutputFile(final OpenStreetMapTile tile) throws CantContinueException {
- final File file = new File(buildPath(tile));
- final File parent = file.getParentFile();
- if (!parent.exists() && !parent.mkdirs()) {
- throw new CantContinueException();
- }
- return file;
- }
-
- void saveFile(final OpenStreetMapTile tile, final File outputFile, final byte[] someData) throws IOException{
- final OutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile, false), StreamUtils.IO_BUFFER_SIZE);
- bos.write(someData);
- bos.flush();
- bos.close();
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-
- private class TileLoader extends OpenStreetMapAsyncTileProvider.TileLoader {
-
- @Override
- public void loadTile(final OpenStreetMapTile aTile) throws CantContinueException {
- final File tileFile = getOutputFile(aTile);
- try {
- if (tileFile.exists()) {
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "Loaded tile: " + aTile);
- tileLoaded(aTile, tileFile.getPath(), true);
- } else {
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "Tile not exist, request for download: " + aTile);
- mTileDownloader.loadMapTileAsync(aTile);
- // don't refresh the screen because there's nothing new
- tileLoaded(aTile, null, false);
- }
- } catch (final Throwable e) {
- Log.e(DEBUGTAG, "Error loading tile", e);
- tileLoaded(aTile, null, false);
- }
- }
- }
-}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/StreamUtils.java b/cardroid/src/org/andnav/osm/tileprovider/StreamUtils.java
deleted file mode 100644
index d2c38f4..0000000
--- a/cardroid/src/org/andnav/osm/tileprovider/StreamUtils.java
+++ /dev/null
@@ -1,72 +0,0 @@
-// Created by plusminus on 19:14:08 - 20.10.2008
-package org.andnav.osm.tileprovider;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-
-public class StreamUtils {
- // ===========================================================
- // Constants
- // ===========================================================
-
- public static final int IO_BUFFER_SIZE = 8 * 1024;
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- /**
- * Copy the content of the input stream into the output stream, using a temporary
- * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
- *
- * @param in The input stream to copy from.
- * @param out The output stream to copy to.
- *
- * @throws IOException If any error occurs during the copy.
- */
- public static void copy(InputStream in, OutputStream out) throws IOException {
- byte[] b = new byte[IO_BUFFER_SIZE];
- int read;
- while ((read = in.read(b)) != -1) {
- out.write(b, 0, read);
- }
- }
-
- /**
- * Closes the specified stream.
- *
- * @param stream The stream to close.
- */
- public static void closeStream(Closeable stream) {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- android.util.Log.e("IO", "Could not close stream", e);
- }
- }
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/constants/OpenStreetMapTileProviderConstants.java b/cardroid/src/org/andnav/osm/tileprovider/constants/OpenStreetMapTileProviderConstants.java
deleted file mode 100644
index a5eda6f..0000000
--- a/cardroid/src/org/andnav/osm/tileprovider/constants/OpenStreetMapTileProviderConstants.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.andnav.osm.tileprovider.constants;
-
-import android.os.Environment;
-
-/**
- *
- * This class contains constants used by the service.
- *
- * @author Neil Boyd
- *
- */
-public interface OpenStreetMapTileProviderConstants {
- // ===========================================================
- // Final Fields
- // ===========================================================
-
- public static final boolean DEBUGMODE = false;
-
- public static final String TILE_PATH_BASE = Environment.getExternalStorageDirectory() + "/andnav2/tiles/";
- public static final String TILE_PATH_EXTENSION = ".andnav";
-
- public static final int NUMBER_OF_TILE_DOWNLOAD_THREADS = 8;
- public static final int NUMBER_OF_TILE_FILESYSTEM_THREADS = 8;
-
- public static final int TILE_DOWNLOAD_MAXIMUM_QUEUE_SIZE = 40;
- public static final int TILE_FILESYSTEM_MAXIMUM_QUEUE_SIZE = 40;
-
- // ===========================================================
- // Methods
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/util/BoundingBoxE6.java b/cardroid/src/org/andnav/osm/util/BoundingBoxE6.java
deleted file mode 100644
index af18cb1..0000000
--- a/cardroid/src/org/andnav/osm/util/BoundingBoxE6.java
+++ /dev/null
@@ -1,190 +0,0 @@
-// Created by plusminus on 19:06:38 - 25.09.2008
-package org.andnav.osm.util;
-
-import static org.andnav.osm.util.MyMath.gudermann;
-import static org.andnav.osm.util.MyMath.gudermannInverse;
-
-import java.util.ArrayList;
-
-import org.andnav.osm.util.constants.OpenStreetMapConstants;
-import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class BoundingBoxE6 implements OpenStreetMapViewConstants, OpenStreetMapConstants {
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final int mLatNorthE6;
- protected final int mLatSouthE6;
- protected final int mLonEastE6;
- protected final int mLonWestE6;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public BoundingBoxE6(final int northE6, final int eastE6, final int southE6, final int westE6){
- this.mLatNorthE6 = northE6;
- this.mLonEastE6 = eastE6;
- this.mLatSouthE6 = southE6;
- this.mLonWestE6 = westE6;
- }
-
- public BoundingBoxE6(final double north, final double east, final double south, final double west){
- this.mLatNorthE6 = (int)(north * 1E6);
- this.mLonEastE6 = (int)(east * 1E6);
- this.mLatSouthE6 = (int)(south * 1E6);
- this.mLonWestE6 = (int)(west * 1E6);
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public int getDiagonalLengthInMeters() {
- return new GeoPoint(this.mLatNorthE6, this.mLonWestE6).distanceTo(new GeoPoint(this.mLatSouthE6, this.mLonEastE6));
- }
-
- public int getLatNorthE6() {
- return this.mLatNorthE6;
- }
-
- public int getLatSouthE6() {
- return this.mLatSouthE6;
- }
-
- public int getLonEastE6() {
- return this.mLonEastE6;
- }
-
- public int getLonWestE6() {
- return this.mLonWestE6;
- }
-
- public int getLatitudeSpanE6() {
- return Math.abs(this.mLatNorthE6 - this.mLatSouthE6);
- }
-
- public int getLongitudeSpanE6() {
- return Math.abs(this.mLonEastE6 - this.mLonWestE6);
- }
- /**
- *
- * @param aLatitude
- * @param aLongitude
- * @param reuse
- * @return relative position determined from the upper left corner.<br />
- * {0,0} would be the upper left corner.
- * {1,1} would be the lower right corner.
- * {1,0} would be the lower left corner.
- * {0,1} would be the upper right corner.
- */
- public float[] getRelativePositionOfGeoPointInBoundingBoxWithLinearInterpolation(final int aLatitude, final int aLongitude, final float[] reuse){
- float[] out = (reuse != null) ? reuse : new float[2];
- out[MAPTILE_LATITUDE_INDEX] = ((float)(this.mLatNorthE6 - aLatitude) / getLatitudeSpanE6());
- out[MAPTILE_LONGITUDE_INDEX] = 1 - ((float)(this.mLonEastE6 - aLongitude) / getLongitudeSpanE6());
- return out;
- }
-
- public float[] getRelativePositionOfGeoPointInBoundingBoxWithExactGudermannInterpolation(final int aLatitudeE6, final int aLongitudeE6, final float[] reuse){
- float[] out = (reuse != null) ? reuse : new float[2];
- out[MAPTILE_LATITUDE_INDEX] = (float)((gudermannInverse(this.mLatNorthE6 / 1E6) - gudermannInverse(aLatitudeE6 / 1E6)) / (gudermannInverse(this.mLatNorthE6 / 1E6) - gudermannInverse(this.mLatSouthE6 / 1E6)));
- out[MAPTILE_LONGITUDE_INDEX] = 1 - ((float)(this.mLonEastE6 - aLongitudeE6) / getLongitudeSpanE6());
- return out;
- }
-
- public GeoPoint getGeoPointOfRelativePositionWithLinearInterpolation(final float relX, final float relY) {
-
- int lat = (int)(this.mLatNorthE6 - (this.getLatitudeSpanE6() * relY));
-
- int lon = (int)(this.mLonWestE6 + (this.getLongitudeSpanE6() * relX));
-
- /* Bring into bounds. */
- while(lat > 90500000)
- lat -= 90500000;
- while(lat < -90500000)
- lat += 90500000;
-
- /* Bring into bounds. */
- while(lon > 180000000)
- lon -= 180000000;
- while(lon < -180000000)
- lon += 180000000;
-
- return new GeoPoint(lat, lon);
- }
-
- public GeoPoint getGeoPointOfRelativePositionWithExactGudermannInterpolation(final float relX, final float relY) {
-
- final double gudNorth = gudermannInverse(this.mLatNorthE6 / 1E6);
- final double gudSouth = gudermannInverse(this.mLatSouthE6 / 1E6);
- final double latD = gudermann((gudSouth + (1-relY) * (gudNorth - gudSouth)));
- int lat = (int)(latD * 1E6);
-
- int lon = (int)((this.mLonWestE6 + (this.getLongitudeSpanE6() * relX)));
-
- /* Bring into bounds. */
- while(lat > 90500000)
- lat -= 90500000;
- while(lat < -90500000)
- lat += 90500000;
-
- /* Bring into bounds. */
- while(lon > 180000000)
- lon -= 180000000;
- while(lon < -180000000)
- lon += 180000000;
-
- return new GeoPoint(lat, lon);
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- public String toString(){
- return new StringBuffer()
- .append("N:").append(this.mLatNorthE6)
- .append("; E:").append(this.mLonEastE6)
- .append("; S:").append(this.mLatSouthE6)
- .append("; W:").append(this.mLonWestE6)
- .toString();
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- public static BoundingBoxE6 fromGeoPoints(final ArrayList<? extends GeoPoint> partialPolyLine) {
- int minLat = Integer.MAX_VALUE;
- int minLon = Integer.MAX_VALUE;
- int maxLat = Integer.MIN_VALUE;
- int maxLon = Integer.MIN_VALUE;
- for (GeoPoint gp : partialPolyLine) {
- final int latitudeE6 = gp.getLatitudeE6();
- final int longitudeE6 = gp.getLongitudeE6();
-
- minLat = Math.min(minLat, latitudeE6);
- minLon = Math.min(minLon, longitudeE6);
- maxLat = Math.max(maxLat, latitudeE6);
- maxLon = Math.max(maxLon, longitudeE6);
- }
-
- return new BoundingBoxE6(minLat, minLon, maxLat, maxLon);
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
-
diff --git a/cardroid/src/org/andnav/osm/util/GeoPoint.java b/cardroid/src/org/andnav/osm/util/GeoPoint.java
deleted file mode 100644
index 383fb21..0000000
--- a/cardroid/src/org/andnav/osm/util/GeoPoint.java
+++ /dev/null
@@ -1,138 +0,0 @@
-// Created by plusminus on 21:28:12 - 25.09.2008
-package org.andnav.osm.util;
-
-import org.andnav.osm.util.constants.GeoConstants;
-import org.andnav.osm.views.util.constants.MathConstants;
-
-import android.location.Location;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class GeoPoint implements MathConstants, GeoConstants{
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- private int mLongitudeE6;
- private int mLatitudeE6;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public GeoPoint(final int aLatitudeE6, final int aLongitudeE6) {
- this.mLatitudeE6 = aLatitudeE6;
- this.mLongitudeE6 = aLongitudeE6;
- }
-
- public GeoPoint(final double aLatitude, final double aLongitude) {
- this.mLatitudeE6 = (int)(aLatitude * 1E6);
- this.mLongitudeE6 = (int)(aLongitude * 1E6);
- }
-
- public GeoPoint(Location aLocation) {
- this(aLocation.getLatitude(), aLocation.getLongitude());
- }
-
-
- protected static GeoPoint fromDoubleString(final String s, final char spacer) {
- final int spacerPos = s.indexOf(spacer);
- return new GeoPoint((int) (Double.parseDouble(s.substring(0,
- spacerPos - 1)) * 1E6), (int) (Double.parseDouble(s.substring(
- spacerPos + 1, s.length())) * 1E6));
- }
-
- public static GeoPoint fromIntString(final String s){
- final int commaPos = s.indexOf(',');
- return new GeoPoint(Integer.parseInt(s.substring(0,commaPos-1)),
- Integer.parseInt(s.substring(commaPos+1,s.length())));
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public int getLongitudeE6() {
- return this.mLongitudeE6;
- }
-
- public int getLatitudeE6() {
- return this.mLatitudeE6;
- }
-
- public void setLongitudeE6(final int aLongitudeE6) {
- this.mLongitudeE6 = aLongitudeE6;
- }
-
- public void setLatitudeE6(final int aLatitudeE6) {
- this.mLatitudeE6 = aLatitudeE6;
- }
-
- public void setCoordsE6(final int aLatitudeE6, final int aLongitudeE6) {
- this.mLatitudeE6 = aLatitudeE6;
- this.mLongitudeE6 = aLongitudeE6;
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- public String toString(){
- return new StringBuilder().append(this.mLatitudeE6).append(",").append(this.mLongitudeE6).toString();
- }
-
- public String toDoubleString() {
- return new StringBuilder().append(this.mLatitudeE6 / 1E6).append(",").append(this.mLongitudeE6 / 1E6).toString();
- }
-
- @Override
- public boolean equals(Object obj) {
- if(!(obj instanceof GeoPoint))
- return false;
- GeoPoint g = (GeoPoint)obj;
- return g.mLatitudeE6 == this.mLatitudeE6 && g.mLongitudeE6 == this.mLongitudeE6;
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- /**
- * @see Source@ http://www.geocities.com/DrChengalva/GPSDistance.html
- * @param gpA
- * @param gpB
- * @return distance in meters
- */
- public int distanceTo(final GeoPoint other) {
-
- final double a1 = DEG2RAD * (this.mLatitudeE6 / 1E6);
- final double a2 = DEG2RAD * (this.mLongitudeE6 / 1E6);
- final double b1 = DEG2RAD * (other.mLatitudeE6 / 1E6);
- final double b2 = DEG2RAD * (other.mLongitudeE6 / 1E6);
-
- final double cosa1 = Math.cos(a1);
- final double cosb1 = Math.cos(b1);
-
- final double t1 = cosa1*Math.cos(a2)*cosb1*Math.cos(b2);
-
- final double t2 = cosa1*Math.sin(a2)*cosb1*Math.sin(b2);
-
- final double t3 = Math.sin(a1)*Math.sin(b1);
-
- final double tt = Math.acos( t1 + t2 + t3 );
-
- return (int)(RADIUS_EARTH_METERS*tt);
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/util/MyMath.java b/cardroid/src/org/andnav/osm/util/MyMath.java
deleted file mode 100644
index d54f937..0000000
--- a/cardroid/src/org/andnav/osm/util/MyMath.java
+++ /dev/null
@@ -1,59 +0,0 @@
-// Created by plusminus on 20:36:01 - 26.09.2008
-package org.andnav.osm.util;
-
-import org.andnav.osm.views.util.constants.MathConstants;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class MyMath implements MathConstants {
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
-
- public static double gudermannInverse(double aLatitude){
- return Math.log(Math.tan(PI_4 + (DEG2RAD * aLatitude / 2)));
- }
-
- public static double gudermann(double y){
- return RAD2DEG * Math.atan(Math.sinh(y));
- }
-
-
- public static int mod(int number, final int modulus){
- if(number > 0)
- return number % modulus;
-
- while(number < 0)
- number += modulus;
-
- return number;
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/util/NetworkLocationIgnorer.java b/cardroid/src/org/andnav/osm/util/NetworkLocationIgnorer.java
deleted file mode 100644
index 393b90b..0000000
--- a/cardroid/src/org/andnav/osm/util/NetworkLocationIgnorer.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package org.andnav.osm.util;
-
-import android.location.LocationManager;
-
-/**
- *
- * A class to check whether we want to use a location.
- * If there are multiple location providers, i.e. network and GPS,
- * then you want to ignore network locations shortly after a GPS location
- * because you will get another GPS location soon.
- *
- * @author Neil Boyd
- *
- */
-public class NetworkLocationIgnorer {
-
- /**
- * The time we wait after the last gps location before displaying
- * a non-gps location.
- */
- private static final long GPS_WAIT_TIME = 20000; // 20 seconds
-
- /** last time we got a location from the gps provider */
- private long mLastGps = 0;
-
- /**
- * Whether we should ignore this location.
- * @param pProvider the provider that provided the location
- * @param pTime the time of the location
- * @return true if we should ignore this location, false if not
- */
- public boolean shouldIgnore(final String pProvider, final long pTime) {
-
- if (LocationManager.GPS_PROVIDER.equals(pProvider)) {
- mLastGps = pTime;
- } else {
- if (pTime < mLastGps + GPS_WAIT_TIME) {
- return true;
- }
- }
-
- return false;
- }
-}
diff --git a/cardroid/src/org/andnav/osm/util/constants/GeoConstants.java b/cardroid/src/org/andnav/osm/util/constants/GeoConstants.java
deleted file mode 100644
index aa701d6..0000000
--- a/cardroid/src/org/andnav/osm/util/constants/GeoConstants.java
+++ /dev/null
@@ -1,15 +0,0 @@
-// Created by plusminus on 17:41:55 - 16.10.2008
-package org.andnav.osm.util.constants;
-
-
-public interface GeoConstants {
- // ===========================================================
- // Final Fields
- // ===========================================================
-
- public static final int RADIUS_EARTH_METERS = 6378140;
-
- // ===========================================================
- // Methods
- // ===========================================================
-}
\ No newline at end of file
diff --git a/cardroid/src/org/andnav/osm/util/constants/OpenStreetMapConstants.java b/cardroid/src/org/andnav/osm/util/constants/OpenStreetMapConstants.java
deleted file mode 100644
index 0b864b4..0000000
--- a/cardroid/src/org/andnav/osm/util/constants/OpenStreetMapConstants.java
+++ /dev/null
@@ -1,32 +0,0 @@
-// Created by plusminus on 23:11:31 - 22.09.2008
-package org.andnav.osm.util.constants;
-
-/**
- *
- * This class contains constants used by the sample applications.
- *
- * @author Nicolas Gramlich
- *
- */
-public interface OpenStreetMapConstants {
- // ===========================================================
- // Final Fields
- // ===========================================================
-
- public static final String DEBUGTAG = "OPENSTREETMAP";
-
- public static final int NOT_SET = Integer.MIN_VALUE;
-
- public static final String PREFS_NAME = "org.andnav.osm.prefs";
- public static final String PREFS_RENDERER = "renderer";
- public static final String PREFS_SCROLL_X = "scrollX";
- public static final String PREFS_SCROLL_Y = "scrollY";
- public static final String PREFS_ZOOM_LEVEL = "zoomLevel";
- public static final String PREFS_SHOW_LOCATION = "showLocation";
- public static final String PREFS_FOLLOW_LOCATION = "followLocation";
-
-
- // ===========================================================
- // Methods
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/OpenStreetMapView.java b/cardroid/src/org/andnav/osm/views/OpenStreetMapView.java
deleted file mode 100644
index 52e64ff..0000000
--- a/cardroid/src/org/andnav/osm/views/OpenStreetMapView.java
+++ /dev/null
@@ -1,1145 +0,0 @@
-// Created by plusminus on 17:45:56 - 25.09.2008
-package org.andnav.osm.views;
-
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.andnav.osm.util.BoundingBoxE6;
-import org.andnav.osm.util.GeoPoint;
-import org.andnav.osm.views.overlay.OpenStreetMapTilesOverlay;
-import org.andnav.osm.views.overlay.OpenStreetMapViewOverlay;
-import org.andnav.osm.views.overlay.OpenStreetMapViewOverlay.Snappable;
-import org.andnav.osm.views.util.Mercator;
-import org.andnav.osm.views.util.OpenStreetMapRendererInfo;
-import org.andnav.osm.views.util.OpenStreetMapTileProvider;
-import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
-
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import android.graphics.Path;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.graphics.Bitmap.Config;
-import android.graphics.Paint.Style;
-import android.util.AttributeSet;
-import android.util.FloatMath;
-import android.util.Log;
-import android.view.GestureDetector;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.GestureDetector.OnGestureListener;
-import android.view.animation.AnimationUtils;
-import android.view.animation.Interpolator;
-import android.view.animation.LinearInterpolator;
-import android.widget.Scroller;
-import android.widget.ZoomButtonsController;
-import android.widget.ZoomButtonsController.OnZoomListener;
-
-public class OpenStreetMapView extends View implements OpenStreetMapViewConstants {
-
- // ===========================================================
- // Constants
- // ===========================================================
-
- final static OpenStreetMapRendererInfo DEFAULTRENDERER = OpenStreetMapRendererInfo.MAPNIK;
- final static String BUNDLE_RENDERER = "org.andnav.osm.views.OpenStreetMapView.RENDERER";
- final static String BUNDLE_SCROLL_X = "org.andnav.osm.views.OpenStreetMapView.SCROLL_X";
- final static String BUNDLE_SCROLL_Y = "org.andnav.osm.views.OpenStreetMapView.SCROLL_Y";
- final static String BUNDLE_ZOOM_LEVEL = "org.andnav.osm.views.OpenStreetMapView.ZOOM";
-
- private static final int MULTI_NONE = 0;
- private static final int MULTI_ACTIVE = 1;
- private static final int MULTI_HANDLED = 2;
-
- private float mPointerDownDistance; /* distance for a ACTION_POINTER_DOWN MotionEvent */
- private int mMultiMode = MULTI_NONE; /* if we are in after an ACTION_POINTER_DOWN */
-
- // get API level 5 MotionEvent constants by reflection
- // TODO can remove this stuff if we upgrade to API level 5
- private static int ACTION_MASK = 255;
- private static int ACTION_POINTER_DOWN = 5;
- private static int ACTION_POINTER_UP = 6;
- private static Method MotionEvent_getX;
- private static Method MotionEvent_getY;
- static {
- final MotionEvent me = MotionEvent.obtain(0, 0, 0, 0f, 0f, 0);
- try {
- ACTION_MASK = MotionEvent.class.getField("ACTION_MASK").getInt(me);
- } catch (final Exception e) {}
- try {
- ACTION_POINTER_DOWN = MotionEvent.class.getField("ACTION_POINTER_DOWN").getInt(me);
- } catch (final Exception e) {}
- try {
- ACTION_POINTER_UP = MotionEvent.class.getField("ACTION_POINTER_UP").getInt(me);
- } catch (final Exception e) {}
- try {
- MotionEvent_getX = MotionEvent.class.getMethod("getX", new Class[] { int.class });
- } catch (final Exception e) {}
- try {
- MotionEvent_getY = MotionEvent.class.getMethod("getY", new Class[] { int.class });
- } catch (final Exception e) {}
- }
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected int mZoomLevel = 0; /** Current zoom level for map tiles */
- protected final List<OpenStreetMapViewOverlay> mOverlays = new ArrayList<OpenStreetMapViewOverlay>();
-
- protected Bitmap mBackBuffer;
- protected Canvas mBackCanvas;
- protected Matrix mTrans = new Matrix();
- protected final Paint mPaint = new Paint();
- private OpenStreetMapViewProjection mProjection;
-
- private OpenStreetMapView mMiniMap, mMaxiMap;
- private final OpenStreetMapTilesOverlay mMapOverlay;
-
- private final GestureDetector mGestureDetector = new GestureDetector(new OpenStreetMapViewGestureDetectorListener());
- final Scroller mScroller; /** Handles map scrolling */
- final Scaler mScaler;
- private OpenStreetMapViewController mController;
- private int mMiniMapOverriddenVisibility = NOT_SET;
- private int mMiniMapZoomDiff = NOT_SET;
-
- private ZoomButtonsController mZoomController;
- private boolean mEnableZoomController = false;
-
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- private OpenStreetMapView(final Context context, AttributeSet attrs,
- final OpenStreetMapRendererInfo aRendererInfo,
- final OpenStreetMapTileProvider aTileProvider) {
- super(context, attrs);
- this.mController = new OpenStreetMapViewController(this);
- this.mScroller = new Scroller(context);
- this.mScaler = new Scaler(context, new LinearInterpolator());
- this.mMapOverlay = new OpenStreetMapTilesOverlay(this, aRendererInfo, aTileProvider);
- mOverlays.add(this.mMapOverlay);
- this.mZoomController = new ZoomButtonsController(this);
- this.mZoomController.setOnZoomListener(new OpenStreetMapViewZoomListener());
- }
-
- /**
- * XML Constructor (uses default Renderer)
- */
- public OpenStreetMapView(Context context, AttributeSet attrs) {
- this(context, attrs, DEFAULTRENDERER, null);
- }
-
- /**
- * Standard Constructor for {@link OpenStreetMapView}.
- *
- * @param context
- * @param aRendererInfo
- * pass a {@link OpenStreetMapRendererInfo} you like.
- */
- public OpenStreetMapView(final Context context, final OpenStreetMapRendererInfo aRendererInfo) {
- this(context, null, aRendererInfo, null);
- }
-
- /**
- *
- * @param context
- * @param aRendererInfo
- * pass a {@link OpenStreetMapRendererInfo} you like.
- * @param osmv
- * another {@link OpenStreetMapView}, to share the TileProvider
- * with.<br/>
- * May significantly improve the render speed, when using the
- * same {@link OpenStreetMapRendererInfo}.
- */
- public OpenStreetMapView(final Context context,
- final OpenStreetMapRendererInfo aRendererInfo,
- final OpenStreetMapView aMapToShareTheTileProviderWith) {
- this(context, null, aRendererInfo, /* TODO aMapToShareTheTileProviderWith.mTileProvider */ null);
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- /**
- * This MapView takes control of the {@link OpenStreetMapView} passed as
- * parameter.<br />
- * I.e. it zoomes it to x levels less than itself and centers it the same
- * coords.<br />
- * Its pretty usefull when the MiniMap uses the same TileProvider.
- *
- * @see OpenStreetMapView.OpenStreetMapView(
- * @param aOsmvMinimap
- * @param aZoomDiff
- * 3 is a good Value. Pass {@link OpenStreetMapViewConstants}
- * .NOT_SET to disable autozooming of the minimap.
- */
- public void setMiniMap(final OpenStreetMapView aOsmvMinimap, final int aZoomDiff) {
- this.mMiniMapZoomDiff = aZoomDiff;
- this.mMiniMap = aOsmvMinimap;
- aOsmvMinimap.setMaxiMap(this);
-
- // TODO Synchronize the Views.
-// this.setMapCenter(this.mLatitudeE6, this.mLongitudeE6);
-// this.setZoomLevel(this.getZoomLevel());
- }
-
- public boolean hasMiniMap() {
- return this.mMiniMap != null;
- }
-
- /**
- * @return {@link View}.GONE or {@link View}.VISIBLE or {@link View}
- * .INVISIBLE or {@link OpenStreetMapViewConstants}.NOT_SET
- * */
- public int getOverrideMiniMapVisiblity() {
- return this.mMiniMapOverriddenVisibility;
- }
-
- /**
- * Use this method if you want to make the MiniMap visible i.e.: always or
- * never. Use {@link View}.GONE , {@link View}.VISIBLE, {@link View}
- * .INVISIBLE. Use {@link OpenStreetMapViewConstants}.NOT_SET to reset this
- * feature.
- *
- * @param aVisiblity
- */
- public void setOverrideMiniMapVisiblity(final int aVisiblity) {
- switch (aVisiblity) {
- case View.GONE:
- case View.VISIBLE:
- case View.INVISIBLE:
- if (this.mMiniMap != null)
- this.mMiniMap.setVisibility(aVisiblity);
- case NOT_SET:
- this.setZoomLevel(this.mZoomLevel);
- break;
- default:
- throw new IllegalArgumentException("See javadoc of this method !!!");
- }
- this.mMiniMapOverriddenVisibility = aVisiblity;
- }
-
- protected void setMaxiMap(final OpenStreetMapView aOsmvMaxiMap) {
- this.mMaxiMap = aOsmvMaxiMap;
- }
-
- public OpenStreetMapViewController getController() {
- return this.mController;
- }
-
- /**
- * You can add/remove/reorder your Overlays using the List of
- * {@link OpenStreetMapViewOverlay}. The first (index 0) Overlay gets drawn
- * first, the one with the highest as the last one.
- */
- public List<OpenStreetMapViewOverlay> getOverlays() {
- return this.mOverlays;
- }
-
- public double getLatitudeSpan() {
- return this.getDrawnBoundingBoxE6().getLongitudeSpanE6() / 1E6;
- }
-
- public int getLatitudeSpanE6() {
- return this.getDrawnBoundingBoxE6().getLatitudeSpanE6();
- }
-
- public double getLongitudeSpan() {
- return this.getDrawnBoundingBoxE6().getLongitudeSpanE6() / 1E6;
- }
-
- public int getLongitudeSpanE6() {
- return this.getDrawnBoundingBoxE6().getLatitudeSpanE6();
- }
-
- public BoundingBoxE6 getDrawnBoundingBoxE6() {
- return getBoundingBox(this.getWidth(), this.getHeight());
- }
-
- public BoundingBoxE6 getVisibleBoundingBoxE6() {
-// final ViewParent parent = this.getParent();
-// if(parent instanceof RotateView){
-// final RotateView par = (RotateView)parent;
-// return getBoundingBox(par.getMeasuredWidth(), par.getMeasuredHeight());
-// }else{
- return getBoundingBox(this.getWidth(), this.getHeight());
-// }
- }
-
- private BoundingBoxE6 getBoundingBox(final int pViewWidth, final int pViewHeight){
- final int mapTileZoom = mMapOverlay.getRendererInfo().MAPTILE_ZOOM;
- final int world_2 = (1 << mZoomLevel + mapTileZoom - 1);
- final int north = world_2 + getScrollY() - getHeight()/2;
- final int south = world_2 + getScrollY() + getHeight()/2;
- final int west = world_2 + getScrollX() - getWidth()/2;
- final int east = world_2 + getScrollX() + getWidth()/2;
-
- return Mercator.getBoundingBoxFromCoords(west, north, east, south, mZoomLevel + mapTileZoom);
- }
-
- /**
- * This class is only meant to be used during on call of onDraw(). Otherwise
- * it may produce strange results.
- *
- * @return
- */
- public OpenStreetMapViewProjection getProjection() {
- return mProjection;
- }
-
- public void setMapCenter(final GeoPoint aCenter) {
- this.setMapCenter(aCenter.getLatitudeE6(), aCenter.getLongitudeE6());
- }
-//
-// public void setMapCenter(final double aLatitude, final double aLongitude) {
-// this.setMapCenter((int) (aLatitude * 1E6), (int) (aLongitude * 1E6));
-// }
-//
- public void setMapCenter(final int aLatitudeE6, final int aLongitudeE6) {
- this.setMapCenter(aLatitudeE6, aLongitudeE6, true);
- }
-
- protected void setMapCenter(final int aLatitudeE6, final int aLongitudeE6,
- final boolean doPassFurther) {
- if (doPassFurther && this.mMiniMap != null)
- this.mMiniMap.setMapCenter(aLatitudeE6, aLongitudeE6, false);
- else if (this.mMaxiMap != null)
- this.mMaxiMap.setMapCenter(aLatitudeE6, aLongitudeE6, false);
-
- final int[] coords = Mercator.projectGeoPoint(aLatitudeE6, aLongitudeE6, getPixelZoomLevel(), null);
- final int worldSize_2 = getWorldSizePx()/2;
- if (getAnimation() == null || getAnimation().hasEnded()) {
- mScroller.startScroll(getScrollX(), getScrollY(),
- coords[MAPTILE_LONGITUDE_INDEX] - worldSize_2 - getScrollX(),
- coords[MAPTILE_LATITUDE_INDEX] - worldSize_2 - getScrollY(), 500);
- postInvalidate();
- }
- }
-
- public OpenStreetMapRendererInfo getRenderer() {
- return this.mMapOverlay.getRendererInfo();
- }
-
- public void setRenderer(final OpenStreetMapRendererInfo aRenderer) {
- this.mMapOverlay.setRendererInfo(aRenderer);
- this.checkZoomButtons();
- postInvalidate();
- }
-
- /**
- * @param aZoomLevel
- * between 0 (equator) and 18/19(closest), depending on the
- * Renderer chosen.
- */
- protected int setZoomLevel(final int aZoomLevel) {
- final int minZoomLevel = this.mMapOverlay.getRendererInfo().ZOOM_MINLEVEL;
- final int maxZoomLevel = this.mMapOverlay.getRendererInfo().ZOOM_MAXLEVEL;
- final int newZoomLevel = Math.max(minZoomLevel, Math.min(maxZoomLevel, aZoomLevel));
- final int curZoomLevel = this.mZoomLevel;
-
- if (this.mMiniMap != null) {
- if (this.mZoomLevel < this.mMiniMapZoomDiff) {
- if (this.mMiniMapOverriddenVisibility == NOT_SET)
- this.mMiniMap.setVisibility(View.INVISIBLE);
- } else {
- if (this.mMiniMapOverriddenVisibility == NOT_SET
- && this.mMiniMap.getVisibility() != View.VISIBLE) {
- this.mMiniMap.setVisibility(View.VISIBLE);
- }
- if (this.mMiniMapZoomDiff != NOT_SET)
- this.mMiniMap.setZoomLevel(this.mZoomLevel - this.mMiniMapZoomDiff);
- }
- }
-
- this.mZoomLevel = newZoomLevel;
- this.checkZoomButtons();
-
- if(newZoomLevel > curZoomLevel)
- scrollTo(getScrollX()<<(newZoomLevel-curZoomLevel), getScrollY()<<(newZoomLevel-curZoomLevel));
- else if(newZoomLevel < curZoomLevel)
- scrollTo(getScrollX()>>(curZoomLevel-newZoomLevel), getScrollY()>>(curZoomLevel-newZoomLevel));
-
- // TODO snap for all snappables
- Point snapPoint = new Point();
- mProjection = new OpenStreetMapViewProjection();
- for (OpenStreetMapViewOverlay osmvo : this.mOverlays) {
- if (osmvo instanceof Snappable &&
- ((Snappable)osmvo).onSnapToItem(getScrollX(), getScrollY(), snapPoint, this)) {
- scrollTo(snapPoint.x, snapPoint.y);
- }
- }
- return this.mZoomLevel;
- }
-
- /**
- * Get the current ZoomLevel for the map tiles.
- * @return the current ZoomLevel between 0 (equator) and 18/19(closest),
- * depending on the Renderer chosen.
- */
- public int getZoomLevel() {
- return this.mZoomLevel;
- }
-
- /*
- * Returns the maximum zoom level for the point currently at the center.
- * @return The maximum zoom level for the map's current center.
- */
- public int getMaxZoomLevel() {
- return getRenderer().ZOOM_MAXLEVEL;
- }
-
- public GeoPoint getMapCenter() {
- return new GeoPoint(getMapCenterLatitudeE6(), getMapCenterLongitudeE6());
- }
-
- public int getMapCenterLatitudeE6() {
- return (int)(Mercator.tile2lat(getScrollY() + getWorldSizePx()/2, getPixelZoomLevel()) * 1E6);
- }
-
- public int getMapCenterLongitudeE6() {
- return (int)(Mercator.tile2lon(getScrollX() + getWorldSizePx()/2, getPixelZoomLevel()) * 1E6);
- }
-
- public void onSaveInstanceState(android.os.Bundle state) {
- state.putInt(BUNDLE_RENDERER, getRenderer().ordinal());
- state.putInt(BUNDLE_SCROLL_X, getScrollX());
- state.putInt(BUNDLE_SCROLL_Y, getScrollY());
- state.putInt(BUNDLE_ZOOM_LEVEL, getZoomLevel());
- }
-
- public void onRestoreInstanceState(android.os.Bundle state) {
- setRenderer(OpenStreetMapRendererInfo.values()[state.getInt(BUNDLE_RENDERER, 0)]);
- setZoomLevel(state.getInt(BUNDLE_ZOOM_LEVEL, 1));
- scrollTo(state.getInt(BUNDLE_SCROLL_X, 0), state.getInt(BUNDLE_SCROLL_Y, 0));
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- public void onLongPress(MotionEvent e) {
- for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
- if (osmvo.onLongPress(e, this))
- return;
- }
-
- public boolean onSingleTapUp(MotionEvent e) {
- for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
- if (osmvo.onSingleTapUp(e, this)) {
- postInvalidate();
- return true;
- }
-
- return false;
- }
-
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
- if (osmvo.onKeyDown(keyCode, event, this))
- return true;
-
- return super.onKeyDown(keyCode, event);
- }
-
- @Override
- public boolean onKeyUp(int keyCode, KeyEvent event) {
- for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
- if (osmvo.onKeyUp(keyCode, event, this))
- return true;
-
- return super.onKeyUp(keyCode, event);
- }
-
- @Override
- public boolean onTrackballEvent(MotionEvent event) {
- for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
- if (osmvo.onTrackballEvent(event, this))
- return true;
-
- scrollBy((int)(event.getX() * 25), (int)(event.getY() * 25));
-
- return super.onTrackballEvent(event);
- }
-
- @Override
- public boolean onTouchEvent(final MotionEvent event) {
-
- Log.d(DEBUGTAG, "onTouchEvent(" + event + ")");
-
- /*
- * handle multi touch events:
- * 1. mask out the action with the ACTION_MASK
- * 2. measure the spreading
- * 3. on ACTION_POINTER_DOWN remember the spreading in the
- * pointerDownDistance and set multiDown mode to ACTIVE
- * 4. on first move changing the spreading by a
- * factor of 2 or a factor of 0.5 increase or
- * decrease the zoom level
- * switch off multiDown mode and set it to HANDLED
- * 5. on ACTION_POINTER_UP also switch off the multiDown mode
- * 6. in any of these cases: claim the event handled and
- * return true
- */
- final int action = event.getAction() & ACTION_MASK;
-
- if (action == ACTION_POINTER_DOWN) {
- mPointerDownDistance = spreading(event);
- mMultiMode = MULTI_ACTIVE;
- return true;
- } else if (action == ACTION_POINTER_UP) {
- mMultiMode = MULTI_NONE;
- return true;
- } else if (mMultiMode != MULTI_NONE) {
- if (mMultiMode == MULTI_ACTIVE && action == MotionEvent.ACTION_MOVE) {
- final float pointerUpDistance = spreading(event);
-
- if (pointerUpDistance > 2 * mPointerDownDistance) {
- mMultiMode = MULTI_HANDLED;
- setZoomLevel(mZoomLevel + 1);
- } else if (pointerUpDistance < 0.5 * mPointerDownDistance) {
- setZoomLevel(mZoomLevel - 1);
- mMultiMode = MULTI_HANDLED;
- }
- }
- return true;
- }
-
- for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
- if (osmvo.onTouchEvent(event, this))
- return true;
-
- if (this.mGestureDetector.onTouchEvent(event))
- return true;
-
- return super.onTouchEvent(event);
- }
-
- @Override
- public void computeScroll() {
- if (mScroller.computeScrollOffset()) {
-// int oldX = getScrollX();
-// int oldY = getScrollY();
-// int x = mScroller.getCurrX();
-// int y = mScroller.getCurrY();
-// if (x != oldX || y != oldY)
- if (mScroller.isFinished())
- mController.onScrollingFinished();
- else
- scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
- postInvalidate(); // Keep on drawing until the animation has finished.
- }
- }
-
- private float spreading(final MotionEvent event) {
- // TODO can do this directly if we upgrade to API level 5
- try {
- final float x0 = Float.valueOf(MotionEvent_getX.invoke(event, 0).toString());
- final float x1 = Float.valueOf(MotionEvent_getX.invoke(event, 1).toString());
- final float y0 = Float.valueOf(MotionEvent_getY.invoke(event, 0).toString());
- final float y1 = Float.valueOf(MotionEvent_getY.invoke(event, 1).toString());
- final float x = x0 - x1;
- final float y = y0 - y1;
- return FloatMath.sqrt(x * x + y * y);
- } catch(final Exception e) {
- return 1;
- }
- }
-
- private void computeScale() {
- if (mScaler.computeScale()) {
- if (mScaler.isFinished())
- mController.onScalingFinished();
- else
- postInvalidate();
- }
- }
-
- @Override
- public void scrollTo(int x, int y) {
- final int worldSize = getWorldSizePx();
- x %= worldSize;
- y %= worldSize;
- super.scrollTo(x, y);
- }
-
- @Override
- protected void onSizeChanged(int w, int h, int oldw, int oldh) {
- if(this.mBackBuffer != null) {
- this.mBackBuffer.recycle();
- this.mBackBuffer = null;
- }
- this.mBackBuffer = Bitmap.createBitmap(w, h, Config.ARGB_8888);
- this.mBackCanvas = new Canvas(this.mBackBuffer);
- super.onSizeChanged(w, h, oldw, oldh);
- }
-
- @Override
- public void onDraw(final Canvas c) {
- final long startMs = System.currentTimeMillis();
-
- mProjection = new OpenStreetMapViewProjection();
-
- c.translate(getWidth()/2, getHeight()/2);
- if (!mScaler.isFinished()) {
- Matrix m = c.getMatrix();
- m.preScale(mScaler.mCurrScale, mScaler.mCurrScale, getScrollX(), getScrollY());
- c.setMatrix(m);
- }
-
- /* Draw background */
- c.drawColor(Color.LTGRAY);
-// This is to slow:
-// final Rect r = c.getClipBounds();
-// mPaint.setColor(Color.GRAY);
-// mPaint.setPathEffect(new DashPathEffect(new float[] {1, 1}, 0));
-// for (int x = r.left; x < r.right; x += 20)
-// c.drawLine(x, r.top, x, r.bottom, mPaint);
-// for (int y = r.top; y < r.bottom; y += 20)
-// c.drawLine(r.left, y, r.right, y, mPaint);
-
- /* Draw all Overlays. */
- for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
- osmvo.onManagedDraw(c, this);
-
- if (this.mMaxiMap != null) { // If this is a MiniMap
- this.mPaint.setColor(Color.RED);
- this.mPaint.setStyle(Style.STROKE);
- final int viewWidth = this.getWidth();
- final int viewHeight = this.getHeight();
- c.drawRect(0, 0, viewWidth, viewHeight, this.mPaint);
- }
-
- final long endMs = System.currentTimeMillis();
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "Rendering overall: " + (endMs - startMs) + "ms");
- computeScale();
- }
-
- @Override
- protected void onDetachedFromWindow() {
- this.mZoomController.setVisible(false);
- this.mMapOverlay.detach();
- super.onDetachedFromWindow();
- }
-
- // ===========================================================
- // Package Methods
- // ===========================================================
-
- /**
- * Get the world size in pixels.
- */
- int getWorldSizePx() {
- return (1 << getPixelZoomLevel());
- }
-
- /**
- * Get the equivalent zoom level on pixel scale
- */
- int getPixelZoomLevel() {
- return this.mZoomLevel + this.mMapOverlay.getRendererInfo().MAPTILE_ZOOM;
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- private void checkZoomButtons() {
- final int maxZoomLevel = this.mMapOverlay.getRendererInfo().ZOOM_MAXLEVEL;
- this.mZoomController.setZoomInEnabled(mZoomLevel < maxZoomLevel);
- this.mZoomController.setZoomOutEnabled(mZoomLevel > 0);
- }
-
- private int[] getCenterMapTileCoords() {
- final int mapTileZoom = this.mMapOverlay.getRendererInfo().MAPTILE_ZOOM;
- final int worldTiles_2 = 1 << (mZoomLevel-1);
- // convert to tile coordinate and make positive
- return new int[] { (getScrollY() >> mapTileZoom) + worldTiles_2,
- (getScrollX() >> mapTileZoom) + worldTiles_2 };
- }
-
- /**
- * @param centerMapTileCoords
- * @param tileSizePx
- * @param reuse
- * just pass null if you do not have a Point to be 'recycled'.
- */
- private Point getUpperLeftCornerOfCenterMapTileInScreen(final int[] centerMapTileCoords,
- final int tileSizePx, final Point reuse) {
- final Point out = (reuse != null) ? reuse : new Point();
-
- final int worldTiles_2 = 1 << (mZoomLevel-1);
- final int centerMapTileScreenLeft = (centerMapTileCoords[MAPTILE_LONGITUDE_INDEX] - worldTiles_2) * tileSizePx - tileSizePx/2;
- final int centerMapTileScreenTop = (centerMapTileCoords[MAPTILE_LATITUDE_INDEX] - worldTiles_2) * tileSizePx - tileSizePx/2;
-
- out.set(centerMapTileScreenLeft, centerMapTileScreenTop);
- return out;
- }
-
- public void setBuiltInZoomControls(boolean on) {
- this.mEnableZoomController = on;
- this.checkZoomButtons();
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-
- /**
- * This class may return valid results until the underlying
- * {@link OpenStreetMapView} gets modified in any way (i.e. new center).
- *
- * @author Nicolas Gramlich
- * @author Manuel Stahl
- */
- public class OpenStreetMapViewProjection {
-
- private final int viewWidth_2 = getWidth() / 2;
- private final int viewHeight_2 = getHeight() / 2;
- private final int worldSize_2 = getWorldSizePx()/2;
- private final int offsetX = - worldSize_2;
- private final int offsetY = - worldSize_2;
-
- private final BoundingBoxE6 bb;
- private final int zoomLevel;
- private final int tileSizePx;
- private final int[] centerMapTileCoords;
- private final Point upperLeftCornerOfCenterMapTile;
-
- private final int[] reuseInt2 = new int[2];
-
- public OpenStreetMapViewProjection() {
-
- /*
- * Do some calculations and drag attributes to local variables to
- * save some performance.
- */
- zoomLevel = OpenStreetMapView.this.mZoomLevel; // TODO Draw to
- // attributes and so
- // make it only
- // 'valid' for a
- // short time.
- tileSizePx = getRenderer().MAPTILE_SIZEPX;
-
- /*
- * Get the center MapTile which is above this.mLatitudeE6 and
- * this.mLongitudeE6 .
- */
- centerMapTileCoords = getCenterMapTileCoords();
- upperLeftCornerOfCenterMapTile = getUpperLeftCornerOfCenterMapTileInScreen(
- centerMapTileCoords, tileSizePx, null);
-
- bb = OpenStreetMapView.this.getDrawnBoundingBoxE6();
- }
-
- /**
- * Converts x/y ScreenCoordinates to the underlying GeoPoint.
- *
- * @param x
- * @param y
- * @return GeoPoint under x/y.
- */
- public GeoPoint fromPixels(float x, float y) {
- return bb.getGeoPointOfRelativePositionWithLinearInterpolation(x / viewWidth_2, y
- / viewHeight_2);
- }
-
- public Point fromMapPixels(int x, int y, Point reuse) {
- final Point out = (reuse != null) ? reuse : new Point();
- out.set(x - viewWidth_2, y - viewHeight_2);
- out.offset(getScrollX(), getScrollY());
- return out;
- }
-
- private static final int EQUATORCIRCUMFENCE = 40075004;
-
- public float metersToEquatorPixels(final float aMeters) {
- return aMeters / EQUATORCIRCUMFENCE * getWorldSizePx();
- }
-
- /**
- * Converts a GeoPoint to its ScreenCoordinates. <br/>
- * <br/>
- * <b>CAUTION</b> ! Conversion currently has a large error on
- * <code>zoomLevels <= 7</code>.<br/>
- * The Error on ZoomLevels higher than 7, the error is below
- * <code>1px</code>.<br/>
- * TODO: Add a linear interpolation to minimize this error.
- *
- * <PRE>
- * Zoom Error(m) Error(px)
- * 11 6m 1/12px
- * 10 24m 1/6px
- * 8 384m 1/2px
- * 6 6144m 3px
- * 4 98304m 10px
- * </PRE>
- *
- * @param in
- * the GeoPoint you want the onScreenCoordinates of.
- * @param reuse
- * just pass null if you do not have a Point to be
- * 'recycled'.
- * @return the Point containing the approximated ScreenCoordinates of
- * the GeoPoint passed.
- */
- public Point toMapPixels(final GeoPoint in, final Point reuse) {
- final Point out = (reuse != null) ? reuse : new Point();
-
- final int[] coords = Mercator.projectGeoPoint(in.getLatitudeE6(), in.getLongitudeE6(), getPixelZoomLevel(), null);
- out.set(coords[MAPTILE_LONGITUDE_INDEX], coords[MAPTILE_LATITUDE_INDEX]);
- out.offset(offsetX, offsetY);
- return out;
- }
-
- /**
- * Performs only the first computationally heavy part of the projection, needToCall toMapPixelsTranslated to get final position.
- * @param latituteE6
- * the latitute of the point
- * @param longitudeE6
- * the longitude of the point
- * @param reuse
- * just pass null if you do not have a Point to be
- * 'recycled'.
- * @return intermediate value to be stored and passed to toMapPixelsTranslated on paint.
- */
- public Point toMapPixelsProjected(final int latituteE6, final int longitudeE6, final Point reuse) {
- final Point out = (reuse != null) ? reuse : new Point();
-
- //26 is the biggest zoomlevel we can project
- final int[] coords = Mercator.projectGeoPoint(latituteE6, longitudeE6, 28, this.reuseInt2);
- out.set(coords[MAPTILE_LONGITUDE_INDEX], coords[MAPTILE_LATITUDE_INDEX]);
- return out;
- }
-
- /**
- * Performs the second computationally light part of the projection.
- * @param in
- * the Point calculated by the toMapPixelsProjected
- * @param reuse
- * just pass null if you do not have a Point to be
- * 'recycled'.
- * @return the Point containing the approximated ScreenCoordinates of
- * the initial GeoPoint passed to the toMapPixelsProjected.
- */
- public Point toMapPixelsTranslated(final Point in, final Point reuse) {
- final Point out = (reuse != null) ? reuse : new Point();
-
- //26 is the biggest zoomlevel we can project
- int zoomDifference = 28 - getPixelZoomLevel();
- out.set((in.x >> zoomDifference) + offsetX , (in.y >> zoomDifference) + offsetY );
- return out;
- }
-
-
- /**
- * Translates a rectangle from screen coordinates to intermediate coordinates.
- * @param in the rectangle in screen coordinates
- * @return a rectangle in intermediate coords.
- */
- public Rect fromPixelsToProjected(final Rect in)
- {
- Rect result = new Rect();
-
- //26 is the biggest zoomlevel we can project
- int zoomDifference = 28 - getPixelZoomLevel();
-
- int x0 = (in.left - offsetX) << zoomDifference;
- int x1 = (in.right - offsetX) << zoomDifference;
- int y0 = (in.bottom - offsetX) << zoomDifference;
- int y1 = (in.top - offsetX) << zoomDifference;
-
- result.set(Math.min(x0,x1), Math.min(y0,y1), Math.max(x0,x1), Math.max(y0,y1));
- return result;
- }
-
- public Point toPixels(final int[] tileCoords, final Point reuse) {
- return toPixels(tileCoords[MAPTILE_LONGITUDE_INDEX], tileCoords[MAPTILE_LATITUDE_INDEX], reuse);
- }
-
- public Point toPixels(int tileX, int tileY, final Point reuse) {
- final Point out = (reuse != null) ? reuse : new Point();
-
- out.set(tileX * tileSizePx, tileY * tileSizePx);
- out.offset(offsetX, offsetY);
-
- return out;
- }
-
- public Path toPixels(final List<? extends GeoPoint> in, final Path reuse) {
- return toPixels(in, reuse, true);
- }
-
- protected Path toPixels(final List<? extends GeoPoint> in, final Path reuse, final boolean doGudermann)
- throws IllegalArgumentException {
- if (in.size() < 2)
- throw new IllegalArgumentException("List of GeoPoints needs to be at least 2.");
-
- final Path out = (reuse != null) ? reuse : new Path();
- out.incReserve(in.size());
-
- boolean first = true;
- for (GeoPoint gp : in) {
- final int[] underGeopointTileCoords = Mercator.projectGeoPoint(gp
- .getLatitudeE6(), gp.getLongitudeE6(), zoomLevel, null);
-
- /*
- * Calculate the Latitude/Longitude on the left-upper
- * ScreenCoords of the MapTile.
- */
- final BoundingBoxE6 bb = Mercator.getBoundingBoxFromMapTile(underGeopointTileCoords,
- zoomLevel);
-
- final float[] relativePositionInCenterMapTile;
- if (doGudermann && zoomLevel < 7)
- relativePositionInCenterMapTile = bb
- .getRelativePositionOfGeoPointInBoundingBoxWithExactGudermannInterpolation(
- gp.getLatitudeE6(), gp.getLongitudeE6(), null);
- else
- relativePositionInCenterMapTile = bb
- .getRelativePositionOfGeoPointInBoundingBoxWithLinearInterpolation(gp
- .getLatitudeE6(), gp.getLongitudeE6(), null);
-
- final int tileDiffX = centerMapTileCoords[MAPTILE_LONGITUDE_INDEX]
- - underGeopointTileCoords[MAPTILE_LONGITUDE_INDEX];
- final int tileDiffY = centerMapTileCoords[MAPTILE_LATITUDE_INDEX]
- - underGeopointTileCoords[MAPTILE_LATITUDE_INDEX];
- final int underGeopointTileScreenLeft = upperLeftCornerOfCenterMapTile.x
- - (tileSizePx * tileDiffX);
- final int underGeopointTileScreenTop = upperLeftCornerOfCenterMapTile.y
- - (tileSizePx * tileDiffY);
-
- final int x = underGeopointTileScreenLeft
- + (int) (relativePositionInCenterMapTile[MAPTILE_LONGITUDE_INDEX] * tileSizePx);
- final int y = underGeopointTileScreenTop
- + (int) (relativePositionInCenterMapTile[MAPTILE_LATITUDE_INDEX] * tileSizePx);
-
- /* Add up the offset caused by touch. */
- if (first)
- out.moveTo(x, y);
-// out.moveTo(x + OpenStreetMapView.this.mTouchMapOffsetX, y
-// + OpenStreetMapView.this.mTouchMapOffsetY);
- else
- out.lineTo(x, y);
- first = false;
- }
-
- return out;
- }
- }
-
- private class OpenStreetMapViewGestureDetectorListener implements OnGestureListener {
-
- @Override
- public boolean onDown(MotionEvent e) {
- mZoomController.setVisible(mEnableZoomController);
- return true;
- }
-
- @Override
- public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
- final int worldSize = getWorldSizePx();
- mScroller.fling(getScrollX(), getScrollY(), (int)-velocityX, (int)-velocityY, -worldSize, worldSize, -worldSize, worldSize);
- return true;
- }
-
- @Override
- public void onLongPress(MotionEvent e) {
- OpenStreetMapView.this.onLongPress(e);
- }
-
- @Override
- public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
- scrollBy((int)distanceX, (int)distanceY);
- return true;
- }
-
- @Override
- public void onShowPress(MotionEvent e) {
- }
-
- @Override
- public boolean onSingleTapUp(MotionEvent e) {
- return OpenStreetMapView.this.onSingleTapUp(e);
- }
-
- }
-
- private class OpenStreetMapViewZoomListener implements OnZoomListener {
- @Override
- public void onZoom(boolean zoomIn) {
- if(zoomIn)
- getController().zoomIn();
- else
- getController().zoomOut();
- }
- @Override
- public void onVisibilityChanged(boolean visible) {}
- }
-
- class Scaler {
-
- private float mStartScale;
- private float mFinalScale;
- private float mCurrScale;
-
- private long mStartTime;
- private int mDuration;
- private float mDurationReciprocal;
- private float mDeltaScale;
- private boolean mFinished;
- private Interpolator mInterpolator;
-
- /**
- * Create a Scaler with the specified interpolator.
- */
- public Scaler(Context context, Interpolator interpolator) {
- mFinished = true;
- mInterpolator = interpolator;
- }
-
- /**
- *
- * Returns whether the scaler has finished scaling.
- *
- * @return True if the scaler has finished scaling, false otherwise.
- */
- public final boolean isFinished() {
- return mFinished;
- }
-
- /**
- * Force the finished field to a particular value.
- *
- * @param finished The new finished value.
- */
- public final void forceFinished(boolean finished) {
- mFinished = finished;
- }
-
- /**
- * Returns how long the scale event will take, in milliseconds.
- *
- * @return The duration of the scale in milliseconds.
- */
- public final int getDuration() {
- return mDuration;
- }
-
- /**
- * Returns the current scale factor.
- *
- * @return The new scale factor.
- */
- public final float getCurrScale() {
- return mCurrScale;
- }
-
- /**
- * Returns the start scale factor.
- *
- * @return The start scale factor.
- */
- public final float getStartScale() {
- return mStartScale;
- }
-
- /**
- * Returns where the scale will end.
- *
- * @return The final scale factor.
- */
- public final float getFinalScale() {
- return mFinalScale;
- }
-
- /**
- * Sets the final scale for this scaler.
- *
- * @param newScale The new scale factor.
- */
- public void setFinalScale(float newScale) {
- mFinalScale = newScale;
- mDeltaScale = mFinalScale - mStartScale;
- mFinished = false;
- }
-
-
- /**
- * Call this when you want to know the new scale. If it returns true,
- * the animation is not yet finished.
- */
- public boolean computeScale() {
- if (mFinished) {
- mCurrScale = 1.0f;
- return false;
- }
-
- int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
-
- if (timePassed < mDuration) {
- float x = (float)timePassed * mDurationReciprocal;
-
- x = mInterpolator.getInterpolation(x);
-
- mCurrScale = mStartScale + x * mDeltaScale;
- if (mCurrScale == mFinalScale)
- mFinished = true;
-
- } else {
- mCurrScale = mFinalScale;
- mFinished = true;
- }
- return true;
- }
-
- /**
- * Start scaling by providing the starting scale and the final scale.
- *
- * @param startX Starting horizontal scroll offset in pixels. Positive
- * numbers will scroll the content to the left.
- * @param startY Starting vertical scroll offset in pixels. Positive numbers
- * will scroll the content up.
- * @param dx Horizontal distance to travel. Positive numbers will scroll the
- * content to the left.
- * @param dy Vertical distance to travel. Positive numbers will scroll the
- * content up.
- * @param duration Duration of the scroll in milliseconds.
- */
- public void startScale(float startScale, float finalScale, int duration) {
- mFinished = false;
- mDuration = duration;
- mStartTime = AnimationUtils.currentAnimationTimeMillis();
- mStartScale = startScale;
- mFinalScale = finalScale;
- mDeltaScale = finalScale - startScale;
- mDurationReciprocal = 1.0f / (float) mDuration;
- }
-
- /**
- * Extend the scale animation. This allows a running animation to scale
- * further and longer, when used with {@link #setFinalScale(float)}.
- *
- * @param extend Additional time to scale in milliseconds.
- * @see #setFinalScale(float)
- */
- public void extendDuration(int extend) {
- int passed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
- mDuration = passed + extend;
- mDurationReciprocal = 1.0f / (float)mDuration;
- mFinished = false;
- }
-
- }
-
-}
diff --git a/cardroid/src/org/andnav/osm/views/OpenStreetMapViewController.java b/cardroid/src/org/andnav/osm/views/OpenStreetMapViewController.java
deleted file mode 100644
index f20b836..0000000
--- a/cardroid/src/org/andnav/osm/views/OpenStreetMapViewController.java
+++ /dev/null
@@ -1,629 +0,0 @@
-// Created by plusminus on 21:37:08 - 27.09.2008
-package org.andnav.osm.views;
-
-import org.andnav.osm.util.BoundingBoxE6;
-import org.andnav.osm.util.GeoPoint;
-import org.andnav.osm.views.OpenStreetMapView.Scaler;
-import org.andnav.osm.views.util.MyMath;
-import org.andnav.osm.views.util.Mercator;
-import org.andnav.osm.views.util.constants.MathConstants;
-
-import android.graphics.Point;
-
-/**
- *
- * @author Nicolas Gramlich
- * TODO use same interface as google maps controller
- */
-public class OpenStreetMapViewController {
- // ===========================================================
- // Constants
- // ===========================================================
-
- public static final int ANIMATION_SMOOTHNESS_LOW = 4;
- public static final int ANIMATION_SMOOTHNESS_DEFAULT = 10;
- public static final int ANIMATION_SMOOTHNESS_HIGH = 20;
-
- public static final int ANIMATION_DURATION_SHORT = 500;
- public static final int ANIMATION_DURATION_DEFAULT = 1000;
- public static final int ANIMATION_DURATION_LONG = 2000;
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- private int mZoomLevel;
- private final OpenStreetMapView mOsmv;
- private AbstractAnimationRunner mCurrentAnimationRunner;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public OpenStreetMapViewController(final OpenStreetMapView osmv) {
- this.mOsmv = osmv;
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- public void zoomToSpan(BoundingBoxE6 bb) {
- zoomToSpan(bb.getLatitudeSpanE6(), bb.getLongitudeSpanE6());
- }
-
- // TODO rework zoomToSpan
- public void zoomToSpan(final int reqLatSpan, final int reqLonSpan) {
- if(reqLatSpan <= 0 || reqLonSpan <= 0 )
- return;
-
- final BoundingBoxE6 bb = this.mOsmv.getVisibleBoundingBoxE6();
- final int curZoomLevel = this.mOsmv.getZoomLevel();
-
- final int curLatSpan = bb.getLatitudeSpanE6();
- final int curLonSpan = bb.getLongitudeSpanE6();
-
- final float diffNeededLat = (float)reqLatSpan / curLatSpan; // i.e. 600/500 = 1,2
- final float diffNeededLon = (float)reqLonSpan / curLonSpan; // i.e. 300/400 = 0,75
-
- final float diffNeeded = Math.max(diffNeededLat, diffNeededLon); // i.e. 1,2
-
- if(diffNeeded > 1){ // Zoom Out
- this.mOsmv.setZoomLevel(curZoomLevel - MyMath.getNextSquareNumberAbove(diffNeeded));
- }else if(diffNeeded < 0.5){ // Can Zoom in
- this.mOsmv.setZoomLevel(curZoomLevel + MyMath.getNextSquareNumberAbove(1 / diffNeeded) - 1);
- }
- }
-
- /**
- * Start animating the map towards the given point.
- */
- public void animateTo(final GeoPoint point) {
- final int x = mOsmv.getScrollX();
- final int y = mOsmv.getScrollY();
- final Point p = Mercator.projectGeoPoint(point, this.mOsmv.getPixelZoomLevel(), null);
- final int worldSize_2 = this.mOsmv.getWorldSizePx()/2;
- mOsmv.mScroller.startScroll(x, y, p.x - worldSize_2 - x, p.y - worldSize_2 - y, ANIMATION_DURATION_DEFAULT);
- mOsmv.postInvalidate();
- }
-
- /**
- * Animates the underlying {@link OpenStreetMapView} that it centers the passed {@link GeoPoint} in the end.
- * Uses: {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT} and {@link OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT}.
- * @param gp
- */
- public void animateTo(final GeoPoint gp, final AnimationType aAnimationType){
- animateTo(gp.getLatitudeE6(), gp.getLongitudeE6(), aAnimationType, ANIMATION_DURATION_DEFAULT, ANIMATION_SMOOTHNESS_DEFAULT);
- }
-
- /**
- * Animates the underlying {@link OpenStreetMapView} that it centers the passed {@link GeoPoint} in the end.
- * @param gp GeoPoint to be centered in the end.
- * @param aSmoothness steps made during animation. I.e.: {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_LOW}, {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT}, {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_HIGH}
- * @param aDuration in Milliseconds. I.e.: {@link OpenStreetMapViewController.ANIMATION_DURATION_SHORT}, {@link OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT}, {@link OpenStreetMapViewController.ANIMATION_DURATION_LONG}
- */
- public void animateTo(final GeoPoint gp, final AnimationType aAnimationType, final int aSmoothness, final int aDuration){
- animateTo(gp.getLatitudeE6(), gp.getLongitudeE6(), aAnimationType, aSmoothness, aDuration);
- }
-
- /**
- * Animates the underlying {@link OpenStreetMapView} that it centers the passed coordinates in the end.
- * Uses: {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT} and {@link OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT}.
- * @param aLatitudeE6
- * @param aLongitudeE6
- */
- public void animateTo(final int aLatitudeE6, final int aLongitudeE6, final AnimationType aAnimationType){
- animateTo(aLatitudeE6, aLongitudeE6, aAnimationType, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
- }
-
- /**
- * Animates the underlying {@link OpenStreetMapView} that it centers the passed coordinates in the end.
- * @param aLatitudeE6
- * @param aLongitudeE6
- * @param aSmoothness steps made during animation. I.e.: {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_LOW}, {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT}, {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_HIGH}
- * @param aDuration in Milliseconds. I.e.: {@link OpenStreetMapViewController.ANIMATION_DURATION_SHORT}, {@link OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT}, {@link OpenStreetMapViewController.ANIMATION_DURATION_LONG}
- */
- public void animateTo(final int aLatitudeE6, final int aLongitudeE6, final AnimationType aAnimationType, final int aSmoothness, final int aDuration){
- this.stopAnimation(false);
-
- switch(aAnimationType){
- case LINEAR:
- this.mCurrentAnimationRunner = new LinearAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
- break;
- case EXPONENTIALDECELERATING:
- this.mCurrentAnimationRunner = new ExponentialDeceleratingAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
- break;
- case QUARTERCOSINUSALDECELERATING:
- this.mCurrentAnimationRunner = new QuarterCosinusalDeceleratingAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
- break;
- case HALFCOSINUSALDECELERATING:
- this.mCurrentAnimationRunner = new HalfCosinusalDeceleratingAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
- break;
- case MIDDLEPEAKSPEED:
- this.mCurrentAnimationRunner = new MiddlePeakSpeedAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
- break;
- }
-
- this.mCurrentAnimationRunner.start();
- }
-
- public void scrollBy(int x, int y) {
- this.mOsmv.scrollBy(x, y);
- }
-
- /**
- * Set the map view to the given center. There will be no animation.
- */
- public void setCenter(final GeoPoint point) {
- final Point p = Mercator.projectGeoPoint(point, this.mOsmv.getPixelZoomLevel(), null);
- final int worldSize_2 = this.mOsmv.getWorldSizePx()/2;
- this.mOsmv.scrollTo(p.x - worldSize_2, p.y - worldSize_2);
- }
-
- /**
- * Stops a running animation.
- * @param jumpToTarget
- */
- public void stopAnimation(final boolean jumpToTarget) {
- final AbstractAnimationRunner currentAnimationRunner = this.mCurrentAnimationRunner;
-
- if(currentAnimationRunner != null && !currentAnimationRunner.isDone()){
- currentAnimationRunner.interrupt();
- if(jumpToTarget)
- setCenter(new GeoPoint(currentAnimationRunner.mTargetLatitudeE6, currentAnimationRunner.mTargetLongitudeE6));
- }
- }
-
-
-
- public int setZoom(int zoomlevel) {
- this.mZoomLevel = zoomlevel;
- return mOsmv.setZoomLevel(zoomlevel);
- }
-
- /**
- * Zoom in by one zoom level.
- */
- public boolean zoomIn() {
-
- if (mZoomLevel >= mOsmv.getMaxZoomLevel()) {
- mZoomLevel = mOsmv.getMaxZoomLevel();
- return false;
- }
-
- mZoomLevel++;
- final Scaler scaler = mOsmv.mScaler;
- if (scaler.isFinished()) {
- scaler.startScale(1.0f, 2.0f, ANIMATION_DURATION_SHORT);
- mOsmv.postInvalidate();
- } else {
- scaler.extendDuration(ANIMATION_DURATION_SHORT);
- scaler.setFinalScale(scaler.getFinalScale() * 2.0f);
- }
-
- return true;
- }
-
- public boolean zoomInFixing(int xPixel, int yPixel) {
- // TODO implement
- return zoomIn();
- }
-
- /**
- * Zoom out by one zoom level.
- */
- public boolean zoomOut() {
-
- if (mZoomLevel <= 0) {
- mZoomLevel = 0;
- return false;
- }
-
- mZoomLevel--;
- final Scaler scaler = mOsmv.mScaler;
- if (scaler.isFinished()) {
- scaler.startScale(1.0f, 0.5f, ANIMATION_DURATION_SHORT);
- mOsmv.postInvalidate();
- } else {
- scaler.extendDuration(ANIMATION_DURATION_SHORT);
- scaler.setFinalScale(scaler.getFinalScale() * 0.5f);
- }
-
- return true;
- }
-
- public boolean zoomOutFixing(int xPixel, int yPixel) {
- // TODO implement
- return zoomOut();
- }
-
- void onScalingFinished() {
- mOsmv.setZoomLevel(mZoomLevel);
- }
-
- void onScrollingFinished() {
-
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-
- /**
- * Choose on of the Styles of approacing the target Coordinates.
- * <ul>
- * <li><code>LINEAR</code>
- * <ul>
- * <li>Uses ses linear interpolation </li>
- * <li>Values produced: 10%, 20%, 30%, 40%, 50%, ...</li>
- * <li>Style: Always average speed.</li>
- * </ul>
- * </li>
- * <li><code>EXPONENTIALDECELERATING</code>
- * <ul>
- * <li>Uses a exponential interpolation/li>
- * <li>Values produced: 50%, 75%, 87.5%, 93.5%, ...</li>
- * <li>Style: Starts very fast, really slow in the end.</li>
- * </ul>
- * </li>
- * <li><code>QUARTERCOSINUSALDECELERATING</code>
- * <ul>
- * <li>Uses the first quarter of the cos curve (from zero to PI/2) for interpolation. </li>
- * <li>Values produced: See cos curve :)</li>
- * <li>Style: Average speed, slows out medium.</li>
- * </ul>
- * </li>
- * <li><code>HALFCOSINUSALDECELERATING</code>
- * <ul>
- * <li>Uses the first half of the cos curve (from zero to PI) for interpolation</li>
- * <li>Values produced: See cos curve :)</li>
- * <li>Style: Average speed, slows out smoothly.</li>
- * </ul>
- * </li>
- * <li><code>MIDDLEPEAKSPEED</code>
- * <ul>
- * <li>Uses the values of cos around the 0 (from -PI/2 to +PI/2) for interpolation</li>
- * <li>Values produced: See cos curve :)</li>
- * <li>Style: Starts medium, speeds high in middle, slows out medium.</li>
- * </ul>
- * </li>
- * </ul>
- */
- public static enum AnimationType {
- /**
- * <ul>
- * <li><code>LINEAR</code>
- * <ul>
- * <li>Uses ses linear interpolation </li>
- * <li>Values produced: 10%, 20%, 30%, 40%, 50%, ...</li>
- * <li>Style: Always average speed.</li>
- * </ul>
- * </li>
- * </ul>
- */
- LINEAR,
- /**
- * <ul>
- * <li><code>EXPONENTIALDECELERATING</code>
- * <ul>
- * <li>Uses a exponential interpolation/li>
- * <li>Values produced: 50%, 75%, 87.5%, 93.5%, ...</li>
- * <li>Style: Starts very fast, really slow in the end.</li>
- * </ul>
- * </li>
- * </ul>
- */
- EXPONENTIALDECELERATING,
- /**
- * <ul>
- * <li><code>QUARTERCOSINUSALDECELERATING</code>
- * <ul>
- * <li>Uses the first quarter of the cos curve (from zero to PI/2) for interpolation. </li>
- * <li>Values produced: See cos curve :)</li>
- * <li>Style: Average speed, slows out medium.</li>
- * </ul>
- * </li>
- * </ul>
- */
- QUARTERCOSINUSALDECELERATING,
- /** <ul>
- * <li><code>HALFCOSINUSALDECELERATING</code>
- * <ul>
- * <li>Uses the first half of the cos curve (from zero to PI) for interpolation</li>
- * <li>Values produced: See cos curve :)</li>
- * <li>Style: Average speed, slows out smoothly.</li>
- * </ul>
- * </li>
- * </ul>
- */
- HALFCOSINUSALDECELERATING,
- /** <ul>
- * <li><code>MIDDLEPEAKSPEED</code>
- * <ul>
- * <li>Uses the values of cos around the 0 (from -PI/2 to +PI/2) for interpolation</li>
- * <li>Values produced: See cos curve :)</li>
- * <li>Style: Starts medium, speeds high in middle, slows out medium.</li>
- * </ul>
- * </li>
- * </ul>
- */
- MIDDLEPEAKSPEED;
- }
-
- private abstract class AbstractAnimationRunner extends Thread{
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final int mSmoothness, mDuration;
- protected final int mTargetLatitudeE6, mTargetLongitudeE6;
- protected boolean mDone = false;
-
- protected final int mStepDuration;
-
- protected final int mPanTotalLatitudeE6, mPanTotalLongitudeE6;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public AbstractAnimationRunner(OpenStreetMapViewController openStreetMapViewController, final int aTargetLatitudeE6, final int aTargetLongitudeE6){
- this(aTargetLatitudeE6, aTargetLongitudeE6, OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT, OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT);
- }
-
- public AbstractAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
- this.mTargetLatitudeE6 = aTargetLatitudeE6;
- this.mTargetLongitudeE6 = aTargetLongitudeE6;
- this.mSmoothness = aSmoothness;
- this.mDuration = aDuration;
-
- this.mStepDuration = aDuration / aSmoothness;
-
-
- /* Get the current mapview-center. */
- final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
- int mapCenterLatE6 = mapview.getMapCenterLatitudeE6();
- int mapCenterLonE6 = mapview.getMapCenterLongitudeE6();
-
- this.mPanTotalLatitudeE6 = (mapCenterLatE6 - aTargetLatitudeE6);
- this.mPanTotalLongitudeE6 = (mapCenterLonE6 - aTargetLongitudeE6);
- }
-
- public void run(){
- onRunAnimation();
- this.mDone = true;
- }
-
- public boolean isDone(){
- return this.mDone;
- }
-
- public abstract void onRunAnimation();
- }
-
- private class LinearAnimationRunner extends AbstractAnimationRunner{
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final int mPanPerStepLatitudeE6, mPanPerStepLongitudeE6;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public LinearAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
- this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
- }
-
- public LinearAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
- super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration);
-
- /* Get the current mapview-center. */
- final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
- int mapCenterLatE6 = mapview.getMapCenterLatitudeE6();
- int mapCenterLonE6 = mapview.getMapCenterLongitudeE6();
-
- this.mPanPerStepLatitudeE6 = (mapCenterLatE6 - aTargetLatitudeE6) / aSmoothness;
- this.mPanPerStepLongitudeE6 = (mapCenterLonE6 - aTargetLongitudeE6) / aSmoothness;
-
- this.setName("LinearAnimationRunner");
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- public void onRunAnimation(){
- final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
- final int panPerStepLatitudeE6 = this.mPanPerStepLatitudeE6;
- final int panPerStepLongitudeE6 = this.mPanPerStepLongitudeE6;
- final int stepDuration = this.mStepDuration;
- try {
- int newMapCenterLatE6;
- int newMapCenterLonE6;
-
- for(int i = this.mSmoothness; i > 0 ; i--){
-
- newMapCenterLatE6 = mapview.getMapCenterLatitudeE6() - panPerStepLatitudeE6;
- newMapCenterLonE6 = mapview.getMapCenterLongitudeE6() - panPerStepLongitudeE6;
- mapview.setMapCenter(newMapCenterLatE6, newMapCenterLonE6);
-
- Thread.sleep(stepDuration);
- }
- } catch (Exception e) {
- this.interrupt();
- }
- }
- }
-
- private class ExponentialDeceleratingAnimationRunner extends AbstractAnimationRunner{
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public ExponentialDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
- this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
- }
-
- public ExponentialDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
- super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration);
-
- this.setName("ExponentialDeceleratingAnimationRunner");
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- public void onRunAnimation(){
- final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
- final int stepDuration = this.mStepDuration;
- try {
- int newMapCenterLatE6;
- int newMapCenterLonE6;
-
- for(int i = 0; i < this.mSmoothness; i++){
-
- final double delta = Math.pow(0.5, i + 1);
- final int deltaLatitudeE6 = (int)(this.mPanTotalLatitudeE6 * delta);
- final int detlaLongitudeE6 = (int)(this.mPanTotalLongitudeE6 * delta);
-
- newMapCenterLatE6 = mapview.getMapCenterLatitudeE6() - deltaLatitudeE6;
- newMapCenterLonE6 = mapview.getMapCenterLongitudeE6() - detlaLongitudeE6;
- mapview.setMapCenter(newMapCenterLatE6, newMapCenterLonE6);
-
- Thread.sleep(stepDuration);
- }
- mapview.setMapCenter(super.mTargetLatitudeE6, super.mTargetLongitudeE6);
- } catch (Exception e) {
- this.interrupt();
- }
- }
- }
-
- private class CosinusalBasedAnimationRunner extends AbstractAnimationRunner implements MathConstants{
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final float mStepIncrement, mAmountStretch;
- protected final float mYOffset, mRange, mStart;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public CosinusalBasedAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final float aStart, final float aRange, final float aYOffset){
- this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT, aStart, aRange, aYOffset);
- }
-
- public CosinusalBasedAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration, final float aStart, final float aRange, final float aYOffset){
- super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration);
- this.mYOffset = aYOffset;
- this.mRange = aRange;
- this.mStart = aStart;
-
- this.mStepIncrement = aRange / aSmoothness;
-
- /* We need to normalize the amount in the end, so wee need the the: sum^(-1) . */
- float amountSum = 0;
- for(int i = 0; i < aSmoothness; i++)
- amountSum += aYOffset + Math.cos(this.mStepIncrement * i + aStart);
-
- this.mAmountStretch = 1 / amountSum;
-
- this.setName("QuarterCosinusalDeceleratingAnimationRunner");
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- public void onRunAnimation(){
- final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
- final int stepDuration = this.mStepDuration;
- final float amountStretch = this.mAmountStretch;
- try {
- int newMapCenterLatE6;
- int newMapCenterLonE6;
-
- for(int i = 0; i < this.mSmoothness; i++){
-
- final double delta = (this.mYOffset + Math.cos(this.mStepIncrement * i + this.mStart)) * amountStretch;
- final int deltaLatitudeE6 = (int)(this.mPanTotalLatitudeE6 * delta);
- final int deltaLongitudeE6 = (int)(this.mPanTotalLongitudeE6 * delta);
-
- newMapCenterLatE6 = mapview.getMapCenterLatitudeE6() - deltaLatitudeE6;
- newMapCenterLonE6 = mapview.getMapCenterLongitudeE6() - deltaLongitudeE6;
- mapview.setMapCenter(newMapCenterLatE6, newMapCenterLonE6);
-
- Thread.sleep(stepDuration);
- }
- mapview.setMapCenter(super.mTargetLatitudeE6, super.mTargetLongitudeE6);
- } catch (Exception e) {
- this.interrupt();
- }
- }
- }
-
- protected class QuarterCosinusalDeceleratingAnimationRunner extends CosinusalBasedAnimationRunner implements MathConstants{
- // ===========================================================
- // Constructors
- // ===========================================================
-
- protected QuarterCosinusalDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
- this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
- }
-
- protected QuarterCosinusalDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
- super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration, 0, PI_2, 0);
- }
- }
-
- protected class HalfCosinusalDeceleratingAnimationRunner extends CosinusalBasedAnimationRunner implements MathConstants{
- // ===========================================================
- // Constructors
- // ===========================================================
-
- protected HalfCosinusalDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
- this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
- }
-
- protected HalfCosinusalDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
- super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration, 0, PI, 1);
- }
- }
-
- protected class MiddlePeakSpeedAnimationRunner extends CosinusalBasedAnimationRunner implements MathConstants{
- // ===========================================================
- // Constructors
- // ===========================================================
-
- protected MiddlePeakSpeedAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
- this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
- }
-
- protected MiddlePeakSpeedAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
- super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration, -PI_2, PI, 0);
- }
- }
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/MyLocationOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/MyLocationOverlay.java
deleted file mode 100644
index 4feb96c..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/MyLocationOverlay.java
+++ /dev/null
@@ -1,269 +0,0 @@
-// Created by plusminus on 22:01:11 - 29.09.2008
-package org.andnav.osm.views.overlay;
-
-import java.util.LinkedList;
-
-import org.andnav.osm.R;
-import org.andnav.osm.util.GeoPoint;
-import org.andnav.osm.util.NetworkLocationIgnorer;
-import org.andnav.osm.views.OpenStreetMapView;
-import org.andnav.osm.views.OpenStreetMapViewController;
-import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
-import org.andnav.osm.views.overlay.OpenStreetMapViewOverlay.Snappable;
-
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Canvas;
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import android.graphics.Point;
-import android.graphics.Paint.Style;
-import android.location.Location;
-import android.location.LocationListener;
-import android.location.LocationManager;
-import android.location.LocationProvider;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.MotionEvent;
-
-/**
- *
- * @author Manuel Stahl
- *
- */
-public class MyLocationOverlay extends OpenStreetMapViewOverlay implements LocationListener, Snappable {
-
- public static final String DEBUGTAG = "OPENSTREETMAP";
-
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final Paint mPaint = new Paint();
- protected final Paint mCirclePaint = new Paint();
-
- protected final Bitmap PERSON_ICON;
- protected final Bitmap DIRECTION_ARROW;
-
- private final OpenStreetMapView mMapView;
- private final OpenStreetMapViewController mMapController;
- private final LocationManager mLocationManager;
- private boolean mMyLocationEnabled = false;
- private LinkedList<Runnable> mRunOnFirstFix = new LinkedList<Runnable>();
- private final Point mMapCoords = new Point();
-
- private Location mLocation;
- protected boolean mFollow = false; // follow location updates
- private NetworkLocationIgnorer mIgnorer = new NetworkLocationIgnorer();
-
- private final Matrix directionRotater = new Matrix();
-
- /** Coordinates the feet of the person are located. */
- protected final android.graphics.Point PERSON_HOTSPOT = new android.graphics.Point(24,39);
-
- private final float DIRECTION_ARROW_CENTER_X;
- private final float DIRECTION_ARROW_CENTER_Y;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public MyLocationOverlay(final Context ctx, final OpenStreetMapView mapView) {
- mMapView = mapView;
- mLocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
- mMapController = mapView.getController();
- mCirclePaint.setARGB(0, 100, 100, 255);
- mCirclePaint.setAntiAlias(true);
-
- PERSON_ICON = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.person);
- DIRECTION_ARROW = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.direction_arrow);
-
- DIRECTION_ARROW_CENTER_X = DIRECTION_ARROW.getWidth() / 2 - 0.5f;
- DIRECTION_ARROW_CENTER_Y = DIRECTION_ARROW.getHeight() / 2 - 0.5f;
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public Location getLastFix() {
- return mLocation;
- }
-
- /**
- * Return a GeoPoint of the last known location, or null if not known.
- */
- public GeoPoint getMyLocation() {
- if (mLocation == null) {
- return null;
- } else {
- return new GeoPoint(mLocation);
- }
- }
-
- public boolean isMyLocationEnabled() {
- return mMyLocationEnabled;
- }
-
- public boolean isLocationFollowEnabled() {
- return mFollow;
- }
-
- public void followLocation(boolean enable) {
- mFollow = enable;
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {}
-
- @Override
- public void onDraw(final Canvas c, final OpenStreetMapView osmv) {
- if(this.mLocation != null) {
- final OpenStreetMapViewProjection pj = osmv.getProjection();
- pj.toMapPixels(new GeoPoint(mLocation), mMapCoords);
- final float radius = pj.metersToEquatorPixels(this.mLocation.getAccuracy());
-
- this.mCirclePaint.setAlpha(50);
- this.mCirclePaint.setStyle(Style.FILL);
- c.drawCircle(mMapCoords.x, mMapCoords.y, radius, this.mCirclePaint);
-
- this.mCirclePaint.setAlpha(150);
- this.mCirclePaint.setStyle(Style.STROKE);
- c.drawCircle(mMapCoords.x, mMapCoords.y, radius, this.mCirclePaint);
-
- float[] mtx = new float[9];
- c.getMatrix().getValues(mtx);
-
- if (DEBUGMODE) {
- float tx = (-mtx[Matrix.MTRANS_X]+20)/mtx[Matrix.MSCALE_X];
- float ty = (-mtx[Matrix.MTRANS_Y]+90)/mtx[Matrix.MSCALE_Y];
- c.drawText("Lat: " + mLocation.getLatitude(), tx, ty + 5, this.mPaint);
- c.drawText("Lon: " + mLocation.getLongitude(), tx, ty + 20, this.mPaint);
- c.drawText("Alt: " + mLocation.getAltitude(), tx, ty + 35, this.mPaint);
- c.drawText("Acc: " + mLocation.getAccuracy(), tx, ty + 50, this.mPaint);
- }
-
- if (mLocation.hasSpeed() && mLocation.getSpeed() > 1) {
- /* Rotate the direction-Arrow according to the bearing we are driving. And draw it to the canvas. */
- this.directionRotater.setRotate(this.mLocation.getBearing(), DIRECTION_ARROW_CENTER_X , DIRECTION_ARROW_CENTER_Y);
- this.directionRotater.postTranslate(-DIRECTION_ARROW_CENTER_X, -DIRECTION_ARROW_CENTER_Y);
- this.directionRotater.postScale(1/mtx[Matrix.MSCALE_X], 1/mtx[Matrix.MSCALE_Y]);
- this.directionRotater.postTranslate(mMapCoords.x, mMapCoords.y);
- c.drawBitmap(DIRECTION_ARROW, this.directionRotater, this.mPaint);
- } else {
- this.directionRotater.setTranslate(-PERSON_HOTSPOT.x, -PERSON_HOTSPOT.y);
- this.directionRotater.postScale(1/mtx[Matrix.MSCALE_X], 1/mtx[Matrix.MSCALE_Y]);
- this.directionRotater.postTranslate(mMapCoords.x, mMapCoords.y);
- c.drawBitmap(PERSON_ICON, this.directionRotater, this.mPaint);
- }
- }
- }
-
- @Override
- public void onLocationChanged(final Location location) {
- if (DEBUGMODE) {
- Log.d(DEBUGTAG, "onLocationChanged(" + location + ")");
- }
-
- // ignore temporary non-gps fix
- if (mIgnorer.shouldIgnore(location.getProvider(), System.currentTimeMillis())) {
- Log.d(DEBUGTAG, "Ignore temporary non-gps location");
- return;
- }
-
- mLocation = location;
- if (mFollow) {
- mMapController.animateTo(new GeoPoint(location));
- } else {
- mMapView.invalidate(); // redraw the my location icon
- }
- }
-
- @Override
- public void onProviderDisabled(String provider) {
- }
-
- @Override
- public void onProviderEnabled(String provider) {
- }
-
- @Override
- public void onStatusChanged(String provider, int status, Bundle extras) {
- if(status == LocationProvider.AVAILABLE) {
- final Thread t = new Thread(new Runnable() {
- @Override
- public void run() {
- for(Runnable runnable: mRunOnFirstFix) {
- runnable.run();
- }
- mRunOnFirstFix.clear();
- }
- });
- t.run();
- }
- }
-
- @Override
- public boolean onSnapToItem(int x, int y, Point snapPoint, OpenStreetMapView mapView) {
- if(this.mLocation != null) {
- final OpenStreetMapViewProjection pj = mapView.getProjection();
- pj.toMapPixels(new GeoPoint(mLocation), mMapCoords);
- snapPoint.x = mMapCoords.x;
- snapPoint.y = mMapCoords.y;
-
- boolean snap = (x - mMapCoords.x)*(x - mMapCoords.x) + (y - mMapCoords.y)*(y - mMapCoords.y) < 64;
- return snap;
- } else {
- return false;
- }
- }
-
- @Override
- public boolean onTouchEvent(MotionEvent event, OpenStreetMapView mapView) {
- if (event.getAction() == MotionEvent.ACTION_MOVE)
- mFollow = false;
-
- return super.onTouchEvent(event, mapView);
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- public void disableMyLocation() {
- mLocationManager.removeUpdates(this);
- mMyLocationEnabled = false;
- }
-
- public boolean enableMyLocation() {
- if (!mMyLocationEnabled) {
- for (final String provider : mLocationManager.getAllProviders()) {
- mLocationManager.requestLocationUpdates(provider, 0, 0, this);
- }
- }
- return mMyLocationEnabled = true;
- }
-
- public boolean runOnFirstFix(Runnable runnable) {
- if(mMyLocationEnabled) {
- runnable.run();
- return true;
- } else {
- mRunOnFirstFix.addLast(runnable);
- return false;
- }
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapTilesOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapTilesOverlay.java
deleted file mode 100644
index 21baae9..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapTilesOverlay.java
+++ /dev/null
@@ -1,141 +0,0 @@
-package org.andnav.osm.views.overlay;
-
-import org.andnav.osm.tileprovider.OpenStreetMapTile;
-import org.andnav.osm.util.GeoPoint;
-import org.andnav.osm.util.MyMath;
-import org.andnav.osm.views.OpenStreetMapView;
-import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
-import org.andnav.osm.views.util.OpenStreetMapRendererInfo;
-import org.andnav.osm.views.util.OpenStreetMapTileProvider;
-
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Paint;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.os.Handler;
-import android.os.Message;
-import android.util.Log;
-
-public class OpenStreetMapTilesOverlay extends OpenStreetMapViewOverlay {
-
- protected OpenStreetMapView mOsmv;
- protected OpenStreetMapRendererInfo mRendererInfo;
-
- /** Current renderer */
- protected final OpenStreetMapTileProvider mTileProvider;
- protected final Paint mPaint = new Paint();
-
- public OpenStreetMapTilesOverlay(final OpenStreetMapView aOsmv,
- final OpenStreetMapRendererInfo aRendererInfo,
- final OpenStreetMapTileProvider aTileProvider) {
- this.mOsmv = aOsmv;
- this.mRendererInfo = aRendererInfo;
- if(aTileProvider == null)
- mTileProvider = OpenStreetMapTileProvider.getInstance(mOsmv.getContext(), new SimpleInvalidationHandler());
- else
- this.mTileProvider = aTileProvider;
- }
-
- public void detach()
- {
- this.mTileProvider.detach();
- }
-
- public OpenStreetMapRendererInfo getRendererInfo() {
- return mRendererInfo;
- }
-
- public void setRendererInfo(final OpenStreetMapRendererInfo aRendererInfo) {
- this.mRendererInfo = aRendererInfo;
- // XXX perhaps we should set the cache capacity back to default here
- }
-
- public void setAlpha(int a) {
- this.mPaint.setAlpha(a);
- }
-
- @Override
- protected void onDraw(Canvas c, OpenStreetMapView osmv) {
-
- if(DEBUGMODE)
- Log.v(DEBUGTAG, "onDraw");
-
- /*
- * Do some calculations and drag attributes to local variables to save
- * some performance.
- */
- final OpenStreetMapViewProjection pj = osmv.getProjection();
- final int zoomLevel = osmv.getZoomLevel();
- final Rect viewPort = c.getClipBounds();
- final int tileSizePx = this.mRendererInfo.MAPTILE_SIZEPX;
- final int tileZoom = this.mRendererInfo.MAPTILE_ZOOM;
- final int worldSize_2 = 1 << (zoomLevel + this.mRendererInfo.MAPTILE_ZOOM - 1);
- final int rendererId = this.mRendererInfo.ordinal(); // TODO get from service
-
- /*
- * Calculate the amount of tiles needed for each side around the center
- * one.
- */
- viewPort.offset(worldSize_2, worldSize_2);
- final int tileNeededToLeftOfCenter = (viewPort.left >> tileZoom) - 1;
- final int tileNeededToRightOfCenter = viewPort.right >> tileZoom;
- final int tileNeededToTopOfCenter = (viewPort.top >> tileZoom) - 1;
- final int tileNeededToBottomOfCenter = viewPort.bottom >> tileZoom;
-
- final int mapTileUpperBound = 1 << zoomLevel;
- final Point tilePos = new Point();
-
- // make sure the cache is big enough for all the tiles
- final int numNeeded = (tileNeededToBottomOfCenter - tileNeededToTopOfCenter + 1)
- * (tileNeededToRightOfCenter - tileNeededToLeftOfCenter + 1);
- mTileProvider.ensureCapacity(numNeeded);
-
- /* Draw all the MapTiles (from the upper left to the lower right). */
- for (int y = tileNeededToTopOfCenter; y <= tileNeededToBottomOfCenter; y++) {
- for (int x = tileNeededToLeftOfCenter; x <= tileNeededToRightOfCenter; x++) {
- /* Construct a URLString, which represents the MapTile. */
- final int tileY = MyMath.mod(y, mapTileUpperBound);
- final int tileX = MyMath.mod(x, mapTileUpperBound);
- final OpenStreetMapTile tile = new OpenStreetMapTile(rendererId, zoomLevel, tileX, tileY);
-
- pj.toPixels(x, y, tilePos);
- final Bitmap currentMapTile = mTileProvider.getMapTile(tile);
- if (currentMapTile != null) {
- c.drawBitmap(currentMapTile, tilePos.x, tilePos.y, mPaint);
- }
-
- if (DEBUGMODE) {
- c.drawText(tile.toString(), tilePos.x + 1, tilePos.y + mPaint.getTextSize(), mPaint);
- c.drawLine(tilePos.x, tilePos.y, tilePos.x + tileSizePx, tilePos.y, mPaint);
- c.drawLine(tilePos.x, tilePos.y, tilePos.x, tilePos.y + tileSizePx, mPaint);
- }
- }
- }
-
- // draw a cross at center in debug mode
- if (DEBUGMODE) {
- final GeoPoint center = osmv.getMapCenter();
- final Point centerPoint = pj.toMapPixels(center, null);
- c.drawLine(centerPoint.x, centerPoint.y - 9, centerPoint.x, centerPoint.y + 9, mPaint);
- c.drawLine(centerPoint.x - 9, centerPoint.y, centerPoint.x + 9, centerPoint.y, mPaint);
- }
-
- }
-
- @Override
- protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
- }
-
- private class SimpleInvalidationHandler extends Handler {
-
- @Override
- public void handleMessage(final Message msg) {
- switch (msg.what) {
- case OpenStreetMapTile.MAPTILE_SUCCESS_ID:
- mOsmv.invalidate();
- break;
- }
- }
- }
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewDirectedLocationOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewDirectedLocationOverlay.java
deleted file mode 100644
index d00143c..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewDirectedLocationOverlay.java
+++ /dev/null
@@ -1,101 +0,0 @@
-// Created by plusminus on 22:01:11 - 29.09.2008
-package org.andnav.osm.views.overlay;
-
-import org.andnav.osm.R;
-import org.andnav.osm.util.GeoPoint;
-import org.andnav.osm.views.OpenStreetMapView;
-import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
-
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Canvas;
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import android.graphics.Point;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class OpenStreetMapViewDirectedLocationOverlay extends OpenStreetMapViewOverlay {
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final Paint mPaint = new Paint();
-
- protected final Bitmap DIRECTION_ARROW;
-
- protected GeoPoint mLocation;
- protected float mBearing;
-
- private final Matrix directionRotater = new Matrix();
-
- private final float DIRECTION_ARROW_CENTER_X;
- private final float DIRECTION_ARROW_CENTER_Y;
- private final int DIRECTION_ARROW_WIDTH;
- private final int DIRECTION_ARROW_HEIGHT;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public OpenStreetMapViewDirectedLocationOverlay(final Context ctx){
- this.DIRECTION_ARROW = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.direction_arrow);
-
- this.DIRECTION_ARROW_CENTER_X = this.DIRECTION_ARROW.getWidth() / 2 - 0.5f;
- this.DIRECTION_ARROW_CENTER_Y = this.DIRECTION_ARROW.getHeight() / 2 - 0.5f;
- this.DIRECTION_ARROW_HEIGHT = this.DIRECTION_ARROW.getHeight();
- this.DIRECTION_ARROW_WIDTH = this.DIRECTION_ARROW.getWidth();
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public void setLocation(final GeoPoint mp){
- this.mLocation = mp;
- }
-
- public void setBearing(final float aHeading){
- this.mBearing = aHeading;
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
- return;
- }
-
- @Override
- public void onDraw(final Canvas c, final OpenStreetMapView osmv) {
- if(this.mLocation != null){
- final OpenStreetMapViewProjection pj = osmv.getProjection();
- final Point screenCoords = new Point();
- pj.toMapPixels(this.mLocation, screenCoords);
-
-
- /* Rotate the direction-Arrow according to the bearing we are driving. And draw it to the canvas. */
- this.directionRotater.setRotate(this.mBearing, DIRECTION_ARROW_CENTER_X , DIRECTION_ARROW_CENTER_Y);
- Bitmap rotatedDirection = Bitmap.createBitmap(DIRECTION_ARROW, 0, 0, DIRECTION_ARROW_WIDTH, DIRECTION_ARROW_HEIGHT, this.directionRotater, false);
- c.drawBitmap(rotatedDirection, screenCoords.x - rotatedDirection.getWidth() / 2, screenCoords.y - rotatedDirection.getHeight() / 2, this.mPaint);
- }
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlay.java
deleted file mode 100644
index 49b6d06..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlay.java
+++ /dev/null
@@ -1,158 +0,0 @@
-// Created by plusminus on 23:18:23 - 02.10.2008
-package org.andnav.osm.views.overlay;
-
-import java.util.List;
-
-import org.andnav.osm.R;
-import org.andnav.osm.views.OpenStreetMapView;
-import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
-
-import android.content.Context;
-import android.graphics.Canvas;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.graphics.drawable.Drawable;
-import android.view.MotionEvent;
-
-/**
- * Draws a list of {@link OpenStreetMapViewOverlayItem} as markers to a map.
- * The item with the lowest index is drawn as last and therefore the 'topmost' marker. It also gets checked for onTap first.
- * This class is generic, because you then you get your custom item-class passed back in onTap().
- * @author Nicolas Gramlich
- *
- * @param <T>
- */
-public class OpenStreetMapViewItemizedOverlay<T extends OpenStreetMapViewOverlayItem> extends OpenStreetMapViewOverlay {
-
- // ===========================================================
- // Constants
- // ===========================================================
-
- protected static final Point DEFAULTMARKER_HOTSPOT = new Point(13, 47);
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected OnItemTapListener<T> mOnItemTapListener;
- protected final List<T> mItemList;
- protected final Point mMarkerHotSpot;
- protected final Drawable mMarker;
- protected final int mMarkerWidth, mMarkerHeight;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public OpenStreetMapViewItemizedOverlay(final Context ctx, final List<T> aList, final OnItemTapListener<T> aOnItemTapListener) {
- this(ctx, aList, null, null, aOnItemTapListener);
- }
-
- public OpenStreetMapViewItemizedOverlay(final Context ctx, final List<T> aList, final Drawable pMarker, final Point pMarkerHotspot, final OnItemTapListener<T> aOnItemTapListener) {
- assert(ctx != null);
- assert(aList != null);
-
- this.mMarker = (pMarker != null) ? pMarker : ctx.getResources().getDrawable(R.drawable.marker_default);
-
- this.mMarkerHotSpot = (pMarkerHotspot != null) ? pMarkerHotspot : DEFAULTMARKER_HOTSPOT;
-
- this.mOnItemTapListener = aOnItemTapListener;
-
- this.mMarkerWidth = this.mMarker.getIntrinsicWidth();
- this.mMarkerHeight = this.mMarker.getIntrinsicHeight();
-
- // Add one sample item.
- this.mItemList = aList;
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
- return;
- }
-
- @Override
- public void onDraw(final Canvas c, final OpenStreetMapView mapView) {
- final OpenStreetMapViewProjection pj = mapView.getProjection();
-
- final Point curScreenCoords = new Point();
-
- /* Draw in backward cycle, so the items with the least index are on the front. */
- for(int i = this.mItemList.size() - 1; i >= 0; i--){
- T item = this.mItemList.get(i);
- pj.toMapPixels(item.mGeoPoint, curScreenCoords);
-
- onDrawItem(c, i, curScreenCoords);
- }
- }
-
- protected void onDrawItem(final Canvas c, final int index, final Point curScreenCoords) {
- final int left = curScreenCoords.x - this.mMarkerHotSpot.x;
- final int right = left + this.mMarkerWidth;
- final int top = curScreenCoords.y - this.mMarkerHotSpot.y;
- final int bottom = top + this.mMarkerHeight;
-
- this.mMarker.setBounds(left, top, right, bottom);
-
- this.mMarker.draw(c);
- }
-
- @Override
- public boolean onSingleTapUp(final MotionEvent event, final OpenStreetMapView mapView) {
- final OpenStreetMapViewProjection pj = mapView.getProjection();
- final int eventX = (int) event.getX();
- final int eventY = (int) event.getY();
- final int markerWidth = this.mMarker.getIntrinsicWidth();
- final int markerHeight = this.mMarker.getIntrinsicHeight();
-
- /* These objects are created to avoid construct new ones every cycle. */
- final Rect curMarkerBounds = new Rect();
- final Point curScreenCoords = new Point();
- final Point curScreenCoords2 = new Point();
-
- for(int i = 0; i < this.mItemList.size(); i++){
- final T item = this.mItemList.get(i);
-
- pj.toMapPixels(item.mGeoPoint, curScreenCoords);
-
- final int left = (curScreenCoords.x - this.mMarkerHotSpot.x);
- final int right = left + markerWidth;
- final int top = (curScreenCoords.y - this.mMarkerHotSpot.y);
- final int bottom = top + markerHeight;
- curMarkerBounds.set(left, top, right, bottom);
-
- pj.fromMapPixels(eventX, eventY, curScreenCoords2);
- if (curMarkerBounds.contains(curScreenCoords2.x, curScreenCoords2.y)) {
- if (onTap(i)) {
- return true;
- }
- }
- }
- return super.onSingleTapUp(event, mapView);
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- protected boolean onTap(int pIndex) {
- if(this.mOnItemTapListener != null)
- return this.mOnItemTapListener.onItemTap(pIndex, this.mItemList.get(pIndex));
- else
- return false;
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
- public static interface OnItemTapListener<T>{
- public boolean onItemTap(final int aIndex, final T aItem);
- }
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayControlView.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayControlView.java
deleted file mode 100644
index 3025cc1..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayControlView.java
+++ /dev/null
@@ -1,127 +0,0 @@
-// Created by plusminus on 22:59:38 - 12.09.2008
-package org.andnav.osm.views.overlay;
-
-import org.andnav.osm.R;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.view.View;
-import android.widget.ImageButton;
-import android.widget.LinearLayout;
-
-public class OpenStreetMapViewItemizedOverlayControlView extends LinearLayout{
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected ImageButton mPreviousButton;
- protected ImageButton mNextButton;
- protected ImageButton mCenterToButton;
- protected ImageButton mNavToButton;
-
- protected ItemizedOverlayControlViewListener mLis;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public OpenStreetMapViewItemizedOverlayControlView(Context context, AttributeSet attrs) {
- super(context, attrs);
-
- this.mPreviousButton = new ImageButton(context);
- this.mPreviousButton.setImageDrawable(context.getResources().getDrawable(R.drawable.previous));
-
- this.mNextButton = new ImageButton(context);
- this.mNextButton.setImageDrawable(context.getResources().getDrawable(R.drawable.next));
-
- this.mCenterToButton = new ImageButton(context);
- this.mCenterToButton.setImageDrawable(context.getResources().getDrawable(R.drawable.center));
-
- this.mNavToButton = new ImageButton(context);
- this.mNavToButton.setImageDrawable(context.getResources().getDrawable(R.drawable.navto_small));
-
- this.addView(mPreviousButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
- this.addView(mCenterToButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
- this.addView(mNavToButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
- this.addView(mNextButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
-
- initViewListeners();
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public void setItemizedOverlayControlViewListener(final ItemizedOverlayControlViewListener lis) {
- this.mLis = lis;
- }
-
- public void setNextEnabled(final boolean pEnabled){
- this.mNextButton.setEnabled(pEnabled);
- }
-
- public void setPreviousEnabled(final boolean pEnabled){
- this.mPreviousButton.setEnabled(pEnabled);
- }
-
- public void setNavToVisible(final int pVisibility){
- this.mNavToButton.setVisibility(pVisibility);
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- private void initViewListeners(){
- this.mNextButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- if(OpenStreetMapViewItemizedOverlayControlView.this.mLis != null)
- OpenStreetMapViewItemizedOverlayControlView.this.mLis.onNext();
- }
- });
-
- this.mPreviousButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- if(OpenStreetMapViewItemizedOverlayControlView.this.mLis != null)
- OpenStreetMapViewItemizedOverlayControlView.this.mLis.onPrevious();
- }
- });
-
- this.mCenterToButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- if(OpenStreetMapViewItemizedOverlayControlView.this.mLis != null)
- OpenStreetMapViewItemizedOverlayControlView.this.mLis.onCenter();
- }
- });
-
- this.mNavToButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- if(OpenStreetMapViewItemizedOverlayControlView.this.mLis != null)
- OpenStreetMapViewItemizedOverlayControlView.this.mLis.onNavTo();
- }
- });
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-
- public interface ItemizedOverlayControlViewListener{
- public void onPrevious();
- public void onNext();
- public void onCenter();
- public void onNavTo();
- }
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayWithFocus.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayWithFocus.java
deleted file mode 100644
index 0eb2de4..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayWithFocus.java
+++ /dev/null
@@ -1,243 +0,0 @@
-// Created by plusminus on 20:50:06 - 03.10.2008
-package org.andnav.osm.views.overlay;
-
-import java.util.List;
-
-import org.andnav.osm.R;
-import org.andnav.osm.views.OpenStreetMapView;
-
-import android.content.Context;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Paint;
-import android.graphics.Point;
-import android.graphics.RectF;
-import android.graphics.drawable.Drawable;
-
-
-public class OpenStreetMapViewItemizedOverlayWithFocus<T extends OpenStreetMapViewOverlayItem> extends OpenStreetMapViewItemizedOverlay<T> {
-
- // ===========================================================
- // Constants
- // ===========================================================
-
- public static final int DESCRIPTION_BOX_PADDING = 3;
- public static final int DESCRIPTION_BOX_CORNERWIDTH = 3;
-
- public static final int DESCRIPTION_LINE_HEIGHT = 12;
- /** Additional to <code>DESCRIPTION_LINE_HEIGHT</code>. */
- public static final int DESCRIPTION_TITLE_EXTRA_LINE_HEIGHT = 2;
-
-
- protected static final Point DEFAULTMARKER_FOCUSED_HOTSPOT = new Point(10, 19);
- protected static final int DEFAULTMARKER_BACKGROUNDCOLOR = Color.rgb(101, 185, 74);
-
- protected static final int DESCRIPTION_MAXWIDTH = 200;
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final Point mMarkerFocusedHotSpot;
- protected final Drawable mMarkerFocusedBase;
- protected final int mMarkerFocusedBackgroundColor;
- protected final int mMarkerFocusedWidth, mMarkerFocusedHeight;
- protected final Paint mMarkerBackgroundPaint, mDescriptionPaint, mTitlePaint;
-
- protected int mFocusedItemIndex;
- protected boolean mFocusItemsOnTap;
- private Point mFocusedScreenCoords = new Point();
-
- private final String UNKNOWN;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public OpenStreetMapViewItemizedOverlayWithFocus(final Context ctx, final List<T> aList, final OnItemTapListener<T> aOnItemTapListener) {
- this(ctx, aList, null, null, null, null, NOT_SET, aOnItemTapListener);
- }
-
- public OpenStreetMapViewItemizedOverlayWithFocus(final Context ctx, final List<T> aList, final Drawable pMarker, final Point pMarkerHotspot, final Drawable pMarkerFocusedBase, final Point pMarkerFocusedHotSpot, final int pFocusedBackgroundColor, final OnItemTapListener<T> aOnItemTapListener) {
- super(ctx, aList, pMarkerFocusedBase, pMarkerHotspot, aOnItemTapListener);
-
- UNKNOWN = ctx.getString(R.string.unknown);
-
- this.mMarkerFocusedBase = (pMarkerFocusedBase != null) ? pMarkerFocusedBase : ctx.getResources().getDrawable(R.drawable.marker_default_focused_base);
-
- this.mMarkerFocusedHotSpot = (pMarkerFocusedHotSpot != null) ? pMarkerFocusedHotSpot : DEFAULTMARKER_FOCUSED_HOTSPOT;
-
- if(pFocusedBackgroundColor != NOT_SET)
- this.mMarkerFocusedBackgroundColor = pFocusedBackgroundColor;
- else
- this.mMarkerFocusedBackgroundColor = DEFAULTMARKER_BACKGROUNDCOLOR;
-
- this.mMarkerBackgroundPaint = new Paint(); // Color is set in onDraw(...)
-
- this.mDescriptionPaint = new Paint();
- this.mDescriptionPaint.setAntiAlias(true);
- this.mTitlePaint = new Paint();
- this.mTitlePaint.setFakeBoldText(true);
- this.mTitlePaint.setAntiAlias(true);
-
- this.mMarkerFocusedWidth = this.mMarkerFocusedBase.getIntrinsicWidth();
- this.mMarkerFocusedHeight = this.mMarkerFocusedBase.getIntrinsicHeight();
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public void setFocusedItem(final int pIndex){
- this.mFocusedItemIndex = pIndex;
- }
-
- public void unSetFocusedItem(){
- this.mFocusedItemIndex = NOT_SET;
- }
-
- public void setFocusedItem(final T pItem){
- final int indexFound = super.mItemList.indexOf(pItem);
- if(indexFound < 0)
- throw new IllegalArgumentException();
-
- this.setFocusedItem(indexFound);
- }
-
- public void setFocusItemsOnTap(final boolean doit) {
- this.mFocusItemsOnTap = doit;
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- protected boolean onTap(int pIndex) {
- if(this.mFocusItemsOnTap)
- this.mFocusedItemIndex = pIndex;
-
- return super.onTap(pIndex);
- }
-
- @Override
- protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
- if(this.mFocusedItemIndex != NOT_SET){
- /* Calculate and set the bounds of the marker. */
- final int left = this.mFocusedScreenCoords.x - this.mMarkerFocusedHotSpot.x;
- final int right = left + this.mMarkerFocusedWidth;
- final int top = this.mFocusedScreenCoords.y - this.mMarkerFocusedHotSpot.y;
- final int bottom = top + this.mMarkerFocusedHeight;
- this.mMarkerFocusedBase.setBounds(left, top, right, bottom);
-
- /* Strings of the OverlayItem, we need. */
- final T focusedItem = super.mItemList.get(this.mFocusedItemIndex);
- final String itemTitle = (focusedItem.mTitle == null) ? UNKNOWN : focusedItem.mTitle;
- final String itemDescription = (focusedItem.mDescription == null) ? UNKNOWN : focusedItem.mDescription;
-
- /* Store the width needed for each char in the description to a float array. This is pretty efficient. */
- final float[] widths = new float[itemDescription.length()];
- this.mDescriptionPaint.getTextWidths(itemDescription, widths);
-
- final StringBuilder sb = new StringBuilder();
- int maxWidth = 0;
- int curLineWidth = 0;
- int lastStop = 0;
- int i;
- int lastwhitespace = 0;
- /* Loop through the charwidth array and harshly insert a linebreak,
- * when the width gets bigger than DESCRIPTION_MAXWIDTH. */
- for (i = 0; i < widths.length; i++) {
- if(!Character.isLetter(itemDescription.charAt(i)))
- lastwhitespace = i;
-
- float charwidth = widths[i];
-
- if(curLineWidth + charwidth> DESCRIPTION_MAXWIDTH){
- if(lastStop == lastwhitespace)
- i--;
- else
- i = lastwhitespace;
-
-
- sb.append(itemDescription.subSequence(lastStop, i));
- sb.append('\n');
-
- lastStop = i;
- maxWidth = Math.max(maxWidth, curLineWidth);
- curLineWidth = 0;
- }
-
- curLineWidth += charwidth;
- }
- /* Add the last line to the rest to the buffer. */
- if(i != lastStop){
- final String rest = itemDescription.substring(lastStop, i);
-
- maxWidth = Math.max(maxWidth, (int)this.mDescriptionPaint.measureText(rest));
-
- sb.append(rest);
- }
- final String[] lines = sb.toString().split("\n");
-
- /* The title also needs to be taken into consideration for the width calculation. */
- final int titleWidth = (int)this.mDescriptionPaint.measureText(itemTitle);
-
- maxWidth = Math.max(maxWidth, titleWidth);
- final int descWidth = Math.min(maxWidth, DESCRIPTION_MAXWIDTH);
-
- /* Calculate the bounds of the Description box that needs to be drawn. */
- final int descBoxLeft = left - descWidth / 2 - DESCRIPTION_BOX_PADDING + this.mMarkerFocusedWidth / 2;
- final int descBoxRight = descBoxLeft + descWidth + 2 * DESCRIPTION_BOX_PADDING;
- final int descBoxBottom = top;
- final int descBoxTop = descBoxBottom
- - DESCRIPTION_TITLE_EXTRA_LINE_HEIGHT
- - (lines.length + 1) * DESCRIPTION_LINE_HEIGHT /* +1 because of the title. */
- - 2 * DESCRIPTION_BOX_PADDING;
-
- /* Twice draw a RoundRect, once in black with 1px as a small border. */
- this.mMarkerBackgroundPaint.setColor(Color.BLACK);
- c.drawRoundRect(new RectF(descBoxLeft - 1, descBoxTop - 1, descBoxRight + 1, descBoxBottom + 1),
- DESCRIPTION_BOX_CORNERWIDTH, DESCRIPTION_BOX_CORNERWIDTH,
- this.mDescriptionPaint);
- this.mMarkerBackgroundPaint.setColor(this.mMarkerFocusedBackgroundColor);
- c.drawRoundRect(new RectF(descBoxLeft, descBoxTop, descBoxRight, descBoxBottom),
- DESCRIPTION_BOX_CORNERWIDTH, DESCRIPTION_BOX_CORNERWIDTH,
- this.mMarkerBackgroundPaint);
-
- final int descLeft = descBoxLeft + DESCRIPTION_BOX_PADDING;
- int descTextLineBottom = descBoxBottom - DESCRIPTION_BOX_PADDING;
-
- /* Draw all the lines of the description. */
- for(int j = lines.length - 1; j >= 0; j--){
- c.drawText(lines[j].trim(), descLeft, descTextLineBottom, this.mDescriptionPaint);
- descTextLineBottom -= DESCRIPTION_LINE_HEIGHT;
- }
- /* Draw the title. */
- c.drawText(itemTitle, descLeft, descTextLineBottom - DESCRIPTION_TITLE_EXTRA_LINE_HEIGHT, this.mTitlePaint);
- c.drawLine(descBoxLeft, descTextLineBottom, descBoxRight, descTextLineBottom, mDescriptionPaint);
-
- /* Finally draw the marker base. This is done in the end to make it look better. */
- this.mMarkerFocusedBase.draw(c);
- }
- }
-
- @Override
- protected void onDrawItem(final Canvas c, final int index, final Point screenCoords) {
- if(this.mFocusedItemIndex != NOT_SET && index == this.mFocusedItemIndex){
- /* Actual draw will take place in onDrawFinished. */
- /* Because we are reusing the screencoords apssed here, we cannot simply store the reference. */
- this.mFocusedScreenCoords.set(screenCoords.x, screenCoords.y);
- }else{
- super.onDrawItem(c, index, screenCoords);
- }
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlay.java
deleted file mode 100644
index a5830ac..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlay.java
+++ /dev/null
@@ -1,150 +0,0 @@
-// Created by plusminus on 20:32:01 - 27.09.2008
-package org.andnav.osm.views.overlay;
-
-import org.andnav.osm.views.OpenStreetMapView;
-import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
-
-import android.graphics.Canvas;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-
-/**
- * Base class representing an overlay which may be displayed on top of a
- * {@link OpenStreetMapView}. To add an overlay, subclass this class, create an
- * instance, and add it to the list obtained from getOverlays() of
- * {@link OpenStreetMapView}.
- *
- * @author Nicolas Gramlich
- */
-public abstract class OpenStreetMapViewOverlay implements OpenStreetMapViewConstants {
-
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods for SuperClass/Interfaces
- // ===========================================================
-
- /**
- * Managed Draw calls gives Overlays the possibility to first draw manually
- * and after that do a final draw. This is very useful, i sth. to be drawn
- * needs to be <b>topmost</b>.
- */
- public void onManagedDraw(final Canvas c, final OpenStreetMapView osmv) {
- onDraw(c, osmv);
- onDrawFinished(c, osmv);
- }
-
- protected abstract void onDraw(final Canvas c, final OpenStreetMapView osmv);
-
- protected abstract void onDrawFinished(final Canvas c,
- final OpenStreetMapView osmv);
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- /**
- * By default does nothing (<code>return false</code>). If you handled the
- * Event, return <code>true</code>, otherwise return <code>false</code>. If
- * you returned <code>true</code> none of the following Overlays or the
- * underlying {@link OpenStreetMapView} has the chance to handle this event.
- */
- public boolean onKeyDown(final int keyCode, KeyEvent event,
- final OpenStreetMapView mapView) {
- return false;
- }
-
- /**
- * By default does nothing (<code>return false</code>). If you handled the
- * Event, return <code>true</code>, otherwise return <code>false</code>. If
- * you returned <code>true</code> none of the following Overlays or the
- * underlying {@link OpenStreetMapView} has the chance to handle this event.
- */
- public boolean onKeyUp(final int keyCode, KeyEvent event,
- final OpenStreetMapView mapView) {
- return false;
- }
-
- /**
- * <b>You can prevent all(!) other Touch-related events from happening!</b><br />
- * By default does nothing (<code>return false</code>). If you handled the
- * Event, return <code>true</code>, otherwise return <code>false</code>. If
- * you returned <code>true</code> none of the following Overlays or the
- * underlying {@link OpenStreetMapView} has the chance to handle this event.
- */
- public boolean onTouchEvent(final MotionEvent event,
- final OpenStreetMapView mapView) {
- return false;
- }
-
- /**
- * By default does nothing (<code>return false</code>). If you handled the
- * Event, return <code>true</code>, otherwise return <code>false</code>. If
- * you returned <code>true</code> none of the following Overlays or the
- * underlying {@link OpenStreetMapView} has the chance to handle this event.
- */
- public boolean onTrackballEvent(final MotionEvent event,
- final OpenStreetMapView mapView) {
- return false;
- }
-
- /**
- * By default does nothing (<code>return false</code>). If you handled the
- * Event, return <code>true</code>, otherwise return <code>false</code>. If
- * you returned <code>true</code> none of the following Overlays or the
- * underlying {@link OpenStreetMapView} has the chance to handle this event.
- */
- public boolean onSingleTapUp(MotionEvent e,
- OpenStreetMapView openStreetMapView) {
- return false;
- }
-
- /**
- * By default does nothing (<code>return false</code>). If you handled the
- * Event, return <code>true</code>, otherwise return <code>false</code>. If
- * you returned <code>true</code> none of the following Overlays or the
- * underlying {@link OpenStreetMapView} has the chance to handle this event.
- */
- public boolean onLongPress(MotionEvent e,
- OpenStreetMapView openStreetMapView) {
- return false;
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-
- /**
- * Interface definition for overlays that contain items that can be snapped
- * to (for example, when the user invokes a zoom, this could be called
- * allowing the user to snap the zoom to an interesting point.)
- */
- public interface Snappable {
-
- /**
- * Checks to see if the given x and y are close enough to an item resulting in snapping the current action (e.g. zoom) to the item.
- * @param x The x in screen coordinates.
- * @param y The y in screen coordinates.
- * @param snapPoint To be filled with the the interesting point (in screen coordinates) that is closest to the given x and y. Can be untouched if not snapping.
- * @param mapView The OpenStreetMapView that is requesting the snap. Use MapView.getProjection() to convert between on-screen pixels and latitude/longitude pairs.
- * @return Whether or not to snap to the interesting point.
- */
- boolean onSnapToItem(int x, int y, android.graphics.Point snapPoint,
- OpenStreetMapView mapView);
- }
-
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlayItem.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlayItem.java
deleted file mode 100644
index d48d3f9..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlayItem.java
+++ /dev/null
@@ -1,54 +0,0 @@
-// Created by plusminus on 00:02:58 - 03.10.2008
-package org.andnav.osm.views.overlay;
-
-import org.andnav.osm.util.GeoPoint;
-
-/**
- * Immutable class describing a GeoPoint with a Title and a Description.
- * @author Nicolas Gramlich
- *
- */
-public class OpenStreetMapViewOverlayItem {
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- public final String mTitle;
- public final String mDescription;
- public final GeoPoint mGeoPoint;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- /**
- * @param aTitle this should be <b>singleLine</b> (no <code>'\n'</code> )
- * @param aDescription a <b>multiLine</b> description ( <code>'\n'</code> possible)
- * @param aGeoPoint
- */
- public OpenStreetMapViewOverlayItem(final String aTitle, final String aDescription, final GeoPoint aGeoPoint) {
- this.mTitle = aTitle;
- this.mDescription = aDescription;
- this.mGeoPoint = aGeoPoint;
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewPathOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewPathOverlay.java
deleted file mode 100644
index 6d045b9..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewPathOverlay.java
+++ /dev/null
@@ -1,203 +0,0 @@
-package org.andnav.osm.views.overlay;
-
-import java.util.ArrayList;
-
-import org.andnav.osm.views.OpenStreetMapView;
-import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
-import org.andnav.osm.util.GeoPoint;
-
-import android.graphics.Canvas;
-import android.graphics.Paint;
-import android.graphics.Point;
-import android.graphics.Rect;
-
-
-/**
- *
- * @author Viesturs Zarins
- *
- * This class draws a path line in given color.
- */
-public class OpenStreetMapViewPathOverlay extends OpenStreetMapViewOverlay
-{
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- /**
- * Stores points, converted to the map projection.
- */
- private ArrayList<Point> mPoints;
-
- /**
- * Number of points that have precomputed values.
- */
- private int mPointsPrecomputed;
-
- /**
- * Paint settings.
- */
- protected final Paint mPaint = new Paint();
-
-
- /**
- * Point cache for Canvas.drawLines.
- */
- static final int POINT_BUFFER_SIZE = 256; //should be a multiple of 4
- private float[] mPointBuffer = new float[POINT_BUFFER_SIZE];
-
- private final Point mTempPoint1 = new Point();
- private final Point mTempPoint2 = new Point();
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
-
- public OpenStreetMapViewPathOverlay(int color)
- {
- this.mPaint.setColor(color);
- this.mPaint.setStrokeWidth(2.0f);
-
- this.clearPath();
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public void setColor(int color)
- {
- this.mPaint.setColor(color);
- }
-
- public void setAlpha(int a)
- {
- this.mPaint.setAlpha(a);
- }
-
- public void clearPath()
- {
- this.mPoints = new ArrayList<Point>();
- this.mPointsPrecomputed = 0;
- }
-
- public void addPoint(GeoPoint pt)
- {
- this.addPoint(pt.getLatitudeE6(), pt.getLongitudeE6());
- }
-
- public void addPoint(int latitudeE6, int longitudeE6)
- {
- this.mPoints.add(new Point(latitudeE6, longitudeE6));
- }
-
- public int getNumberOfPoints() {
- return this.mPoints.size();
- }
-
-
- /**
- * This method draws the line.
- * Note - highly optimized to handle long paths, proceed with care. Should be fine up to 10K points.
- */
- @Override
- protected void onDraw(Canvas canvas, OpenStreetMapView mapView)
- {
- if (this.mPoints.size() < 2)
- {
- //nothing to paint
- return;
- }
-
- final OpenStreetMapViewProjection pj = mapView.getProjection();
-
- //precompute new points to the intermediate projection.
- int size = this.mPoints.size();
-
- while (this.mPointsPrecomputed < size)
- {
- Point pt = this.mPoints.get(this.mPointsPrecomputed);
- pj.toMapPixelsProjected(pt.x, pt.y, pt);
-
- this.mPointsPrecomputed ++;
- }
-
- Point screenPoint0 = null; //points on screen
- Point screenPoint1 = null;
- Point projectedPoint0; //points from the points list
- Point projectedPoint1;
-
- float [] buffer = this.mPointBuffer;
- int bufferCount = 0;
- Rect clipBounds = pj.fromPixelsToProjected(canvas.getClipBounds()); // clipping rectangle in the intermediate projection, to avoid performing projection.
- Rect lineBounds = new Rect(); // bounding rectangle for the current line segment.
-
- projectedPoint0 = this.mPoints.get(size - 1);
- lineBounds.set(projectedPoint0.x, projectedPoint0.y, projectedPoint0.x, projectedPoint0.y);
-
- for(int i = size - 2; i >= 0; i--)
- {
- //compute next points
- projectedPoint1 = this.mPoints.get(i);
- lineBounds.union(projectedPoint1.x, projectedPoint1.y);
-
- if (!Rect.intersects(clipBounds, lineBounds))
- {
- //skip this line, move to next point
- projectedPoint0 = projectedPoint1;
- screenPoint0 = null;
- continue;
- }
-
- // the starting point may be not calculated, because previous segment was out of clip bounds
- if (screenPoint0 == null)
- {
- screenPoint0 = pj.toMapPixelsTranslated(projectedPoint0, this.mTempPoint1);
- }
-
- screenPoint1 = pj.toMapPixelsTranslated(projectedPoint1, this.mTempPoint2);
-
- //skip this point, too close to previous point
- if (Math.abs(screenPoint1.x - screenPoint0.x) + Math.abs(screenPoint1.y - screenPoint0.y) <= 1)
- {
- continue;
- }
-
- //add new line to buffer
- buffer[bufferCount] = screenPoint0.x;
- buffer[bufferCount + 1] = screenPoint0.y;
- buffer[bufferCount + 2] = screenPoint1.x;
- buffer[bufferCount + 3] = screenPoint1.y;
- bufferCount += 4;
-
- if (bufferCount == POINT_BUFFER_SIZE)
- {
- canvas.drawLines(buffer, this.mPaint);
- bufferCount = 0;
- }
-
- //update starting point to next position
- projectedPoint0 = projectedPoint1;
- screenPoint0.x = screenPoint1.x;
- screenPoint0.y = screenPoint1.y;
- lineBounds.set(projectedPoint0.x, projectedPoint0.y, projectedPoint0.x, projectedPoint0.y);
- }
-
- if (bufferCount >0 )
- {
- canvas.drawLines(buffer, 0, bufferCount, this.mPaint);
- }
- }
-
- @Override
- protected void onDrawFinished(Canvas c, OpenStreetMapView osmv)
- {
- //nothing here
- }
-
-}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewSimpleLocationOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewSimpleLocationOverlay.java
deleted file mode 100644
index c6cfd20..0000000
--- a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewSimpleLocationOverlay.java
+++ /dev/null
@@ -1,81 +0,0 @@
-// Created by plusminus on 22:01:11 - 29.09.2008
-package org.andnav.osm.views.overlay;
-
-import org.andnav.osm.R;
-import org.andnav.osm.util.GeoPoint;
-import org.andnav.osm.views.OpenStreetMapView;
-import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
-
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Canvas;
-import android.graphics.Paint;
-import android.graphics.Point;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class OpenStreetMapViewSimpleLocationOverlay extends OpenStreetMapViewOverlay {
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected final Paint mPaint = new Paint();
-
- protected final Bitmap PERSON_ICON;
- /** Coordinates the feet of the person are located. */
- protected final android.graphics.Point PERSON_HOTSPOT = new android.graphics.Point(24,39);
-
- protected GeoPoint mLocation;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public OpenStreetMapViewSimpleLocationOverlay(final Context ctx){
- this.PERSON_ICON = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.person);
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public void setLocation(final GeoPoint mp){
- this.mLocation = mp;
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- @Override
- protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
- return;
- }
-
- @Override
- public void onDraw(final Canvas c, final OpenStreetMapView osmv) {
- if(this.mLocation != null){
- final OpenStreetMapViewProjection pj = osmv.getProjection();
- final Point screenCoords = new Point();
- pj.toMapPixels(this.mLocation, screenCoords);
-
- c.drawBitmap(PERSON_ICON, screenCoords.x - PERSON_HOTSPOT.x, screenCoords.y - PERSON_HOTSPOT.y, this.mPaint);
- }
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/LRUMapTileCache.java b/cardroid/src/org/andnav/osm/views/util/LRUMapTileCache.java
deleted file mode 100644
index bc7ea8a..0000000
--- a/cardroid/src/org/andnav/osm/views/util/LRUMapTileCache.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package org.andnav.osm.views.util;
-
-import java.util.ConcurrentModificationException;
-import java.util.LinkedHashMap;
-
-import org.andnav.osm.tileprovider.OpenStreetMapTile;
-import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
-
-import android.graphics.Bitmap;
-import android.util.Log;
-
-public class LRUMapTileCache extends LinkedHashMap<OpenStreetMapTile, Bitmap> implements OpenStreetMapViewConstants {
-
- private static final long serialVersionUID = -541142277575493335L;
-
- private int mCapacity;
-
- public LRUMapTileCache(final int aCapacity) {
- super(aCapacity + 2, 0.1f, true);
- mCapacity = aCapacity;
- }
-
- public void ensureCapacity(final int aCapacity) {
- if (aCapacity > mCapacity) {
- mCapacity = aCapacity;
- }
- }
-
- @Override
- public Bitmap remove(final Object aKey) {
- final Bitmap bm = super.remove(aKey);
- if (bm != null) {
- bm.recycle();
- }
- return bm;
- }
-
- @Override
- public void clear() {
- // remove them all individually so that they get recycled
- try {
- for (final OpenStreetMapTile key : keySet()) {
- remove(key);
- }
- } catch (final ConcurrentModificationException ignore) {
- Log.i(DEBUGTAG, "ConcurrentModificationException clearing tile cache");
- }
-
- // and then clear
- super.clear();
- }
-
- @Override
- protected boolean removeEldestEntry(final Entry<OpenStreetMapTile, Bitmap> aEldest) {
- return size() > mCapacity;
- }
-
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/Mercator.java b/cardroid/src/org/andnav/osm/views/util/Mercator.java
deleted file mode 100644
index 1ebe12f..0000000
--- a/cardroid/src/org/andnav/osm/views/util/Mercator.java
+++ /dev/null
@@ -1,134 +0,0 @@
-// Created by plusminus on 17:53:07 - 25.09.2008
-package org.andnav.osm.views.util;
-
-import org.andnav.osm.util.BoundingBoxE6;
-import org.andnav.osm.util.GeoPoint;
-import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
-
-import android.graphics.Point;
-
-/**
- * http://wiki.openstreetmap.org/index.php/Mercator
- * @author Nicolas Gramlich
- *
- */
-public class Mercator implements OpenStreetMapViewConstants {
- // ===========================================================
- // Constants
- // ===========================================================
-
- final static double DEG2RAD = Math.PI / 180;
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- /**
- * Mercator projection of GeoPoint at given zoom level
- * @param aLat latitude in degrees [-89000000 to 89000000]
- * @param aLon longitude in degrees [-180000000 to 180000000]
- * @param zoom zoom level
- * @param aUseAsReturnValue
- * @return Point with x,y in the range [-2^(zoom-1) to 2^(zoom-1)]
- */
- public static int[] projectGeoPoint(final int aLatE6, final int aLonE6, final int aZoom, final int[] reuse) {
- return projectGeoPoint(aLatE6 * 1E-6, aLonE6 * 1E-6, aZoom, reuse);
- }
-
- /**
- * Mercator projection of GeoPoint at given zoom level
- * @param aLat latitude in degrees [-89 to 89]
- * @param aLon longitude in degrees [-180 to 180]
- * @param zoom zoom level
- * @param aUseAsReturnValue
- * @return Point with x,y in the range [-2^(zoom-1) to 2^(zoom-1)]
- */
- public static int[] projectGeoPoint(final double aLat, final double aLon, final int aZoom, final int[] aUseAsReturnValue) {
- final int[] out = (aUseAsReturnValue != null) ? aUseAsReturnValue : new int[2];
-
- out[MAPTILE_LONGITUDE_INDEX] = (int) Math.floor((aLon + 180) / 360 * (1 << aZoom));
- out[MAPTILE_LATITUDE_INDEX] = (int) Math.floor((1 - Math.log(Math.tan(aLat * DEG2RAD) + 1 / Math.cos(aLat * DEG2RAD)) / Math.PI) / 2 * (1 << aZoom));
-
- return out;
- }
-
- /**
- * Mercator projection of GeoPoint at given zoom level
- * @param aGeoPoint
- * @param zoom zoom level
- * @param aUseAsReturnValue
- * @return Point with x,y in the range [-2^(zoom-1) to 2^(zoom-1)]
- */
- public static Point projectGeoPoint(final GeoPoint aGeoPoint, final int aZoom, final Point aUseAsReturnValue) {
- final Point p = (aUseAsReturnValue != null) ? aUseAsReturnValue : new Point();
-
- final double aLon = aGeoPoint.getLongitudeE6()*1E-6;
- final double aLat = aGeoPoint.getLatitudeE6()*1E-6;
- p.x = (int) Math.floor((aLon + 180) / 360 * (1 << aZoom));
- p.y = (int) Math.floor((1 - Math.log(Math.tan(aLat * DEG2RAD) + 1 / Math.cos(aLat * DEG2RAD)) / Math.PI) / 2 * (1 << aZoom));
-
- return p;
- }
-
- /**
- * Get bounding box from reverse Mercator projection.
- * @param left
- * @param top
- * @param right
- * @param bottom
- * @param zoom
- * @return
- */
- public static BoundingBoxE6 getBoundingBoxFromCoords(final int left, final int top, final int right, final int bottom, final int zoom) {
- return new BoundingBoxE6(tile2lat(top, zoom), tile2lon(right, zoom), tile2lat(bottom, zoom), tile2lon(left, zoom));
- }
-
- /**
- * Get bounding box from reverse Mercator projection.
- * @param aMapTile
- * @param aZoom
- * @return
- */
- public static BoundingBoxE6 getBoundingBoxFromMapTile(final int[] aMapTile, final int aZoom) {
- final int y = aMapTile[MAPTILE_LATITUDE_INDEX];
- final int x = aMapTile[MAPTILE_LONGITUDE_INDEX];
- return new BoundingBoxE6(tile2lat(y, aZoom), tile2lon(x + 1, aZoom), tile2lat(y + 1, aZoom), tile2lon(x, aZoom));
- }
-
- /**
- * Reverse Mercator projection of Point at given zoom level
- *
- */
- public static GeoPoint projectPoint(int x, int y, int aZoom) {
- return new GeoPoint((int)(tile2lat(y, aZoom)*1E6), (int)(tile2lon(x, aZoom)*1E6));
- }
-
- public static double tile2lon(int x, int aZoom) {
- return ((double)x / (1 << aZoom) * 360.0) - 180;
- }
-
- public static double tile2lat(int y, int aZoom) {
- final double n = Math.PI - ((2.0 * Math.PI * y) / (1 << aZoom));
- return 180.0 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/MyMath.java b/cardroid/src/org/andnav/osm/views/util/MyMath.java
deleted file mode 100644
index 408bf9b..0000000
--- a/cardroid/src/org/andnav/osm/views/util/MyMath.java
+++ /dev/null
@@ -1,70 +0,0 @@
-// Created by plusminus on 20:36:01 - 26.09.2008
-package org.andnav.osm.views.util;
-
-import org.andnav.osm.views.util.constants.MathConstants;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class MyMath implements MathConstants {
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- /**
- * Calculates i.e. the increase of zoomlevel needed when the visible latitude needs to be bigger by <code>factor</code>.
- *
- * Assert.assertEquals(1, getNextSquareNumberAbove(1.1f));
- * Assert.assertEquals(2, getNextSquareNumberAbove(2.1f));
- * Assert.assertEquals(2, getNextSquareNumberAbove(3.9f));
- * Assert.assertEquals(3, getNextSquareNumberAbove(4.1f));
- * Assert.assertEquals(3, getNextSquareNumberAbove(7.9f));
- * Assert.assertEquals(4, getNextSquareNumberAbove(8.1f));
- * Assert.assertEquals(5, getNextSquareNumberAbove(16.1f));
- *
- * Assert.assertEquals(-1, - getNextSquareNumberAbove(1 / 0.4f) + 1);
- * Assert.assertEquals(-2, - getNextSquareNumberAbove(1 / 0.24f) + 1);
- *
- * @param factor
- * @return
- */
- public static int getNextSquareNumberAbove(final float factor){
- int out = 0;
- int cur = 1;
- int i = 1;
- while(true){
- if(cur > factor)
- return out;
-
- out = i;
- cur *= 2;
- i++;
- }
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapRendererInfo.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapRendererInfo.java
deleted file mode 100644
index bec8c98..0000000
--- a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapRendererInfo.java
+++ /dev/null
@@ -1,96 +0,0 @@
-// Created by plusminus on 18:23:16 - 25.09.2008
-package org.andnav.osm.views.util;
-
-import java.util.Random;
-
-import org.andnav.osm.R;
-import org.andnav.osm.tileprovider.OpenStreetMapTile;
-
-/**
- * The OpenStreetMapRendererInfo stores information about available tile servers.
- * @author Nicolas Gramlich
- *
- */
-public enum OpenStreetMapRendererInfo {
- OSMARENDER(R.string.osmarender, ".png", 0, 17, 8, CodeScheme.X_Y,"http://tah.openstreetmap.org/Tiles/tile/"),
- MAPNIK(R.string.mapnik, ".png", 0, 18, 8, CodeScheme.X_Y,"http://tile.openstreetmap.org/"),
- CYCLEMAP(R.string.cyclemap, ".png", 0, 17, 8, CodeScheme.X_Y,
- "http://a.andy.sandbox.cloudmade.com/tiles/cycle/",
- "http://b.andy.sandbox.cloudmade.com/tiles/cycle/",
- "http://c.andy.sandbox.cloudmade.com/tiles/cycle/"),
- OPENARIELMAP( R.string.openareal_sat, ".jpg", 0, 13, 8, CodeScheme.X_Y,"http://tile.openaerialmap.org/tiles/1.0.0/openaerialmap-900913/"),
- BASE( R.string.base, ".png", 4, 17, 8, CodeScheme.X_Y,"http://topo.openstreetmap.de/base/"),
- TOPO(R.string.topo, ".png", 4, 17, 8, CodeScheme.X_Y,"http://topo.openstreetmap.de/topo/"),
- HILLS(R.string.hills, ".png", 8, 17, 8, CodeScheme.X_Y,"http://topo.geofabrik.de/hills/"),
- CLOUDMADESMALLTILES(R.string.cloudmade_small, ".png", 0, 13, 6, CodeScheme.X_Y,"http://tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/2/64/"),
- CLOUDMADESTANDARDTILES(R.string.cloudmade_standard, ".png", 0, 18, 8, CodeScheme.X_Y,"http://tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/2/256/");
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- public enum CodeScheme { X_Y, QUAD_TREE };
-
- public final String BASEURLS[], IMAGE_FILENAMEENDING;
- public final int NAME, ZOOM_MINLEVEL, ZOOM_MAXLEVEL, MAPTILE_ZOOM, MAPTILE_SIZEPX;
- public final CodeScheme CODE_SCHEME;
- private final Random random;
- // ===========================================================
- // Constructors
- // ===========================================================
-
- private OpenStreetMapRendererInfo(final int aName,
- final String aImageFilenameEnding, final int aZoomMin,
- final int aZoomMax, final int aTileZoom, final CodeScheme aCodeScheme,final String ...aBaseUrl) {
- this.BASEURLS = aBaseUrl;
- this.NAME = aName;
- this.ZOOM_MINLEVEL = aZoomMin;
- this.ZOOM_MAXLEVEL = aZoomMax;
- this.IMAGE_FILENAMEENDING = aImageFilenameEnding;
- this.MAPTILE_ZOOM = aTileZoom;
- this.MAPTILE_SIZEPX = 1<<aTileZoom;
- this.CODE_SCHEME = aCodeScheme;
- this.random = new Random();
- }
-
- public static OpenStreetMapRendererInfo getDefault() {
- return MAPNIK;
- }
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- public String getTileURLString(final OpenStreetMapTile aTile) {
- final CodeScheme cs = this.CODE_SCHEME;
- final String baseurl = BASEURLS[random.nextInt()%BASEURLS.length];
- switch (cs) {
- case QUAD_TREE:
- return String.format("%s%s%s", baseurl, quadTree(aTile), this.IMAGE_FILENAMEENDING);
- case X_Y:
- default:
- return String.format("%s%d/%d/%d%s", baseurl, aTile.getZoomLevel(), aTile.getX(), aTile.getY(), this.IMAGE_FILENAMEENDING);
- }
- }
-
- /**
- * Converts TMS tile coordinates to QuadTree
- * @param aTile The tile coordinates to convert
- * @return The QuadTree as String.
- */
- private String quadTree(final OpenStreetMapTile aTile) {
- final StringBuilder quadKey = new StringBuilder();
- for (int i = aTile.getZoomLevel(); i > 0; i--) {
- int digit = 0;
- int mask = 1 << (i - 1);
- if ((aTile.getX() & mask) != 0)
- digit += 1;
- if ((aTile.getY() & mask) != 0)
- digit += 2;
- quadKey.append("" + digit);
- }
-
- return quadKey.toString();
- }
-
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java
deleted file mode 100644
index 7c426e4..0000000
--- a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java
+++ /dev/null
@@ -1,77 +0,0 @@
-// Created by plusminus on 17:58:57 - 25.09.2008
-package org.andnav.osm.views.util;
-
-import org.andnav.osm.tileprovider.OpenStreetMapTile;
-import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
-
-import android.graphics.Bitmap;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public class OpenStreetMapTileCache implements OpenStreetMapViewConstants {
- // ===========================================================
- // Constants
- // ===========================================================
-
- // ===========================================================
- // Fields
- // ===========================================================
-
- protected LRUMapTileCache mCachedTiles;
-
- // ===========================================================
- // Constructors
- // ===========================================================
-
- public OpenStreetMapTileCache() {
- this(CACHE_MAPTILECOUNT_DEFAULT);
- }
-
- /**
- * @param aMaximumCacheSize Maximum amount of MapTiles to be hold within.
- */
- public OpenStreetMapTileCache(final int aMaximumCacheSize){
- this.mCachedTiles = new LRUMapTileCache(aMaximumCacheSize);
- }
-
- // ===========================================================
- // Getter & Setter
- // ===========================================================
-
- public void ensureCapacity(final int aCapacity) {
- mCachedTiles.ensureCapacity(aCapacity);
- }
-
- public synchronized Bitmap getMapTile(final OpenStreetMapTile aTile) {
- return this.mCachedTiles.get(aTile);
- }
-
- public synchronized void putTile(final OpenStreetMapTile aTile, final Bitmap aImage) {
- if (aImage != null) {
- this.mCachedTiles.put(aTile, aImage);
- }
- }
-
- // ===========================================================
- // Methods from SuperClass/Interfaces
- // ===========================================================
-
- // ===========================================================
- // Methods
- // ===========================================================
-
- public boolean containsTile(final OpenStreetMapTile aTile) {
- return this.mCachedTiles.containsKey(aTile);
- }
-
- public void clear() {
- this.mCachedTiles.clear();
- }
-
- // ===========================================================
- // Inner and Anonymous Classes
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java
deleted file mode 100644
index 498af84..0000000
--- a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java
+++ /dev/null
@@ -1,95 +0,0 @@
-// Created by plusminus on 21:46:22 - 25.09.2008
-package org.andnav.osm.views.util;
-
-import java.io.File;
-
-import org.andnav.osm.services.IOpenStreetMapTileProviderService;
-import org.andnav.osm.tileprovider.OpenStreetMapTile;
-import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
-
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.ResolveInfo;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.os.Handler;
-import android.util.Log;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public abstract class OpenStreetMapTileProvider implements OpenStreetMapViewConstants {
-
- protected final OpenStreetMapTileCache mTileCache;
- protected final Handler mDownloadFinishedHandler;
-
- public OpenStreetMapTileProvider(final Handler pDownloadFinishedListener) {
- mTileCache = new OpenStreetMapTileCache();
- mDownloadFinishedHandler = pDownloadFinishedListener;
- }
-
- /**
- * Get a tile provider.
- * If a tile provider service exists then it will use the service,
- * otherwise it'll use a direct tile provider that doesn't use a service
- * @param pContext
- * @param pDownloadFinishedListener
- * @return
- */
- public static OpenStreetMapTileProvider getInstance(final Context pContext,
- final Handler pDownloadFinishedListener) {
- final Intent intent = new Intent(IOpenStreetMapTileProviderService.class.getName());
- final ResolveInfo ri = pContext.getPackageManager().resolveService(intent, 0);
- if (ri == null) {
- Log.i(DEBUGTAG, "Service not found - using direct tile provider");
- return new OpenStreetMapTileProviderDirect(pDownloadFinishedListener);
- } else {
- Log.i(DEBUGTAG, "Using tile provider service");
- return new OpenStreetMapTileProviderService(pContext, pDownloadFinishedListener);
- // XXX Perhaps we should pass the Intent or the class name (action) into
- // this constructor since we do the same again in there.
- // That will also give the option of specifying something else.
- }
- }
-
- public void mapTileRequestCompleted(final OpenStreetMapTile pTile, final String pTilePath) {
-
- // if the tile path has been returned, add the tile to the cache
- if (pTilePath != null) {
- try {
- final Bitmap bitmap = BitmapFactory.decodeFile(pTilePath);
- if (bitmap != null) {
- mTileCache.putTile(pTile, bitmap);
- } else {
- // if we couldn't load it then it's invalid - delete it
- try {
- new File(pTilePath).delete();
- } catch (Throwable e) {
- Log.e(DEBUGTAG, "Error deleting invalid file: " + pTilePath, e);
- }
- }
- } catch (final OutOfMemoryError e) {
- Log.e(DEBUGTAG, "OutOfMemoryError putting tile in cache: " + pTile);
- mTileCache.clear();
- System.gc();
- }
- }
-
- // tell our caller we've finished and it should update its view
- mDownloadFinishedHandler.sendEmptyMessage(OpenStreetMapTile.MAPTILE_SUCCESS_ID);
-
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "MapTile request complete: " + pTile);
- }
-
- public void ensureCapacity(final int aCapacity) {
- mTileCache.ensureCapacity(aCapacity);
- }
-
- public abstract Bitmap getMapTile(OpenStreetMapTile pTile);
-
- public abstract void detach();
-
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderDirect.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderDirect.java
deleted file mode 100644
index 53a7e42..0000000
--- a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderDirect.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package org.andnav.osm.views.util;
-
-import org.andnav.osm.tileprovider.IOpenStreetMapTileProviderCallback;
-import org.andnav.osm.tileprovider.OpenStreetMapTile;
-import org.andnav.osm.tileprovider.OpenStreetMapTileFilesystemProvider;
-
-import android.graphics.Bitmap;
-import android.os.Handler;
-import android.util.Log;
-
-public class OpenStreetMapTileProviderDirect extends OpenStreetMapTileProvider implements IOpenStreetMapTileProviderCallback {
-
- private final OpenStreetMapTileFilesystemProvider mFileSystemProvider;
-
- public OpenStreetMapTileProviderDirect(final Handler pDownloadFinishedListener) {
- super(pDownloadFinishedListener);
- mFileSystemProvider = new OpenStreetMapTileFilesystemProvider(this);
- }
-
- @Override
- public void detach() {
- }
-
- @Override
- public Bitmap getMapTile(final OpenStreetMapTile pTile) {
- if (mTileCache.containsTile(pTile)) {
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "MapTileCache succeeded for: " + pTile);
- return mTileCache.getMapTile(pTile);
- } else {
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "Cache failed, trying from FS: " + pTile);
- mFileSystemProvider.loadMapTileAsync(pTile);
- return null;
- }
- }
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderService.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderService.java
deleted file mode 100644
index 9f318e3..0000000
--- a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderService.java
+++ /dev/null
@@ -1,143 +0,0 @@
-package org.andnav.osm.views.util;
-
-import org.andnav.osm.services.IOpenStreetMapTileProviderService;
-import org.andnav.osm.services.IOpenStreetMapTileProviderServiceCallback;
-import org.andnav.osm.tileprovider.OpenStreetMapTile;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.graphics.Bitmap;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.util.Log;
-
-public class OpenStreetMapTileProviderService extends OpenStreetMapTileProvider implements ServiceConnection {
-
- private final Context mContext;
-
- private IOpenStreetMapTileProviderService mTileService;
-
- /**
- * Service is bound, but maybe not still connected.
- */
- private boolean mServiceBound;
-
- public OpenStreetMapTileProviderService(final Context pContext, final Handler pDownloadFinishedListener) {
- super(pDownloadFinishedListener);
- mContext = pContext;
- bindToService();
- }
-
- public void onServiceConnected(final ComponentName name, final IBinder service) {
- Log.d(DEBUGTAG, "onServiceConnected(" + name + ")");
-
- mTileService = IOpenStreetMapTileProviderService.Stub.asInterface(service);
-
- try {
- mTileService.setCallback(mServiceCallback);
- } catch (RemoteException e) {
- Log.e(DEBUGTAG, "Error setting callback", e);
- }
-
- try {
- mDownloadFinishedHandler.sendEmptyMessage(OpenStreetMapTile.MAPTILE_SUCCESS_ID);
- } catch(Exception e) {
- Log.e(DEBUGTAG, "Error sending success message on connect", e);
- }
- };
-
- @Override
- public void onServiceDisconnected(final ComponentName name) {
- onDisconnect();
- Log.d(DEBUGTAG, "disconnected");
- }
-
- /**
- * Get the tile from the cache.
- * If it's in the cache then it will be returned.
- * If not it will return null and request it from the service.
- * In turn, the service will request it from the file system.
- * If it's found in the file system it will notify the callback.
- * If not it will initiate a download.
- * When the download has finished it will notify the callback.
- * @param aTile the tile being requested
- * @return the tile bitmap if found in the cache, null otherwise
- */
- @Override
- public Bitmap getMapTile(final OpenStreetMapTile aTile) {
- if (mTileCache.containsTile(aTile)) { // from cache
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "MapTileCache succeeded for: " + aTile);
- return mTileCache.getMapTile(aTile);
- } else { // from service
- if (mTileService != null) {
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "Cache failed, trying from FS: " + aTile);
- try {
- mTileService.requestMapTile(aTile.getRendererId(), aTile.getZoomLevel(), aTile.getX(), aTile.getY());
- } catch (Throwable e) {
- Log.e(DEBUGTAG, "Error getting map tile from tile service: " + aTile, e);
- }
- } else {
- // try to reconnect, but the connection will take time.
- if (!bindToService()) {
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "Cache failed, can't get from FS because no tile service: " + aTile);
- } else {
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "Cache failed, tile service still not woken up: " + aTile);
- }
- }
-
- return null;
- }
- }
-
- /***
- * Disconnects from the tile downloader service.
- */
- @Override
- public void detach()
- {
- if (mServiceBound)
- {
- if (DEBUGMODE)
- Log.d(DEBUGTAG, "Unbinding service");
- mContext.unbindService(this);
- onDisconnect();
- }
- }
-
- private boolean bindToService()
- {
- if (mServiceBound)
- return true;
-
- boolean success = mContext.bindService(new Intent(IOpenStreetMapTileProviderService.class.getName()), this, Context.BIND_AUTO_CREATE);
-
- if (!success)
- Log.e(DEBUGTAG, "Could not bind to " + IOpenStreetMapTileProviderService.class.getName());
-
- mServiceBound = success;
-
- return success;
- }
-
- private void onDisconnect()
- {
- mServiceBound = false;
- mTileService = null;
- }
-
- IOpenStreetMapTileProviderServiceCallback mServiceCallback = new IOpenStreetMapTileProviderServiceCallback.Stub() {
- @Override
- public void mapTileRequestCompleted(final int aRendererID, final int aZoomLevel, final int aTileX, final int aTileY, final String aTilePath) throws RemoteException {
- final OpenStreetMapTile tile = new OpenStreetMapTile(aRendererID, aZoomLevel, aTileX, aTileY);
- OpenStreetMapTileProviderService.this.mapTileRequestCompleted(tile, aTilePath);
- }
- };
-
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/constants/MathConstants.java b/cardroid/src/org/andnav/osm/views/util/constants/MathConstants.java
deleted file mode 100644
index 8e235d5..0000000
--- a/cardroid/src/org/andnav/osm/views/util/constants/MathConstants.java
+++ /dev/null
@@ -1,24 +0,0 @@
-// Created by plusminus on 17:27:54 - 30.09.2008
-package org.andnav.osm.views.util.constants;
-
-/**
- *
- * @author Nicolas Gramlich
- *
- */
-public interface MathConstants {
- // ===========================================================
- // Final Fields
- // ===========================================================
-
- public static final float DEG2RAD = (float)(Math.PI / 180.0);
- public static final float RAD2DEG = (float)(180.0 / Math.PI);
-
- public static final float PI = (float)Math.PI;
- public static final float PI_2 = PI / 2.0f;
- public static final float PI_4 = PI / 4.0f;
-
- // ===========================================================
- // Methods
- // ===========================================================
-}
diff --git a/cardroid/src/org/andnav/osm/views/util/constants/OpenStreetMapViewConstants.java b/cardroid/src/org/andnav/osm/views/util/constants/OpenStreetMapViewConstants.java
deleted file mode 100644
index ce3aeea..0000000
--- a/cardroid/src/org/andnav/osm/views/util/constants/OpenStreetMapViewConstants.java
+++ /dev/null
@@ -1,30 +0,0 @@
-// Created by plusminus on 18:00:24 - 25.09.2008
-package org.andnav.osm.views.util.constants;
-
-/**
- *
- * This class contains constants used by the map view.
- *
- * @author Nicolas Gramlich
- *
- */
-public interface OpenStreetMapViewConstants {
- // ===========================================================
- // Final Fields
- // ===========================================================
-
- public static final boolean DEBUGMODE = false;
-
- public static final String DEBUGTAG = "OPENSTREETMAP_VIEW";
-
- public static final int NOT_SET = Integer.MIN_VALUE;
-
- public static final int CACHE_MAPTILECOUNT_DEFAULT = 40;
-
- public static final int MAPTILE_LATITUDE_INDEX = 0;
- public static final int MAPTILE_LONGITUDE_INDEX = 1;
-
- // ===========================================================
- // Methods
- // ===========================================================
-}
|
cstim/carcomm
|
4f2c9d1b6be717b4c1c62cb7d9a06c162fc04e04
|
Minor cosmetic improvements
|
diff --git a/cardroid/cmdline.txt b/cardroid/cmdline.txt
index 23b858f..933936d 100644
--- a/cardroid/cmdline.txt
+++ b/cardroid/cmdline.txt
@@ -1,38 +1,41 @@
## To have SUN java in path:
#export PATH=/usr/lib/jvm/java-6-sun-1.6.0.15/jre/bin:$PATH
# Creating the project:
ANDROIDROOT=$HOME/android-sdk-linux_86
cd $ANDROIDROOT/tools
./android list targets
./android create project \
--target android-3 \
--name carinfo \
--path /home/chs/carinfo \
--activity CarinfoActivity \
--package de.cstimming.carinfo
PROJDIR=$HOME/carinfo
cd $PROJDIR
# Building in debug mode
ant debug
# Starting an emulator
cd $ANDROIDROOT/tools
./android list avds
# I have one Android Virtual Device (AVD) named "test1"; start this
# AVD:
./emulator -avd test1
# Install the application on the currently running emulator
./adb install $PROJDIR/bin/carinfo-debug.apk
# Building my application and installing it to the currently running
# emulator in one step
cd $PROJDIR
ant install
# Compile with the java libraries
CLASSPATH=lib/httpmime-4.0-beta1.jar:lib/apache-mime4j-0.4.jar ant debug
+
+# Uninstall
+adb uninstall de.cstimming.carinfo
diff --git a/cardroid/res/values-de/strings.xml b/cardroid/res/values-de/strings.xml
index 6c12bf2..b1e5fe5 100644
--- a/cardroid/res/values-de/strings.xml
+++ b/cardroid/res/values-de/strings.xml
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
- <string name="app_name">Meine CarinfoActivity</string>
+ <string name="app_name">CarDroid Prototyp</string>
<string name="hello">Hallo Welt, CarinfoActivity</string>
<string name="map_mode">Kartenmodus</string>
<string name="my_location">Standort</string>
<string name="about">Ãber</string>
<string name="about_message">Diese Software benutzt Kartenmaterial von OpenStreetMap.org</string></resources>
diff --git a/cardroid/res/values/strings.xml b/cardroid/res/values/strings.xml
index ec1b000..802bdc6 100644
--- a/cardroid/res/values/strings.xml
+++ b/cardroid/res/values/strings.xml
@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
- <string name="app_name">My CarinfoActivity</string>
+ <string name="app_name">CarDroid Prototype</string>
<string name="hello">Hello World, CarinfoActivity</string>
<string name="app_name_itemizedoverlay">OSMViewer ItemizedOverlay</string>
<string name="unknown">Unknown</string>
<string name="map_mode">Map mode</string>
<string name="my_location">My location</string>
<string name="samples">Samples</string>
<string name="about">About</string>
<string name="about_message">This software uses map data provided by <b>OpenStreetMap.org</b></string>
</resources>
|
cstim/carcomm
|
f4ceffd2da58e473abda4d3f4c291a12f1886454
|
Copy the osmdroid code to here and get it to compile.
|
diff --git a/cardroid/.gitignore b/cardroid/.gitignore
index 07eee84..479c192 100644
--- a/cardroid/.gitignore
+++ b/cardroid/.gitignore
@@ -1,3 +1,4 @@
bin
build.xml
-local.properties
\ No newline at end of file
+local.properties
+gen
diff --git a/cardroid/AndroidManifest.xml b/cardroid/AndroidManifest.xml
index 314b76e..b53ec2a 100644
--- a/cardroid/AndroidManifest.xml
+++ b/cardroid/AndroidManifest.xml
@@ -1,15 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.cstimming.carinfo"
android:versionCode="1"
android:versionName="1.0">
+
+ <uses-sdk android:minSdkVersion="4" />
+
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
<application android:label="@string/app_name">
<activity android:name=".CarinfoActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
+
+ <!--
+ If this service exists then the view will use it to get its tiles.
+ If you remove this service then the view will use a tile provider directly.
+ -->
+ <service android:name=".services.OpenStreetMapTileProviderService"
+ android:process=":remote"
+ android:label="OpenStreetMapTileProviderService">
+ <intent-filter>
+ <action android:name="org.andnav.osm.services.IOpenStreetMapTileProviderService" />
+ </intent-filter>
+ </service>
+
</application>
</manifest>
diff --git a/cardroid/cmdline.txt b/cardroid/cmdline.txt
index 7c6447e..23b858f 100644
--- a/cardroid/cmdline.txt
+++ b/cardroid/cmdline.txt
@@ -1,34 +1,38 @@
## To have SUN java in path:
#export PATH=/usr/lib/jvm/java-6-sun-1.6.0.15/jre/bin:$PATH
# Creating the project:
ANDROIDROOT=$HOME/android-sdk-linux_86
cd $ANDROIDROOT/tools
./android list targets
./android create project \
--target android-3 \
--name carinfo \
--path /home/chs/carinfo \
--activity CarinfoActivity \
--package de.cstimming.carinfo
PROJDIR=$HOME/carinfo
cd $PROJDIR
# Building in debug mode
ant debug
# Starting an emulator
cd $ANDROIDROOT/tools
./android list avds
# I have one Android Virtual Device (AVD) named "test1"; start this
# AVD:
./emulator -avd test1
# Install the application on the currently running emulator
./adb install $PROJDIR/bin/carinfo-debug.apk
# Building my application and installing it to the currently running
# emulator in one step
cd $PROJDIR
ant install
+
+
+# Compile with the java libraries
+CLASSPATH=lib/httpmime-4.0-beta1.jar:lib/apache-mime4j-0.4.jar ant debug
diff --git a/cardroid/default.properties b/cardroid/default.properties
index 4513a1e..9d79b12 100644
--- a/cardroid/default.properties
+++ b/cardroid/default.properties
@@ -1,11 +1,11 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
-target=android-3
+target=android-4
diff --git a/cardroid/gen/de/cstimming/carinfo/R.java b/cardroid/gen/de/cstimming/carinfo/R.java
index 326ae46..0fb7d2b 100644
--- a/cardroid/gen/de/cstimming/carinfo/R.java
+++ b/cardroid/gen/de/cstimming/carinfo/R.java
@@ -1,20 +1,49 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package de.cstimming.carinfo;
public final class R {
public static final class attr {
}
+ public static final class drawable {
+ public static final int center=0x7f020000;
+ public static final int direction_arrow=0x7f020001;
+ public static final int icon=0x7f020002;
+ public static final int marker_default=0x7f020003;
+ public static final int marker_default_focused_base=0x7f020004;
+ public static final int navto_small=0x7f020005;
+ public static final int next=0x7f020006;
+ public static final int person=0x7f020007;
+ public static final int previous=0x7f020008;
+ public static final int zoom_in=0x7f020009;
+ public static final int zoom_out=0x7f02000a;
+ }
public static final class layout {
- public static final int main=0x7f020000;
+ public static final int main=0x7f030000;
}
public static final class string {
- public static final int app_name=0x7f030000;
- public static final int hello=0x7f030001;
+ public static final int about=0x7f040010;
+ public static final int about_message=0x7f040011;
+ public static final int app_name=0x7f040009;
+ public static final int app_name_itemizedoverlay=0x7f04000b;
+ public static final int base=0x7f040004;
+ public static final int cloudmade_small=0x7f040007;
+ public static final int cloudmade_standard=0x7f040008;
+ public static final int cyclemap=0x7f040002;
+ public static final int hello=0x7f04000a;
+ public static final int hills=0x7f040006;
+ public static final int map_mode=0x7f04000d;
+ public static final int mapnik=0x7f040001;
+ public static final int my_location=0x7f04000e;
+ public static final int openareal_sat=0x7f040003;
+ public static final int osmarender=0x7f040000;
+ public static final int samples=0x7f04000f;
+ public static final int topo=0x7f040005;
+ public static final int unknown=0x7f04000c;
}
}
diff --git a/cardroid/lib/apache-mime4j-0.4.jar b/cardroid/lib/apache-mime4j-0.4.jar
new file mode 100644
index 0000000..b5fe9bf
Binary files /dev/null and b/cardroid/lib/apache-mime4j-0.4.jar differ
diff --git a/cardroid/lib/httpmime-4.0-beta1.jar b/cardroid/lib/httpmime-4.0-beta1.jar
new file mode 100644
index 0000000..2564dcf
Binary files /dev/null and b/cardroid/lib/httpmime-4.0-beta1.jar differ
diff --git a/cardroid/res/drawable/center.png b/cardroid/res/drawable/center.png
new file mode 100644
index 0000000..025bdad
Binary files /dev/null and b/cardroid/res/drawable/center.png differ
diff --git a/cardroid/res/drawable/direction_arrow.png b/cardroid/res/drawable/direction_arrow.png
new file mode 100644
index 0000000..e69291f
Binary files /dev/null and b/cardroid/res/drawable/direction_arrow.png differ
diff --git a/cardroid/res/drawable/icon.png b/cardroid/res/drawable/icon.png
new file mode 100644
index 0000000..b74f1ea
Binary files /dev/null and b/cardroid/res/drawable/icon.png differ
diff --git a/cardroid/res/drawable/marker_default.png b/cardroid/res/drawable/marker_default.png
new file mode 100644
index 0000000..e161c69
Binary files /dev/null and b/cardroid/res/drawable/marker_default.png differ
diff --git a/cardroid/res/drawable/marker_default_focused_base.png b/cardroid/res/drawable/marker_default_focused_base.png
new file mode 100644
index 0000000..e9d775d
Binary files /dev/null and b/cardroid/res/drawable/marker_default_focused_base.png differ
diff --git a/cardroid/res/drawable/navto_small.png b/cardroid/res/drawable/navto_small.png
new file mode 100644
index 0000000..76518bf
Binary files /dev/null and b/cardroid/res/drawable/navto_small.png differ
diff --git a/cardroid/res/drawable/next.png b/cardroid/res/drawable/next.png
new file mode 100644
index 0000000..30560f2
Binary files /dev/null and b/cardroid/res/drawable/next.png differ
diff --git a/cardroid/res/drawable/person.png b/cardroid/res/drawable/person.png
new file mode 100644
index 0000000..9f9db93
Binary files /dev/null and b/cardroid/res/drawable/person.png differ
diff --git a/cardroid/res/drawable/previous.png b/cardroid/res/drawable/previous.png
new file mode 100644
index 0000000..0fdbc52
Binary files /dev/null and b/cardroid/res/drawable/previous.png differ
diff --git a/cardroid/res/drawable/zoom_in.png b/cardroid/res/drawable/zoom_in.png
new file mode 100644
index 0000000..36845e7
Binary files /dev/null and b/cardroid/res/drawable/zoom_in.png differ
diff --git a/cardroid/res/drawable/zoom_out.png b/cardroid/res/drawable/zoom_out.png
new file mode 100644
index 0000000..e327d96
Binary files /dev/null and b/cardroid/res/drawable/zoom_out.png differ
diff --git a/cardroid/res/values-de/renderers.xml b/cardroid/res/values-de/renderers.xml
new file mode 100644
index 0000000..2208825
--- /dev/null
+++ b/cardroid/res/values-de/renderers.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+<string name="base">OSM Basislayer</string>
+<string name="topo">Topographisch</string><string name="hills">Relief</string><string name="cyclemap">Fahrradkarte</string>
+
+
+
+</resources>
diff --git a/cardroid/res/values-de/strings.xml b/cardroid/res/values-de/strings.xml
index 7ae9de7..6c12bf2 100644
--- a/cardroid/res/values-de/strings.xml
+++ b/cardroid/res/values-de/strings.xml
@@ -1,5 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Meine CarinfoActivity</string>
<string name="hello">Hallo Welt, CarinfoActivity</string>
-</resources>
+
+<string name="map_mode">Kartenmodus</string>
+<string name="my_location">Standort</string>
+<string name="about">Ãber</string>
+<string name="about_message">Diese Software benutzt Kartenmaterial von OpenStreetMap.org</string></resources>
diff --git a/cardroid/res/values/renderers.xml b/cardroid/res/values/renderers.xml
new file mode 100644
index 0000000..cab3c47
--- /dev/null
+++ b/cardroid/res/values/renderers.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="osmarender">OsmaRender</string>
+ <string name="mapnik">Mapnik</string>
+ <string name="cyclemap">Cycle Map</string>
+ <string name="openareal_sat">OpenArialMap</string>
+ <string name="base">OSM base layer</string>
+ <string name="topo">Topographic</string>
+ <string name="hills">Hills</string>
+ <string name="cloudmade_small">Cloudmade (small tiles)</string>
+ <string name="cloudmade_standard">Cloudmade (Standard tiles)</string>
+</resources>
diff --git a/cardroid/res/values/strings.xml b/cardroid/res/values/strings.xml
index 2d0d21c..ec1b000 100644
--- a/cardroid/res/values/strings.xml
+++ b/cardroid/res/values/strings.xml
@@ -1,5 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My CarinfoActivity</string>
<string name="hello">Hello World, CarinfoActivity</string>
+
+<string name="app_name_itemizedoverlay">OSMViewer ItemizedOverlay</string>
+<string name="unknown">Unknown</string>
+<string name="map_mode">Map mode</string>
+<string name="my_location">My location</string>
+<string name="samples">Samples</string>
+<string name="about">About</string>
+<string name="about_message">This software uses map data provided by <b>OpenStreetMap.org</b></string>
</resources>
diff --git a/cardroid/src/org/andnav/osm/R.java b/cardroid/src/org/andnav/osm/R.java
new file mode 100644
index 0000000..0a3903e
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/R.java
@@ -0,0 +1,31 @@
+// Dummy R.java to redirect to a generated one
+
+package org.andnav.osm;
+
+public final class R {
+
+ public static final class drawable {
+ public static final int center = de.cstimming.carinfo.R.drawable.center;
+ public static final int direction_arrow = de.cstimming.carinfo.R.drawable.direction_arrow;
+ public static final int marker_default = de.cstimming.carinfo.R.drawable.marker_default;
+ public static final int marker_default_focused_base = de.cstimming.carinfo.R.drawable.marker_default_focused_base;
+ public static final int navto_small = de.cstimming.carinfo.R.drawable.navto_small;
+ public static final int next = de.cstimming.carinfo.R.drawable.next;
+ public static final int person = de.cstimming.carinfo.R.drawable.person;
+ public static final int previous = de.cstimming.carinfo.R.drawable.previous;
+ }
+
+ public static final class string {
+ public static final int osmarender = de.cstimming.carinfo.R.string.osmarender;
+ public static final int mapnik = de.cstimming.carinfo.R.string.mapnik;
+ public static final int cyclemap = de.cstimming.carinfo.R.string.cyclemap;
+ public static final int openareal_sat = de.cstimming.carinfo.R.string.openareal_sat;
+ public static final int hills = de.cstimming.carinfo.R.string.hills;
+ public static final int base = de.cstimming.carinfo.R.string.base;
+ public static final int topo = de.cstimming.carinfo.R.string.topo;
+ public static final int unknown = de.cstimming.carinfo.R.string.unknown;
+ public static final int cloudmade_small = de.cstimming.carinfo.R.string.cloudmade_small;
+ public static final int cloudmade_standard = de.cstimming.carinfo.R.string.cloudmade_standard;
+ }
+
+}
diff --git a/cardroid/src/org/andnav/osm/contributor/GpxToPHPUploader.java b/cardroid/src/org/andnav/osm/contributor/GpxToPHPUploader.java
new file mode 100644
index 0000000..a7d2c36
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/contributor/GpxToPHPUploader.java
@@ -0,0 +1,70 @@
+package org.andnav.osm.contributor;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.util.ArrayList;
+
+import org.andnav.osm.contributor.util.RecordedGeoPoint;
+import org.andnav.osm.contributor.util.RecordedRouteGPXFormatter;
+import org.andnav.osm.contributor.util.Util;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.mime.MultipartEntity;
+import org.apache.http.entity.mime.content.InputStreamBody;
+import org.apache.http.impl.client.DefaultHttpClient;
+
+import android.util.Log;
+
+
+public class GpxToPHPUploader {
+
+ protected static final String UPLOADSCRIPT_URL = "http://www.PLACEYOURDOMAINHERE.com/anyfolder/gpxuploader/upload.php";
+
+ public static void uploadAsync(final ArrayList<RecordedGeoPoint> recordedGeoPoints){
+ new Thread(new Runnable(){
+ @Override
+ public void run() {
+ try{
+ if(!Util.isSufficienDataForUpload(recordedGeoPoints)) return;
+
+ final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes());
+ final HttpClient httpClient = new DefaultHttpClient();
+
+ final HttpPost request = new HttpPost(UPLOADSCRIPT_URL);
+
+ // create the multipart request and add the parts to it
+ final MultipartEntity requestEntity = new MultipartEntity();
+ requestEntity.addPart("gpxfile", new InputStreamBody(gpxInputStream, "" + System.currentTimeMillis() + ".gpx"));
+
+ httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
+
+ request.setEntity(requestEntity);
+
+ final HttpResponse response = httpClient.execute(request);
+ final int status = response.getStatusLine().getStatusCode();
+
+ if (status != HttpStatus.SC_OK) {
+ Log.e("GPXUploader", "status != HttpStatus.SC_OK");
+ } else {
+ final Reader r = new InputStreamReader(new BufferedInputStream(response.getEntity().getContent()));
+ // see above
+ final char[] buf = new char[8 * 1024];
+ int read;
+ final StringBuilder sb = new StringBuilder();
+ while((read = r.read(buf)) != -1)
+ sb.append(buf, 0, read);
+
+ Log.d("GPXUploader", "Response: " + sb.toString());
+ }
+ }catch (Exception e){
+// Log.e(DEBUGTAG, "OSMUpload Error", e);
+ }
+ }
+ }).start();
+ }
+}
diff --git a/cardroid/src/org/andnav/osm/contributor/OSMUploader.java b/cardroid/src/org/andnav/osm/contributor/OSMUploader.java
new file mode 100644
index 0000000..5737018
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/contributor/OSMUploader.java
@@ -0,0 +1,223 @@
+package org.andnav.osm.contributor;
+
+/**
+ * Copyright by Christof Dallermassl
+ * This program is free software and licensed under GPL.
+ *
+ * Original JAVA-Code ported for Android compatibility by Nicolas 'plusminus' Gramlich.
+ */
+
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.GregorianCalendar;
+
+import org.andnav.osm.contributor.util.RecordedGeoPoint;
+import org.andnav.osm.contributor.util.RecordedRouteGPXFormatter;
+import org.andnav.osm.contributor.util.Util;
+import org.andnav.osm.contributor.util.constants.OpenStreetMapContributorConstants;
+import org.andnav.osm.util.constants.OpenStreetMapConstants;
+
+
+/**
+ * Small java class that allows to upload gpx files to www.openstreetmap.org via its api call.
+ *
+ * @author cdaller
+ * @author Nicolas Gramlich
+ */
+public class OSMUploader implements OpenStreetMapConstants, OpenStreetMapContributorConstants{
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ public static final String API_VERSION = "0.5";
+ private static final int BUFFER_SIZE = 65535;
+ private static final String BASE64_ENC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ private static final String BOUNDARY = "----------------------------d10f7aa230e8";
+ private static final String LINE_END = "\r\n";
+
+ private static final String DEFAULT_DESCRIPTION = "AndNav - automatically created route.";
+ private static final String DEFAULT_TAGS = "AndNav";
+
+ public static final SimpleDateFormat pseudoFileNameFormat = new SimpleDateFormat("yyyyMMdd'_'HHmmss'_'SSS");
+ private static final SimpleDateFormat autoTagFormat = new SimpleDateFormat("MMMM yyyy");
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ /**
+ * Uses OSMConstants.OSM_USERNAME and OSMConstants.OSM_PASSWORD as username/password.
+ * Description will be <code>DEFAULT_DESCRIPTION</code>, tags will be automatically generated (i.e. "<code>October 2008</code>")
+ * NOTE: This method is not blocking!
+ * @param gpxInputStream the InputStream containing the gpx-data.
+ * @throws IOException
+ */
+ public static void uploadAsync(final ArrayList<RecordedGeoPoint> recordedGeoPoints) {
+ uploadAsync( DEFAULT_DESCRIPTION, DEFAULT_TAGS, true, recordedGeoPoints);
+ }
+
+ /**
+ * Uses OSMConstants.OSM_USERNAME and OSMConstants.OSM_PASSWORD as username/password.
+ * The 'filename' will be the current <code>timestamp.gpx</code> (i.e. "20081231_234815_912.gpx")
+ * NOTE: This method is not blocking!
+ * @param description <code>not null</code>
+ * @param tags <code>not null</code>
+ * @param addDateTags adds Date Tags to the existing Tags (i.e. "October 2008")
+ * @param gpxInputStreaman the InputStream containing the gpx-data.
+ * @throws IOException
+ */
+ public static void uploadAsync(final String description, final String tags, final boolean addDateTags, final ArrayList<RecordedGeoPoint> recordedGeoPoints) {
+ uploadAsync(OSM_USERNAME, OSM_PASSWORD, description, tags, addDateTags, recordedGeoPoints, pseudoFileNameFormat.format(new GregorianCalendar().getTime()) + "_" + OSM_USERNAME + ".gpx");
+ }
+
+
+ /**
+ * NOTE: This method is not blocking! (Code runs in thread)
+ * @param username <code>not null</code> and <code>not empty</code>. Valid OSM-username
+ * @param password <code>not null</code> and <code>not empty</code>. Valid password to the OSM-username.
+ * @param description <code>not null</code>
+ * @param tags if <code>null</code> addDateTags is treated as <code>true</code>
+ * @param addDateTags adds Date Tags to the existing Tags (i.e. "<code>October 2008</code>")
+ * @param gpxInputStream the InputStream containing the gpx-data.
+ * @param pseudoFileName ending with "<code>.gpx</code>"
+ * @throws IOException
+ */
+ public static void uploadAsync(final String username, final String password, final String description, final String tags, final boolean addDateTags, final ArrayList<RecordedGeoPoint> recordedGeoPoints, final String pseudoFileName) {
+ if(username == null || username.length() == 0) return;
+ if(password == null || password.length() == 0) return;
+ if(description == null || description.length() == 0) return;
+ if(tags == null || tags.length() == 0) return;
+ if(pseudoFileName == null || pseudoFileName.endsWith(".gpx")) return;
+
+ new Thread(new Runnable(){
+ @Override
+ public void run() {
+ if(!Util.isSufficienDataForUpload(recordedGeoPoints)) return;
+
+ final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes());
+
+ String tagsToUse = tags;
+ if(addDateTags || tagsToUse == null)
+ if(tagsToUse == null)
+ tagsToUse = autoTagFormat.format(new GregorianCalendar().getTime());
+ else
+ tagsToUse = tagsToUse + " " + autoTagFormat.format(new GregorianCalendar().getTime());
+
+// Log.d(DEBUGTAG, "Uploading " + pseudoFileName + " to openstreetmap.org");
+ try {
+ //String urlGpxName = URLEncoder.encode(gpxName.replaceAll("\\.;&?,/","_"), "UTF-8");
+ final String urlDesc = (description == null) ? DEFAULT_DESCRIPTION : description.replaceAll("\\.;&?,/","_");
+ final String urlTags = (tagsToUse == null) ? DEFAULT_TAGS : tagsToUse.replaceAll("\\\\.;&?,/","_");
+ final URL url = new URL("http://www.openstreetmap.org/api/" + API_VERSION + "/gpx/create");
+// Log.d(DEBUGTAG, "Destination Url: " + url);
+ final HttpURLConnection con = (HttpURLConnection) url.openConnection();
+ con.setConnectTimeout(15000);
+ con.setRequestMethod("POST");
+ con.setDoOutput(true);
+ con.addRequestProperty("Authorization", "Basic "+encodeBase64(username+":"+password));
+ con.addRequestProperty("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
+ con.addRequestProperty("Connection", "close"); // counterpart of keep-alive
+ con.addRequestProperty("Expect", "");
+
+ con.connect();
+ DataOutputStream out = new DataOutputStream(new BufferedOutputStream(con.getOutputStream()));
+ // DataOutputStream out = new DataOutputStream(System.out);
+
+ writeContentDispositionFile(out, "file", gpxInputStream, pseudoFileName);
+ writeContentDisposition(out, "description", urlDesc);
+ writeContentDisposition(out, "tags", urlTags);
+
+ writeContentDisposition(out, "public", "1");
+
+ out.writeBytes("--" + BOUNDARY + "--" + LINE_END);
+ out.flush();
+
+ final int retCode = con.getResponseCode();
+ String retMsg = con.getResponseMessage();
+// Log.d(DEBUGTAG, "\nreturn code: "+retCode + " " + retMsg);
+ if (retCode != 200) {
+ // Look for a detailed error message from the server
+ if (con.getHeaderField("Error") != null)
+ retMsg += "\n" + con.getHeaderField("Error");
+ con.disconnect();
+ throw new RuntimeException(retCode+" "+retMsg);
+ }
+ out.close();
+ con.disconnect();
+ } catch(Exception e) {
+// Log.e(DEBUGTAG, "OSMUpload Error", e);
+ }
+ }
+
+ }, "OSMUpload-Thread").start();
+ }
+
+ public static void upload(final String username, final String password, final String description, final String tags, final boolean addDateTags, final ArrayList<RecordedGeoPoint> recordedGeoPoints, final String pseudoFileName) throws IOException{
+ uploadAsync(username, password, description, tags, addDateTags, recordedGeoPoints, pseudoFileName);
+ }
+
+ /**
+ * @param out
+ * @param string
+ * @param gpxFile
+ * @throws IOException
+ */
+ private static void writeContentDispositionFile(final DataOutputStream out, final String name, final InputStream gpxInputStream, final String pseudoFileName) throws IOException {
+ out.writeBytes("--" + BOUNDARY + LINE_END);
+ out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + pseudoFileName + "\"" + LINE_END);
+ out.writeBytes("Content-Type: application/octet-stream" + LINE_END);
+ out.writeBytes(LINE_END);
+
+ final byte[] buffer = new byte[BUFFER_SIZE];
+ //int fileLen = (int)gpxFile.length();
+ int read;
+ int sumread = 0;
+ final InputStream in = new BufferedInputStream(gpxInputStream);
+// Log.d(DEBUGTAG, "Transferring data to server");
+ while((read = in.read(buffer)) >= 0) {
+ out.write(buffer, 0, read);
+ out.flush();
+ sumread += read;
+ }
+ in.close();
+ out.writeBytes(LINE_END);
+ }
+
+ /**
+ * @param string
+ * @param urlDesc
+ * @throws IOException
+ */
+ private static void writeContentDisposition(final DataOutputStream out, final String name, final String value) throws IOException {
+ out.writeBytes("--" + BOUNDARY + LINE_END);
+ out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + LINE_END);
+ out.writeBytes(LINE_END);
+ out.writeBytes(value + LINE_END);
+ }
+
+ private static String encodeBase64(final String s) {
+ StringBuilder out = new StringBuilder();
+ for (int i = 0; i < (s.length()+2)/3; ++i) {
+ int l = Math.min(3, s.length()-i*3);
+ final String buf = s.substring(i*3, i*3+l);
+ out.append(BASE64_ENC.charAt(buf.charAt(0)>>2));
+ out.append(BASE64_ENC.charAt((buf.charAt(0) & 0x03) << 4 | (l==1?0:(buf.charAt(1) & 0xf0) >> 4)));
+ out.append(l>1 ? BASE64_ENC.charAt((buf.charAt(1) & 0x0f) << 2 | (l==2 ? 0 : (buf.charAt(2) & 0xc0) >> 6)) : '=');
+ out.append(l>2 ? BASE64_ENC.charAt(buf.charAt(2) & 0x3f) : '=');
+ }
+ return out.toString();
+ }
+}
\ No newline at end of file
diff --git a/cardroid/src/org/andnav/osm/contributor/RouteRecorder.java b/cardroid/src/org/andnav/osm/contributor/RouteRecorder.java
new file mode 100644
index 0000000..0c953c3
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/contributor/RouteRecorder.java
@@ -0,0 +1,66 @@
+// Created by plusminus on 12:28:16 - 21.09.2008
+package org.andnav.osm.contributor;
+
+import java.util.ArrayList;
+
+import org.andnav.osm.contributor.util.RecordedGeoPoint;
+import org.andnav.osm.util.GeoPoint;
+
+import android.location.Location;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class RouteRecorder {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final ArrayList<RecordedGeoPoint> mRecords = new ArrayList<RecordedGeoPoint>();
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public ArrayList<RecordedGeoPoint> getRecordedGeoPoints() {
+ return this.mRecords;
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ public void add(final Location aLocation, final int aNumSatellites){
+ this.mRecords.add(new RecordedGeoPoint(
+ (int)(aLocation.getLatitude() * 1E6),
+ (int)(aLocation.getLongitude() * 1E6),
+ System.currentTimeMillis(),
+ aNumSatellites));
+ }
+
+ public void add(final GeoPoint aGeoPoint, final int aNumSatellites){
+ this.mRecords.add(new RecordedGeoPoint(
+ aGeoPoint.getLatitudeE6(),
+ aGeoPoint.getLongitudeE6(),
+ System.currentTimeMillis(),
+ aNumSatellites));
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/contributor/util/RecordedGeoPoint.java b/cardroid/src/org/andnav/osm/contributor/util/RecordedGeoPoint.java
new file mode 100644
index 0000000..6240adb
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/contributor/util/RecordedGeoPoint.java
@@ -0,0 +1,69 @@
+// Created by plusminus on 12:29:23 - 21.09.2008
+package org.andnav.osm.contributor.util;
+
+import org.andnav.osm.util.GeoPoint;
+import org.andnav.osm.util.constants.OpenStreetMapConstants;
+
+/**
+ * Extends the {@link GeoPoint} with a timeStamp.
+ * @author Nicolas Gramlich
+ */
+public class RecordedGeoPoint extends GeoPoint implements OpenStreetMapConstants {
+
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final long mTimeStamp;
+ protected final int mNumSatellites;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public RecordedGeoPoint(final int latitudeE6, final int longitudeE6) {
+ this(latitudeE6, longitudeE6, System.currentTimeMillis(), NOT_SET);
+ }
+
+ public RecordedGeoPoint(final int latitudeE6, final int longitudeE6, final long aTimeStamp, final int aNumSatellites) {
+ super(latitudeE6, longitudeE6);
+ this.mTimeStamp = aTimeStamp;
+ this.mNumSatellites = aNumSatellites;
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public long getTimeStamp() {
+ return this.mTimeStamp;
+ }
+
+ public double getLatitudeAsDouble(){
+ return this.getLatitudeE6() / 1E6;
+ }
+
+ public double getLongitudeAsDouble(){
+ return this.getLongitudeE6() / 1E6;
+ }
+
+ public int getNumSatellites(){
+ return this.mNumSatellites;
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/contributor/util/RecordedRouteGPXFormatter.java b/cardroid/src/org/andnav/osm/contributor/util/RecordedRouteGPXFormatter.java
new file mode 100644
index 0000000..abb34b9
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/contributor/util/RecordedRouteGPXFormatter.java
@@ -0,0 +1,118 @@
+// Created by plusminus on 13:23:45 - 21.09.2008
+package org.andnav.osm.contributor.util;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Formatter;
+import java.util.List;
+
+import org.andnav.osm.contributor.util.constants.OpenStreetMapContributorConstants;
+import org.andnav.osm.util.constants.OpenStreetMapConstants;
+
+/**
+ * Class capable of formatting a List of Points to the GPX 1.1 format.
+ * @author Nicolas Gramlich
+ *
+ */
+public class RecordedRouteGPXFormatter implements OpenStreetMapContributorConstants, OpenStreetMapConstants{
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ private static final String XML_VERSION = "<?xml version=\"1.0\"?>";
+ private static final String GPX_VERSION = "1.1";
+ private static final String GPX_TAG = "<gpx version=\"" + GPX_VERSION + "\" creator=\"%s\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/1\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">";
+ private static final String GPX_TAG_CLOSE = "</gpx>";
+ private static final String GPX_TAG_TIME = "<time>%s</time>";
+ private static final String GPX_TAG_TRACK = "<trk>";
+ private static final String GPX_TAG_TRACK_CLOSE = "</trk>";
+ private static final String GPX_TAG_TRACK_NAME = "<name>%s</name>";
+ private static final String GPX_TAG_TRACK_SEGMENT = "<trkseg>";
+ private static final String GPX_TAG_TRACK_SEGMENT_CLOSE = "</trkseg>";
+ private static final String GPX_TAG_TRACK_SEGMENT_POINT = "<trkpt lat=\"%f\" lon=\"%f\">";
+ private static final String GPX_TAG_TRACK_SEGMENT_POINT_CLOSE = "</trkpt>";
+ private static final String GPX_TAG_TRACK_SEGMENT_POINT_TIME = "<time>%s</time>";
+ private static final String GPX_TAG_TRACK_SEGMENT_POINT_SAT = "<sat>%d</sat>";
+
+
+ private static final SimpleDateFormat formatterCompleteDateTime = new SimpleDateFormat("yyyyMMdd'_'HHmmss");
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+ /**
+ * Creates a String in the following XML format:
+ * <PRE><?xml version="1.0"?>
+ * <gpx version="1.1" creator="AndNav - http://www.andnav.org - Android Navigation System" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
+ * <time>2008-09-22T00:46:20Z</time>
+ * <trk>
+ * <name>plusminus--yyyyMMdd_HHmmss-yyyyMMdd_HHmmss</name>
+ * <trkseg>
+ * <trkpt lat="49.472767" lon="8.654174">
+ * <time>2008-09-22T00:46:20Z</time>
+ * </trkpt>
+ * <trkpt lat="49.472797" lon="8.654102">
+ * <time>2008-09-22T00:46:35Z</time>
+ * </trkpt>
+ * <trkpt lat="49.472802" lon="8.654185">
+ * <time>2008-09-22T00:46:50Z</time>
+ * </trkpt>
+ * </trkseg>
+ * </trk>
+ * </gpx></PRE>
+ *
+ */
+ public static String create(final List<RecordedGeoPoint> someRecords) throws IllegalArgumentException {
+ if(someRecords == null)
+ throw new IllegalArgumentException("Records may not be null.");
+
+ if(someRecords.size() == 0)
+ throw new IllegalArgumentException("Records size == 0");
+
+ final StringBuilder sb = new StringBuilder();
+ final Formatter f = new Formatter(sb);
+ sb.append(XML_VERSION);
+ f.format(GPX_TAG, OSM_CREATOR_INFO);
+ f.format(GPX_TAG_TIME, Util.convertTimestampToUTCString(System.currentTimeMillis()));
+ sb.append(GPX_TAG_TRACK);
+ f.format(GPX_TAG_TRACK_NAME, OSM_USERNAME + "--"
+ + formatterCompleteDateTime.format(new Date(someRecords.get(0).getTimeStamp()).getTime())
+ + "-"
+ + formatterCompleteDateTime.format(new Date(someRecords.get(someRecords.size() - 1).getTimeStamp()).getTime()));
+ sb.append(GPX_TAG_TRACK_SEGMENT);
+
+ for (RecordedGeoPoint rgp : someRecords) {
+ f.format(GPX_TAG_TRACK_SEGMENT_POINT, rgp.getLatitudeAsDouble(), rgp.getLongitudeAsDouble());
+ f.format(GPX_TAG_TRACK_SEGMENT_POINT_TIME, Util.convertTimestampToUTCString(rgp.getTimeStamp()));
+ if(rgp.mNumSatellites != NOT_SET)
+ f.format(GPX_TAG_TRACK_SEGMENT_POINT_SAT, rgp.mNumSatellites);
+ sb.append(GPX_TAG_TRACK_SEGMENT_POINT_CLOSE);
+ }
+
+ sb.append(GPX_TAG_TRACK_SEGMENT_CLOSE)
+ .append(GPX_TAG_TRACK_CLOSE)
+ .append(GPX_TAG_CLOSE);
+
+ return sb.toString();
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/contributor/util/Util.java b/cardroid/src/org/andnav/osm/contributor/util/Util.java
new file mode 100644
index 0000000..10dc0e1
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/contributor/util/Util.java
@@ -0,0 +1,69 @@
+// Created by plusminus on 13:24:05 - 21.09.2008
+package org.andnav.osm.contributor.util;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.TimeZone;
+
+import org.andnav.osm.contributor.util.constants.OpenStreetMapContributorConstants;
+import org.andnav.osm.util.BoundingBoxE6;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class Util implements OpenStreetMapContributorConstants{
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ public static final SimpleDateFormat UTCSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
+ {
+ UTCSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ }
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ public static final String convertTimestampToUTCString(final long aTimestamp){
+ return UTCSimpleDateFormat.format(new Date(aTimestamp));
+ }
+
+ public static boolean isSufficienDataForUpload(final ArrayList<RecordedGeoPoint> recordedGeoPoints){
+ if(recordedGeoPoints == null)
+ return false;
+
+ if(recordedGeoPoints.size() < MINGEOPOINTS_FOR_OSM_CONTRIBUTION)
+ return false;
+
+ final BoundingBoxE6 bb = BoundingBoxE6.fromGeoPoints(recordedGeoPoints);
+ final int diagMeters = bb.getDiagonalLengthInMeters();
+ if(diagMeters < MINDIAGONALMETERS_FOR_OSM_CONTRIBUTION)
+ return false;
+
+ return true;
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/contributor/util/constants/OpenStreetMapContributorConstants.java b/cardroid/src/org/andnav/osm/contributor/util/constants/OpenStreetMapContributorConstants.java
new file mode 100644
index 0000000..016b2fb
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/contributor/util/constants/OpenStreetMapContributorConstants.java
@@ -0,0 +1,27 @@
+// Created by plusminus on 14:11:09 - 21.09.2008
+package org.andnav.osm.contributor.util.constants;
+
+/**
+ *
+ * This class contains constants used by the contributor package.
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public interface OpenStreetMapContributorConstants {
+ // ===========================================================
+ // Final Fields
+ // ===========================================================
+
+ public static final String OSM_USERNAME = "PUT_YOUR_USERNAME_HERE";
+ public static final String OSM_PASSWORD = "PUT_YOUR_PASSWORD_HERE";
+
+ public static final int MINGEOPOINTS_FOR_OSM_CONTRIBUTION = 100;
+ public static final int MINDIAGONALMETERS_FOR_OSM_CONTRIBUTION = 300;
+
+ public static final String OSM_CREATOR_INFO = "AndNav - http://www.andnav.org - Android Navigation System";
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderService.aidl b/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderService.aidl
new file mode 100644
index 0000000..52502cd
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderService.aidl
@@ -0,0 +1,24 @@
+package org.andnav.osm.services;
+
+import org.andnav.osm.services.IOpenStreetMapTileProviderServiceCallback;
+
+interface IOpenStreetMapTileProviderService {
+
+/**
+ * Set the callback for tile completions.
+ * @param callback the callback to notify when the request completes
+ */
+void setCallback(in IOpenStreetMapTileProviderServiceCallback callback);
+
+/**
+ * Initiate a request for a map tile.
+ * When the request has completed it will call the callback previously set in setCallback.
+ * @param rendererID
+ * @param zoomLevel
+ * @param tileX
+ * @param tileY
+ * @param callback the callback to notify when the request completes
+ */
+void requestMapTile(in int rendererID, in int zoomLevel, in int tileX, in int tileY);
+
+}
diff --git a/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderServiceCallback.aidl b/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderServiceCallback.aidl
new file mode 100644
index 0000000..f465a8b
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/services/IOpenStreetMapTileProviderServiceCallback.aidl
@@ -0,0 +1,15 @@
+package org.andnav.osm.services;
+
+interface IOpenStreetMapTileProviderServiceCallback {
+
+/**
+ * The map tile request has completed.
+ * @param rendererID
+ * @param zoomLevel
+ * @param tileX
+ * @param tileY
+ * @param aTilePath the path of the requested tile, or null if request has completed without returning a tile path
+ */
+void mapTileRequestCompleted(in int rendererID, in int zoomLevel, in int tileX, in int tileY, in String aTilePath);
+
+}
diff --git a/cardroid/src/org/andnav/osm/services/OpenStreetMapTileProviderService.java b/cardroid/src/org/andnav/osm/services/OpenStreetMapTileProviderService.java
new file mode 100644
index 0000000..0c0be65
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/services/OpenStreetMapTileProviderService.java
@@ -0,0 +1,105 @@
+package org.andnav.osm.services;
+
+import org.andnav.osm.services.constants.OpenStreetMapServiceConstants;
+import org.andnav.osm.tileprovider.IOpenStreetMapTileProviderCallback;
+import org.andnav.osm.tileprovider.OpenStreetMapTile;
+import org.andnav.osm.tileprovider.OpenStreetMapTileFilesystemProvider;
+
+import android.app.Service;
+import android.content.Intent;
+import android.content.res.Configuration;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.util.Log;
+
+/**
+ * The OpenStreetMapTileProviderService can download map tiles from a server
+ * and stores them in a file system cache.
+ * @author Manuel Stahl
+ */
+public class OpenStreetMapTileProviderService extends Service implements OpenStreetMapServiceConstants, IOpenStreetMapTileProviderCallback {
+
+ private static final String DEBUGTAG = "OSM_TILE_PROVIDER_SERVICE";
+
+ private OpenStreetMapTileFilesystemProvider mFileSystemProvider;
+ private IOpenStreetMapTileProviderServiceCallback mCallback;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mFileSystemProvider = new OpenStreetMapTileFilesystemProvider(this);
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mBinder;
+ }
+
+ @Override
+ public void onConfigurationChanged(Configuration pNewConfig) {
+ if(DEBUGMODE)
+ Log.d(DEBUGTAG, "onConfigurationChanged");
+ super.onConfigurationChanged(pNewConfig);
+ }
+
+ @Override
+ public void onDestroy() {
+ if(DEBUGMODE)
+ Log.d(DEBUGTAG, "onDestroy");
+ mFileSystemProvider.stopWorkers();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onLowMemory() {
+ if(DEBUGMODE)
+ Log.d(DEBUGTAG, "onLowMemory");
+ super.onLowMemory();
+ }
+
+ @Override
+ public void onRebind(Intent pIntent) {
+ if(DEBUGMODE)
+ Log.d(DEBUGTAG, "onRebind");
+ super.onRebind(pIntent);
+ }
+
+ @Override
+ public void onStart(Intent pIntent, int pStartId) {
+ if(DEBUGMODE)
+ Log.d(DEBUGTAG, "onStart");
+ super.onStart(pIntent, pStartId);
+ }
+
+ @Override
+ public boolean onUnbind(Intent pIntent) {
+ if(DEBUGMODE)
+ Log.d(DEBUGTAG, "onUnbind");
+ return super.onUnbind(pIntent);
+ }
+
+ @Override
+ public void mapTileRequestCompleted(final OpenStreetMapTile pTile, final String pTilePath) {
+ try {
+ mCallback.mapTileRequestCompleted(pTile.getRendererId(), pTile.getZoomLevel(), pTile.getX(), pTile.getY(), pTilePath);
+ } catch (final RemoteException e) {
+ Log.e(DEBUGTAG, "Error invoking callback", e);
+ }
+ }
+
+ /**
+ * The IRemoteInterface is defined through IDL
+ */
+ private final IOpenStreetMapTileProviderService.Stub mBinder = new IOpenStreetMapTileProviderService.Stub() {
+ @Override
+ public void setCallback(final IOpenStreetMapTileProviderServiceCallback pCallback) throws RemoteException {
+ mCallback = pCallback;
+ }
+ @Override
+ public void requestMapTile(int rendererID, int zoomLevel, int tileX, int tileY) throws RemoteException {
+ OpenStreetMapTile tile = new OpenStreetMapTile(rendererID, zoomLevel, tileX, tileY);
+ mFileSystemProvider.loadMapTileAsync(tile);
+ }
+ };
+
+}
diff --git a/cardroid/src/org/andnav/osm/services/constants/OpenStreetMapServiceConstants.java b/cardroid/src/org/andnav/osm/services/constants/OpenStreetMapServiceConstants.java
new file mode 100644
index 0000000..07a8a47
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/services/constants/OpenStreetMapServiceConstants.java
@@ -0,0 +1,21 @@
+package org.andnav.osm.services.constants;
+
+
+/**
+ *
+ * This class contains constants used by the service.
+ *
+ * @author Neil Boyd
+ *
+ */
+public interface OpenStreetMapServiceConstants {
+ // ===========================================================
+ // Final Fields
+ // ===========================================================
+
+ public static final boolean DEBUGMODE = false;
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/IOpenStreetMapTileProviderCallback.java b/cardroid/src/org/andnav/osm/tileprovider/IOpenStreetMapTileProviderCallback.java
new file mode 100644
index 0000000..0aac24e
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/tileprovider/IOpenStreetMapTileProviderCallback.java
@@ -0,0 +1,12 @@
+package org.andnav.osm.tileprovider;
+
+public interface IOpenStreetMapTileProviderCallback {
+
+ /**
+ * The map tile request has completed.
+ * @param pTile the tile request that has completed
+ * @param aTilePath the path of the requested tile, or null if request has completed without returning a tile path
+ */
+ void mapTileRequestCompleted(OpenStreetMapTile pTile, String aTilePath);
+
+}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapAsyncTileProvider.java b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapAsyncTileProvider.java
new file mode 100644
index 0000000..08dfd48
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapAsyncTileProvider.java
@@ -0,0 +1,171 @@
+package org.andnav.osm.tileprovider;
+
+import java.util.ConcurrentModificationException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+
+import org.andnav.osm.tileprovider.constants.OpenStreetMapTileProviderConstants;
+
+import android.util.Log;
+
+public abstract class OpenStreetMapAsyncTileProvider implements OpenStreetMapTileProviderConstants {
+
+ private final int mThreadPoolSize;
+ private final ThreadGroup mThreadPool = new ThreadGroup(debugtag());
+ private final HashMap<OpenStreetMapTile, Object> mWorking;
+ final LinkedHashMap<OpenStreetMapTile, Object> mPending;
+ private static final Object PRESENT = new Object();
+
+ protected final IOpenStreetMapTileProviderCallback mCallback;
+
+ public OpenStreetMapAsyncTileProvider(final IOpenStreetMapTileProviderCallback pCallback, final int aThreadPoolSize, final int aPendingQueueSize) {
+ mCallback = pCallback;
+ mThreadPoolSize = aThreadPoolSize;
+ mWorking = new HashMap<OpenStreetMapTile, Object>();
+ mPending = new LinkedHashMap<OpenStreetMapTile, Object>(aPendingQueueSize + 2, 0.1f, true) {
+ private static final long serialVersionUID = 6455337315681858866L;
+ @Override
+ protected boolean removeEldestEntry(Entry<OpenStreetMapTile, Object> pEldest) {
+ return size() > aPendingQueueSize;
+ }
+ };
+ }
+
+ public void loadMapTileAsync(final OpenStreetMapTile aTile) {
+
+ final int activeCount = mThreadPool.activeCount();
+
+ // sanity check
+ if (activeCount == 0 && !mPending.isEmpty()) {
+ Log.w(debugtag(), "Unexpected - no active threads but pending queue not empty");
+ clearQueue();
+ }
+
+ // this will put the tile in the queue, or move it to the front of the
+ // queue if it's already present
+ mPending.put(aTile, PRESENT);
+
+ if (DEBUGMODE)
+ Log.d(debugtag(), activeCount + " active threads");
+ if (activeCount < mThreadPoolSize) {
+ final Thread t = new Thread(mThreadPool, getTileLoader());
+ t.start();
+ }
+ }
+
+ private void clearQueue() {
+ mPending.clear();
+ mWorking.clear();
+ }
+
+ /**
+ * Stops all workers, the service is shutting down.
+ */
+ public void stopWorkers()
+ {
+ this.clearQueue();
+ this.mThreadPool.interrupt();
+ }
+
+ /**
+ * The debug tag.
+ * Because the tag of the abstract class is not so interesting.
+ * @return
+ */
+ protected abstract String debugtag();
+
+ protected abstract Runnable getTileLoader();
+
+ protected interface TileLoaderCallback {
+ /**
+ * A tile has loaded.
+ * @param aTile the tile that has loaded
+ * @param aTilePath the path of the file. May be null.
+ * @param aRefresh whether to redraw the screen so that new tiles will be used
+ */
+ void tileLoaded(OpenStreetMapTile aTile, String aTilePath, boolean aRefresh);
+ }
+
+ protected abstract class TileLoader implements Runnable, TileLoaderCallback {
+ /**
+ * Load the requested tile.
+ * @param aTile the tile to load
+ * @throws CantContinueException if it is not possible to continue with processing the queue
+ */
+ protected abstract void loadTile(OpenStreetMapTile aTile) throws CantContinueException;
+
+ private OpenStreetMapTile nextTile() {
+
+ synchronized (mPending) {
+ OpenStreetMapTile result = null;
+
+ // get the most recently accessed tile
+ // - the last item in the iterator that's not already being processed
+ Iterator<OpenStreetMapTile> iterator = mPending.keySet().iterator();
+
+ // TODO this iterates the whole list, make this faster...
+ while (iterator.hasNext()) {
+ try {
+ final OpenStreetMapTile tile = iterator.next();
+ if (!mWorking.containsKey(tile)) {
+ result = tile;
+ }
+ } catch (final ConcurrentModificationException e) {
+ if (DEBUGMODE)
+ Log.w(debugtag(), "ConcurrentModificationException break: " + (result != null));
+
+ // if we've got a result return it, otherwise try again
+ if (result != null) {
+ break;
+ } else {
+ iterator = mPending.keySet().iterator();
+ }
+ }
+ }
+
+ if (result != null)
+ {
+ mWorking.put(result, PRESENT);
+ }
+
+ return result;
+ }
+ }
+
+ @Override
+ public void tileLoaded(final OpenStreetMapTile aTile, final String aTilePath, final boolean aRefresh) {
+
+ mPending.remove(aTile);
+ mWorking.remove(aTile);
+
+ if (aRefresh) {
+ mCallback.mapTileRequestCompleted(aTile, aTilePath);
+ }
+ }
+
+ @Override
+ final public void run() {
+
+ OpenStreetMapTile tile;
+ while ((tile = nextTile()) != null) {
+ if (DEBUGMODE)
+ Log.d(debugtag(), "Next tile: " + tile);
+ try {
+ loadTile(tile);
+ } catch (final CantContinueException e) {
+ Log.i(debugtag(), "Tile loader can't continue");
+ clearQueue();
+ } catch (final Throwable e) {
+ Log.e(debugtag(), "Error downloading tile: " + tile, e);
+ }
+ }
+ if (DEBUGMODE)
+ Log.d(debugtag(), "No more tiles");
+ }
+ }
+
+ protected class CantContinueException extends Exception {
+ private static final long serialVersionUID = 146526524087765133L;
+ }
+}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTile.java b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTile.java
new file mode 100644
index 0000000..85f732a
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTile.java
@@ -0,0 +1,60 @@
+package org.andnav.osm.tileprovider;
+
+public class OpenStreetMapTile {
+
+ public static final int MAPTILE_SUCCESS_ID = 0;
+ public static final int MAPTILE_FAIL_ID = MAPTILE_SUCCESS_ID + 1;
+
+ private final int rendererId;
+ private final int x;
+ private final int y;
+ private final int zoomLevel;
+
+ public OpenStreetMapTile(int rendererId, int zoomLevel, int tileX, int tileY) {
+ this.rendererId = rendererId;
+ this.zoomLevel = zoomLevel;
+ this.x = tileX;
+ this.y = tileY;
+ }
+
+ public int getRendererId() {
+ return rendererId;
+ }
+
+ public int getZoomLevel() {
+ return zoomLevel;
+ }
+
+ public int getX() {
+ return x;
+ }
+
+ public int getY() {
+ return y;
+ }
+
+ @Override
+ public String toString() {
+ return rendererId + "/" + zoomLevel + "/" + x + "/" + y;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof OpenStreetMapTile) {
+ OpenStreetMapTile t = (OpenStreetMapTile) o;
+ return zoomLevel == t.zoomLevel && x == t.x && y == t.y && rendererId == t.rendererId;
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ int code = 17;
+ code *= 37 + rendererId;
+ code *= 37 + zoomLevel;
+ code *= 37 + x;
+ code *= 37 + y;
+ return code;
+ }
+
+}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileDownloader.java b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileDownloader.java
new file mode 100644
index 0000000..8cbc1d1
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileDownloader.java
@@ -0,0 +1,139 @@
+// Created by plusminus on 21:31:36 - 25.09.2008
+package org.andnav.osm.tileprovider;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URL;
+import java.net.UnknownHostException;
+
+import org.andnav.osm.views.util.OpenStreetMapRendererInfo;
+
+import android.util.Log;
+
+/**
+ * The OpenStreetMapTileDownloader loads tiles from a server and passes them to
+ * a OpenStreetMapTileFilesystemProvider.
+ * @author Nicolas Gramlich
+ * @author Manuel Stahl
+ *
+ */
+public class OpenStreetMapTileDownloader extends OpenStreetMapAsyncTileProvider {
+
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ private static final String DEBUGTAG = "OSM_DOWNLOADER";
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ private final OpenStreetMapTileFilesystemProvider mMapTileFSProvider;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public OpenStreetMapTileDownloader(final IOpenStreetMapTileProviderCallback pCallback, final OpenStreetMapTileFilesystemProvider aMapTileFSProvider){
+ super(pCallback, NUMBER_OF_TILE_DOWNLOAD_THREADS, TILE_DOWNLOAD_MAXIMUM_QUEUE_SIZE);
+ this.mMapTileFSProvider = aMapTileFSProvider;
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ protected String debugtag() {
+ return DEBUGTAG;
+ }
+
+ @Override
+ protected Runnable getTileLoader() {
+ return new TileLoader();
+ };
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ private String buildURL(final OpenStreetMapTile tile) {
+ OpenStreetMapRendererInfo renderer = OpenStreetMapRendererInfo.values()[tile.getRendererId()];
+ return renderer.getTileURLString(tile);
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+
+ private class TileLoader extends OpenStreetMapAsyncTileProvider.TileLoader {
+
+ @Override
+ public void loadTile(final OpenStreetMapTile aTile) throws CantContinueException {
+
+ InputStream in = null;
+ OutputStream out = null;
+
+ final File outputFile = mMapTileFSProvider.getOutputFile(aTile);
+ final String tileURLString = buildURL(aTile);
+
+ try {
+ if(DEBUGMODE)
+ Log.d(DEBUGTAG, "Downloading Maptile from url: " + tileURLString);
+
+ in = new BufferedInputStream(new URL(tileURLString).openStream(), StreamUtils.IO_BUFFER_SIZE);
+
+ final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
+ out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
+ StreamUtils.copy(in, out);
+ out.flush();
+
+ final byte[] data = dataStream.toByteArray();
+
+ // sanity check - don't save an empty file
+ if (data.length == 0) {
+ Log.i(DEBUGTAG, "Empty maptile not saved: " + aTile);
+ } else {
+ mMapTileFSProvider.saveFile(aTile, outputFile, data);
+ if(DEBUGMODE)
+ Log.d(DEBUGTAG, "Maptile saved " + data.length + " bytes : " + aTile);
+ }
+ } catch (final UnknownHostException e) {
+ // no network connection so empty the queue
+ Log.w(DEBUGTAG, "UnknownHostException downloading MapTile: " + aTile + " : " + e);
+ throw new CantContinueException();
+ } catch(final FileNotFoundException e){
+ Log.w(DEBUGTAG, "Url not found: " + aTile+ " : " + e);
+ } catch (final IOException e) {
+ Log.w(DEBUGTAG, "IOException downloading MapTile: " + aTile + " : " + e);
+ } catch(final Throwable e) {
+ Log.e(DEBUGTAG, "Error downloading MapTile: " + aTile, e);
+ } finally {
+ StreamUtils.closeStream(in);
+ StreamUtils.closeStream(out);
+ }
+
+ /* Don't immediately send the tile back.
+ * If we're moving, and the internet is a bit patchy, then by the time
+ * the download has finished we don't need this tile any more.
+ * If we still do need it then the file system provider will get it
+ * again next time it's needed.
+ * That should be immediately because the view is redrawn when it
+ * receives this completion event.
+ */
+ tileLoaded(aTile, null, true);
+ }
+ };
+
+}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileFilesystemProvider.java b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileFilesystemProvider.java
new file mode 100644
index 0000000..88343da
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/tileprovider/OpenStreetMapTileFilesystemProvider.java
@@ -0,0 +1,135 @@
+// Created by plusminus on 21:46:41 - 25.09.2008
+package org.andnav.osm.tileprovider;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.andnav.osm.views.util.OpenStreetMapRendererInfo;
+
+import android.util.Log;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class OpenStreetMapTileFilesystemProvider extends OpenStreetMapAsyncTileProvider {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ final static String DEBUGTAG = "OSM_FS_PROVIDER";
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ /** online provider */
+ protected OpenStreetMapTileDownloader mTileDownloader;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ /**
+ * @param ctx
+ * @param aCache to load fs-tiles to.
+ */
+ public OpenStreetMapTileFilesystemProvider(final IOpenStreetMapTileProviderCallback pCallback) {
+ super(pCallback, NUMBER_OF_TILE_FILESYSTEM_THREADS, TILE_FILESYSTEM_MAXIMUM_QUEUE_SIZE);
+ this.mTileDownloader = new OpenStreetMapTileDownloader(pCallback, this);
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ protected String debugtag() {
+ return DEBUGTAG;
+ }
+
+ @Override
+ protected Runnable getTileLoader() {
+ return new TileLoader();
+ };
+
+
+ /**
+ * Stops all workers, the service is shutting down.
+ */
+ @Override
+ public void stopWorkers()
+ {
+ super.stopWorkers();
+ this.mTileDownloader.stopWorkers();
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ private String buildPath(final OpenStreetMapTile tile) {
+ final OpenStreetMapRendererInfo renderer = OpenStreetMapRendererInfo.values()[tile.getRendererId()];
+ return TILE_PATH_BASE + renderer.name() + "/" + tile.getZoomLevel() + "/"
+ + tile.getX() + "/" + tile.getY() + renderer.IMAGE_FILENAMEENDING + TILE_PATH_EXTENSION;
+ }
+
+ /**
+ * Get the file location for the tile.
+ * @param tile
+ * @return
+ * @throws CantContinueException if the directory containing the file doesn't exist
+ * and can't be created
+ */
+ File getOutputFile(final OpenStreetMapTile tile) throws CantContinueException {
+ final File file = new File(buildPath(tile));
+ final File parent = file.getParentFile();
+ if (!parent.exists() && !parent.mkdirs()) {
+ throw new CantContinueException();
+ }
+ return file;
+ }
+
+ void saveFile(final OpenStreetMapTile tile, final File outputFile, final byte[] someData) throws IOException{
+ final OutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile, false), StreamUtils.IO_BUFFER_SIZE);
+ bos.write(someData);
+ bos.flush();
+ bos.close();
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+
+ private class TileLoader extends OpenStreetMapAsyncTileProvider.TileLoader {
+
+ @Override
+ public void loadTile(final OpenStreetMapTile aTile) throws CantContinueException {
+ final File tileFile = getOutputFile(aTile);
+ try {
+ if (tileFile.exists()) {
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "Loaded tile: " + aTile);
+ tileLoaded(aTile, tileFile.getPath(), true);
+ } else {
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "Tile not exist, request for download: " + aTile);
+ mTileDownloader.loadMapTileAsync(aTile);
+ // don't refresh the screen because there's nothing new
+ tileLoaded(aTile, null, false);
+ }
+ } catch (final Throwable e) {
+ Log.e(DEBUGTAG, "Error loading tile", e);
+ tileLoaded(aTile, null, false);
+ }
+ }
+ }
+}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/StreamUtils.java b/cardroid/src/org/andnav/osm/tileprovider/StreamUtils.java
new file mode 100644
index 0000000..d2c38f4
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/tileprovider/StreamUtils.java
@@ -0,0 +1,72 @@
+// Created by plusminus on 19:14:08 - 20.10.2008
+package org.andnav.osm.tileprovider;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+
+public class StreamUtils {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ public static final int IO_BUFFER_SIZE = 8 * 1024;
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ /**
+ * Copy the content of the input stream into the output stream, using a temporary
+ * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
+ *
+ * @param in The input stream to copy from.
+ * @param out The output stream to copy to.
+ *
+ * @throws IOException If any error occurs during the copy.
+ */
+ public static void copy(InputStream in, OutputStream out) throws IOException {
+ byte[] b = new byte[IO_BUFFER_SIZE];
+ int read;
+ while ((read = in.read(b)) != -1) {
+ out.write(b, 0, read);
+ }
+ }
+
+ /**
+ * Closes the specified stream.
+ *
+ * @param stream The stream to close.
+ */
+ public static void closeStream(Closeable stream) {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException e) {
+ android.util.Log.e("IO", "Could not close stream", e);
+ }
+ }
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/tileprovider/constants/OpenStreetMapTileProviderConstants.java b/cardroid/src/org/andnav/osm/tileprovider/constants/OpenStreetMapTileProviderConstants.java
new file mode 100644
index 0000000..a5eda6f
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/tileprovider/constants/OpenStreetMapTileProviderConstants.java
@@ -0,0 +1,31 @@
+package org.andnav.osm.tileprovider.constants;
+
+import android.os.Environment;
+
+/**
+ *
+ * This class contains constants used by the service.
+ *
+ * @author Neil Boyd
+ *
+ */
+public interface OpenStreetMapTileProviderConstants {
+ // ===========================================================
+ // Final Fields
+ // ===========================================================
+
+ public static final boolean DEBUGMODE = false;
+
+ public static final String TILE_PATH_BASE = Environment.getExternalStorageDirectory() + "/andnav2/tiles/";
+ public static final String TILE_PATH_EXTENSION = ".andnav";
+
+ public static final int NUMBER_OF_TILE_DOWNLOAD_THREADS = 8;
+ public static final int NUMBER_OF_TILE_FILESYSTEM_THREADS = 8;
+
+ public static final int TILE_DOWNLOAD_MAXIMUM_QUEUE_SIZE = 40;
+ public static final int TILE_FILESYSTEM_MAXIMUM_QUEUE_SIZE = 40;
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/util/BoundingBoxE6.java b/cardroid/src/org/andnav/osm/util/BoundingBoxE6.java
new file mode 100644
index 0000000..af18cb1
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/util/BoundingBoxE6.java
@@ -0,0 +1,190 @@
+// Created by plusminus on 19:06:38 - 25.09.2008
+package org.andnav.osm.util;
+
+import static org.andnav.osm.util.MyMath.gudermann;
+import static org.andnav.osm.util.MyMath.gudermannInverse;
+
+import java.util.ArrayList;
+
+import org.andnav.osm.util.constants.OpenStreetMapConstants;
+import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class BoundingBoxE6 implements OpenStreetMapViewConstants, OpenStreetMapConstants {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final int mLatNorthE6;
+ protected final int mLatSouthE6;
+ protected final int mLonEastE6;
+ protected final int mLonWestE6;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public BoundingBoxE6(final int northE6, final int eastE6, final int southE6, final int westE6){
+ this.mLatNorthE6 = northE6;
+ this.mLonEastE6 = eastE6;
+ this.mLatSouthE6 = southE6;
+ this.mLonWestE6 = westE6;
+ }
+
+ public BoundingBoxE6(final double north, final double east, final double south, final double west){
+ this.mLatNorthE6 = (int)(north * 1E6);
+ this.mLonEastE6 = (int)(east * 1E6);
+ this.mLatSouthE6 = (int)(south * 1E6);
+ this.mLonWestE6 = (int)(west * 1E6);
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public int getDiagonalLengthInMeters() {
+ return new GeoPoint(this.mLatNorthE6, this.mLonWestE6).distanceTo(new GeoPoint(this.mLatSouthE6, this.mLonEastE6));
+ }
+
+ public int getLatNorthE6() {
+ return this.mLatNorthE6;
+ }
+
+ public int getLatSouthE6() {
+ return this.mLatSouthE6;
+ }
+
+ public int getLonEastE6() {
+ return this.mLonEastE6;
+ }
+
+ public int getLonWestE6() {
+ return this.mLonWestE6;
+ }
+
+ public int getLatitudeSpanE6() {
+ return Math.abs(this.mLatNorthE6 - this.mLatSouthE6);
+ }
+
+ public int getLongitudeSpanE6() {
+ return Math.abs(this.mLonEastE6 - this.mLonWestE6);
+ }
+ /**
+ *
+ * @param aLatitude
+ * @param aLongitude
+ * @param reuse
+ * @return relative position determined from the upper left corner.<br />
+ * {0,0} would be the upper left corner.
+ * {1,1} would be the lower right corner.
+ * {1,0} would be the lower left corner.
+ * {0,1} would be the upper right corner.
+ */
+ public float[] getRelativePositionOfGeoPointInBoundingBoxWithLinearInterpolation(final int aLatitude, final int aLongitude, final float[] reuse){
+ float[] out = (reuse != null) ? reuse : new float[2];
+ out[MAPTILE_LATITUDE_INDEX] = ((float)(this.mLatNorthE6 - aLatitude) / getLatitudeSpanE6());
+ out[MAPTILE_LONGITUDE_INDEX] = 1 - ((float)(this.mLonEastE6 - aLongitude) / getLongitudeSpanE6());
+ return out;
+ }
+
+ public float[] getRelativePositionOfGeoPointInBoundingBoxWithExactGudermannInterpolation(final int aLatitudeE6, final int aLongitudeE6, final float[] reuse){
+ float[] out = (reuse != null) ? reuse : new float[2];
+ out[MAPTILE_LATITUDE_INDEX] = (float)((gudermannInverse(this.mLatNorthE6 / 1E6) - gudermannInverse(aLatitudeE6 / 1E6)) / (gudermannInverse(this.mLatNorthE6 / 1E6) - gudermannInverse(this.mLatSouthE6 / 1E6)));
+ out[MAPTILE_LONGITUDE_INDEX] = 1 - ((float)(this.mLonEastE6 - aLongitudeE6) / getLongitudeSpanE6());
+ return out;
+ }
+
+ public GeoPoint getGeoPointOfRelativePositionWithLinearInterpolation(final float relX, final float relY) {
+
+ int lat = (int)(this.mLatNorthE6 - (this.getLatitudeSpanE6() * relY));
+
+ int lon = (int)(this.mLonWestE6 + (this.getLongitudeSpanE6() * relX));
+
+ /* Bring into bounds. */
+ while(lat > 90500000)
+ lat -= 90500000;
+ while(lat < -90500000)
+ lat += 90500000;
+
+ /* Bring into bounds. */
+ while(lon > 180000000)
+ lon -= 180000000;
+ while(lon < -180000000)
+ lon += 180000000;
+
+ return new GeoPoint(lat, lon);
+ }
+
+ public GeoPoint getGeoPointOfRelativePositionWithExactGudermannInterpolation(final float relX, final float relY) {
+
+ final double gudNorth = gudermannInverse(this.mLatNorthE6 / 1E6);
+ final double gudSouth = gudermannInverse(this.mLatSouthE6 / 1E6);
+ final double latD = gudermann((gudSouth + (1-relY) * (gudNorth - gudSouth)));
+ int lat = (int)(latD * 1E6);
+
+ int lon = (int)((this.mLonWestE6 + (this.getLongitudeSpanE6() * relX)));
+
+ /* Bring into bounds. */
+ while(lat > 90500000)
+ lat -= 90500000;
+ while(lat < -90500000)
+ lat += 90500000;
+
+ /* Bring into bounds. */
+ while(lon > 180000000)
+ lon -= 180000000;
+ while(lon < -180000000)
+ lon += 180000000;
+
+ return new GeoPoint(lat, lon);
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ public String toString(){
+ return new StringBuffer()
+ .append("N:").append(this.mLatNorthE6)
+ .append("; E:").append(this.mLonEastE6)
+ .append("; S:").append(this.mLatSouthE6)
+ .append("; W:").append(this.mLonWestE6)
+ .toString();
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ public static BoundingBoxE6 fromGeoPoints(final ArrayList<? extends GeoPoint> partialPolyLine) {
+ int minLat = Integer.MAX_VALUE;
+ int minLon = Integer.MAX_VALUE;
+ int maxLat = Integer.MIN_VALUE;
+ int maxLon = Integer.MIN_VALUE;
+ for (GeoPoint gp : partialPolyLine) {
+ final int latitudeE6 = gp.getLatitudeE6();
+ final int longitudeE6 = gp.getLongitudeE6();
+
+ minLat = Math.min(minLat, latitudeE6);
+ minLon = Math.min(minLon, longitudeE6);
+ maxLat = Math.max(maxLat, latitudeE6);
+ maxLon = Math.max(maxLon, longitudeE6);
+ }
+
+ return new BoundingBoxE6(minLat, minLon, maxLat, maxLon);
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
+
diff --git a/cardroid/src/org/andnav/osm/util/GeoPoint.java b/cardroid/src/org/andnav/osm/util/GeoPoint.java
new file mode 100644
index 0000000..383fb21
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/util/GeoPoint.java
@@ -0,0 +1,138 @@
+// Created by plusminus on 21:28:12 - 25.09.2008
+package org.andnav.osm.util;
+
+import org.andnav.osm.util.constants.GeoConstants;
+import org.andnav.osm.views.util.constants.MathConstants;
+
+import android.location.Location;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class GeoPoint implements MathConstants, GeoConstants{
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ private int mLongitudeE6;
+ private int mLatitudeE6;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public GeoPoint(final int aLatitudeE6, final int aLongitudeE6) {
+ this.mLatitudeE6 = aLatitudeE6;
+ this.mLongitudeE6 = aLongitudeE6;
+ }
+
+ public GeoPoint(final double aLatitude, final double aLongitude) {
+ this.mLatitudeE6 = (int)(aLatitude * 1E6);
+ this.mLongitudeE6 = (int)(aLongitude * 1E6);
+ }
+
+ public GeoPoint(Location aLocation) {
+ this(aLocation.getLatitude(), aLocation.getLongitude());
+ }
+
+
+ protected static GeoPoint fromDoubleString(final String s, final char spacer) {
+ final int spacerPos = s.indexOf(spacer);
+ return new GeoPoint((int) (Double.parseDouble(s.substring(0,
+ spacerPos - 1)) * 1E6), (int) (Double.parseDouble(s.substring(
+ spacerPos + 1, s.length())) * 1E6));
+ }
+
+ public static GeoPoint fromIntString(final String s){
+ final int commaPos = s.indexOf(',');
+ return new GeoPoint(Integer.parseInt(s.substring(0,commaPos-1)),
+ Integer.parseInt(s.substring(commaPos+1,s.length())));
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public int getLongitudeE6() {
+ return this.mLongitudeE6;
+ }
+
+ public int getLatitudeE6() {
+ return this.mLatitudeE6;
+ }
+
+ public void setLongitudeE6(final int aLongitudeE6) {
+ this.mLongitudeE6 = aLongitudeE6;
+ }
+
+ public void setLatitudeE6(final int aLatitudeE6) {
+ this.mLatitudeE6 = aLatitudeE6;
+ }
+
+ public void setCoordsE6(final int aLatitudeE6, final int aLongitudeE6) {
+ this.mLatitudeE6 = aLatitudeE6;
+ this.mLongitudeE6 = aLongitudeE6;
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ public String toString(){
+ return new StringBuilder().append(this.mLatitudeE6).append(",").append(this.mLongitudeE6).toString();
+ }
+
+ public String toDoubleString() {
+ return new StringBuilder().append(this.mLatitudeE6 / 1E6).append(",").append(this.mLongitudeE6 / 1E6).toString();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if(!(obj instanceof GeoPoint))
+ return false;
+ GeoPoint g = (GeoPoint)obj;
+ return g.mLatitudeE6 == this.mLatitudeE6 && g.mLongitudeE6 == this.mLongitudeE6;
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ /**
+ * @see Source@ http://www.geocities.com/DrChengalva/GPSDistance.html
+ * @param gpA
+ * @param gpB
+ * @return distance in meters
+ */
+ public int distanceTo(final GeoPoint other) {
+
+ final double a1 = DEG2RAD * (this.mLatitudeE6 / 1E6);
+ final double a2 = DEG2RAD * (this.mLongitudeE6 / 1E6);
+ final double b1 = DEG2RAD * (other.mLatitudeE6 / 1E6);
+ final double b2 = DEG2RAD * (other.mLongitudeE6 / 1E6);
+
+ final double cosa1 = Math.cos(a1);
+ final double cosb1 = Math.cos(b1);
+
+ final double t1 = cosa1*Math.cos(a2)*cosb1*Math.cos(b2);
+
+ final double t2 = cosa1*Math.sin(a2)*cosb1*Math.sin(b2);
+
+ final double t3 = Math.sin(a1)*Math.sin(b1);
+
+ final double tt = Math.acos( t1 + t2 + t3 );
+
+ return (int)(RADIUS_EARTH_METERS*tt);
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/util/MyMath.java b/cardroid/src/org/andnav/osm/util/MyMath.java
new file mode 100644
index 0000000..d54f937
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/util/MyMath.java
@@ -0,0 +1,59 @@
+// Created by plusminus on 20:36:01 - 26.09.2008
+package org.andnav.osm.util;
+
+import org.andnav.osm.views.util.constants.MathConstants;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class MyMath implements MathConstants {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+
+ public static double gudermannInverse(double aLatitude){
+ return Math.log(Math.tan(PI_4 + (DEG2RAD * aLatitude / 2)));
+ }
+
+ public static double gudermann(double y){
+ return RAD2DEG * Math.atan(Math.sinh(y));
+ }
+
+
+ public static int mod(int number, final int modulus){
+ if(number > 0)
+ return number % modulus;
+
+ while(number < 0)
+ number += modulus;
+
+ return number;
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/util/NetworkLocationIgnorer.java b/cardroid/src/org/andnav/osm/util/NetworkLocationIgnorer.java
new file mode 100644
index 0000000..393b90b
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/util/NetworkLocationIgnorer.java
@@ -0,0 +1,44 @@
+package org.andnav.osm.util;
+
+import android.location.LocationManager;
+
+/**
+ *
+ * A class to check whether we want to use a location.
+ * If there are multiple location providers, i.e. network and GPS,
+ * then you want to ignore network locations shortly after a GPS location
+ * because you will get another GPS location soon.
+ *
+ * @author Neil Boyd
+ *
+ */
+public class NetworkLocationIgnorer {
+
+ /**
+ * The time we wait after the last gps location before displaying
+ * a non-gps location.
+ */
+ private static final long GPS_WAIT_TIME = 20000; // 20 seconds
+
+ /** last time we got a location from the gps provider */
+ private long mLastGps = 0;
+
+ /**
+ * Whether we should ignore this location.
+ * @param pProvider the provider that provided the location
+ * @param pTime the time of the location
+ * @return true if we should ignore this location, false if not
+ */
+ public boolean shouldIgnore(final String pProvider, final long pTime) {
+
+ if (LocationManager.GPS_PROVIDER.equals(pProvider)) {
+ mLastGps = pTime;
+ } else {
+ if (pTime < mLastGps + GPS_WAIT_TIME) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/cardroid/src/org/andnav/osm/util/constants/GeoConstants.java b/cardroid/src/org/andnav/osm/util/constants/GeoConstants.java
new file mode 100644
index 0000000..aa701d6
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/util/constants/GeoConstants.java
@@ -0,0 +1,15 @@
+// Created by plusminus on 17:41:55 - 16.10.2008
+package org.andnav.osm.util.constants;
+
+
+public interface GeoConstants {
+ // ===========================================================
+ // Final Fields
+ // ===========================================================
+
+ public static final int RADIUS_EARTH_METERS = 6378140;
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+}
\ No newline at end of file
diff --git a/cardroid/src/org/andnav/osm/util/constants/OpenStreetMapConstants.java b/cardroid/src/org/andnav/osm/util/constants/OpenStreetMapConstants.java
new file mode 100644
index 0000000..0b864b4
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/util/constants/OpenStreetMapConstants.java
@@ -0,0 +1,32 @@
+// Created by plusminus on 23:11:31 - 22.09.2008
+package org.andnav.osm.util.constants;
+
+/**
+ *
+ * This class contains constants used by the sample applications.
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public interface OpenStreetMapConstants {
+ // ===========================================================
+ // Final Fields
+ // ===========================================================
+
+ public static final String DEBUGTAG = "OPENSTREETMAP";
+
+ public static final int NOT_SET = Integer.MIN_VALUE;
+
+ public static final String PREFS_NAME = "org.andnav.osm.prefs";
+ public static final String PREFS_RENDERER = "renderer";
+ public static final String PREFS_SCROLL_X = "scrollX";
+ public static final String PREFS_SCROLL_Y = "scrollY";
+ public static final String PREFS_ZOOM_LEVEL = "zoomLevel";
+ public static final String PREFS_SHOW_LOCATION = "showLocation";
+ public static final String PREFS_FOLLOW_LOCATION = "followLocation";
+
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/OpenStreetMapView.java b/cardroid/src/org/andnav/osm/views/OpenStreetMapView.java
new file mode 100644
index 0000000..52e64ff
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/OpenStreetMapView.java
@@ -0,0 +1,1145 @@
+// Created by plusminus on 17:45:56 - 25.09.2008
+package org.andnav.osm.views;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.andnav.osm.util.BoundingBoxE6;
+import org.andnav.osm.util.GeoPoint;
+import org.andnav.osm.views.overlay.OpenStreetMapTilesOverlay;
+import org.andnav.osm.views.overlay.OpenStreetMapViewOverlay;
+import org.andnav.osm.views.overlay.OpenStreetMapViewOverlay.Snappable;
+import org.andnav.osm.views.util.Mercator;
+import org.andnav.osm.views.util.OpenStreetMapRendererInfo;
+import org.andnav.osm.views.util.OpenStreetMapTileProvider;
+import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Matrix;
+import android.graphics.Paint;
+import android.graphics.Path;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.graphics.Bitmap.Config;
+import android.graphics.Paint.Style;
+import android.util.AttributeSet;
+import android.util.FloatMath;
+import android.util.Log;
+import android.view.GestureDetector;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.GestureDetector.OnGestureListener;
+import android.view.animation.AnimationUtils;
+import android.view.animation.Interpolator;
+import android.view.animation.LinearInterpolator;
+import android.widget.Scroller;
+import android.widget.ZoomButtonsController;
+import android.widget.ZoomButtonsController.OnZoomListener;
+
+public class OpenStreetMapView extends View implements OpenStreetMapViewConstants {
+
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ final static OpenStreetMapRendererInfo DEFAULTRENDERER = OpenStreetMapRendererInfo.MAPNIK;
+ final static String BUNDLE_RENDERER = "org.andnav.osm.views.OpenStreetMapView.RENDERER";
+ final static String BUNDLE_SCROLL_X = "org.andnav.osm.views.OpenStreetMapView.SCROLL_X";
+ final static String BUNDLE_SCROLL_Y = "org.andnav.osm.views.OpenStreetMapView.SCROLL_Y";
+ final static String BUNDLE_ZOOM_LEVEL = "org.andnav.osm.views.OpenStreetMapView.ZOOM";
+
+ private static final int MULTI_NONE = 0;
+ private static final int MULTI_ACTIVE = 1;
+ private static final int MULTI_HANDLED = 2;
+
+ private float mPointerDownDistance; /* distance for a ACTION_POINTER_DOWN MotionEvent */
+ private int mMultiMode = MULTI_NONE; /* if we are in after an ACTION_POINTER_DOWN */
+
+ // get API level 5 MotionEvent constants by reflection
+ // TODO can remove this stuff if we upgrade to API level 5
+ private static int ACTION_MASK = 255;
+ private static int ACTION_POINTER_DOWN = 5;
+ private static int ACTION_POINTER_UP = 6;
+ private static Method MotionEvent_getX;
+ private static Method MotionEvent_getY;
+ static {
+ final MotionEvent me = MotionEvent.obtain(0, 0, 0, 0f, 0f, 0);
+ try {
+ ACTION_MASK = MotionEvent.class.getField("ACTION_MASK").getInt(me);
+ } catch (final Exception e) {}
+ try {
+ ACTION_POINTER_DOWN = MotionEvent.class.getField("ACTION_POINTER_DOWN").getInt(me);
+ } catch (final Exception e) {}
+ try {
+ ACTION_POINTER_UP = MotionEvent.class.getField("ACTION_POINTER_UP").getInt(me);
+ } catch (final Exception e) {}
+ try {
+ MotionEvent_getX = MotionEvent.class.getMethod("getX", new Class[] { int.class });
+ } catch (final Exception e) {}
+ try {
+ MotionEvent_getY = MotionEvent.class.getMethod("getY", new Class[] { int.class });
+ } catch (final Exception e) {}
+ }
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected int mZoomLevel = 0; /** Current zoom level for map tiles */
+ protected final List<OpenStreetMapViewOverlay> mOverlays = new ArrayList<OpenStreetMapViewOverlay>();
+
+ protected Bitmap mBackBuffer;
+ protected Canvas mBackCanvas;
+ protected Matrix mTrans = new Matrix();
+ protected final Paint mPaint = new Paint();
+ private OpenStreetMapViewProjection mProjection;
+
+ private OpenStreetMapView mMiniMap, mMaxiMap;
+ private final OpenStreetMapTilesOverlay mMapOverlay;
+
+ private final GestureDetector mGestureDetector = new GestureDetector(new OpenStreetMapViewGestureDetectorListener());
+ final Scroller mScroller; /** Handles map scrolling */
+ final Scaler mScaler;
+ private OpenStreetMapViewController mController;
+ private int mMiniMapOverriddenVisibility = NOT_SET;
+ private int mMiniMapZoomDiff = NOT_SET;
+
+ private ZoomButtonsController mZoomController;
+ private boolean mEnableZoomController = false;
+
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ private OpenStreetMapView(final Context context, AttributeSet attrs,
+ final OpenStreetMapRendererInfo aRendererInfo,
+ final OpenStreetMapTileProvider aTileProvider) {
+ super(context, attrs);
+ this.mController = new OpenStreetMapViewController(this);
+ this.mScroller = new Scroller(context);
+ this.mScaler = new Scaler(context, new LinearInterpolator());
+ this.mMapOverlay = new OpenStreetMapTilesOverlay(this, aRendererInfo, aTileProvider);
+ mOverlays.add(this.mMapOverlay);
+ this.mZoomController = new ZoomButtonsController(this);
+ this.mZoomController.setOnZoomListener(new OpenStreetMapViewZoomListener());
+ }
+
+ /**
+ * XML Constructor (uses default Renderer)
+ */
+ public OpenStreetMapView(Context context, AttributeSet attrs) {
+ this(context, attrs, DEFAULTRENDERER, null);
+ }
+
+ /**
+ * Standard Constructor for {@link OpenStreetMapView}.
+ *
+ * @param context
+ * @param aRendererInfo
+ * pass a {@link OpenStreetMapRendererInfo} you like.
+ */
+ public OpenStreetMapView(final Context context, final OpenStreetMapRendererInfo aRendererInfo) {
+ this(context, null, aRendererInfo, null);
+ }
+
+ /**
+ *
+ * @param context
+ * @param aRendererInfo
+ * pass a {@link OpenStreetMapRendererInfo} you like.
+ * @param osmv
+ * another {@link OpenStreetMapView}, to share the TileProvider
+ * with.<br/>
+ * May significantly improve the render speed, when using the
+ * same {@link OpenStreetMapRendererInfo}.
+ */
+ public OpenStreetMapView(final Context context,
+ final OpenStreetMapRendererInfo aRendererInfo,
+ final OpenStreetMapView aMapToShareTheTileProviderWith) {
+ this(context, null, aRendererInfo, /* TODO aMapToShareTheTileProviderWith.mTileProvider */ null);
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ /**
+ * This MapView takes control of the {@link OpenStreetMapView} passed as
+ * parameter.<br />
+ * I.e. it zoomes it to x levels less than itself and centers it the same
+ * coords.<br />
+ * Its pretty usefull when the MiniMap uses the same TileProvider.
+ *
+ * @see OpenStreetMapView.OpenStreetMapView(
+ * @param aOsmvMinimap
+ * @param aZoomDiff
+ * 3 is a good Value. Pass {@link OpenStreetMapViewConstants}
+ * .NOT_SET to disable autozooming of the minimap.
+ */
+ public void setMiniMap(final OpenStreetMapView aOsmvMinimap, final int aZoomDiff) {
+ this.mMiniMapZoomDiff = aZoomDiff;
+ this.mMiniMap = aOsmvMinimap;
+ aOsmvMinimap.setMaxiMap(this);
+
+ // TODO Synchronize the Views.
+// this.setMapCenter(this.mLatitudeE6, this.mLongitudeE6);
+// this.setZoomLevel(this.getZoomLevel());
+ }
+
+ public boolean hasMiniMap() {
+ return this.mMiniMap != null;
+ }
+
+ /**
+ * @return {@link View}.GONE or {@link View}.VISIBLE or {@link View}
+ * .INVISIBLE or {@link OpenStreetMapViewConstants}.NOT_SET
+ * */
+ public int getOverrideMiniMapVisiblity() {
+ return this.mMiniMapOverriddenVisibility;
+ }
+
+ /**
+ * Use this method if you want to make the MiniMap visible i.e.: always or
+ * never. Use {@link View}.GONE , {@link View}.VISIBLE, {@link View}
+ * .INVISIBLE. Use {@link OpenStreetMapViewConstants}.NOT_SET to reset this
+ * feature.
+ *
+ * @param aVisiblity
+ */
+ public void setOverrideMiniMapVisiblity(final int aVisiblity) {
+ switch (aVisiblity) {
+ case View.GONE:
+ case View.VISIBLE:
+ case View.INVISIBLE:
+ if (this.mMiniMap != null)
+ this.mMiniMap.setVisibility(aVisiblity);
+ case NOT_SET:
+ this.setZoomLevel(this.mZoomLevel);
+ break;
+ default:
+ throw new IllegalArgumentException("See javadoc of this method !!!");
+ }
+ this.mMiniMapOverriddenVisibility = aVisiblity;
+ }
+
+ protected void setMaxiMap(final OpenStreetMapView aOsmvMaxiMap) {
+ this.mMaxiMap = aOsmvMaxiMap;
+ }
+
+ public OpenStreetMapViewController getController() {
+ return this.mController;
+ }
+
+ /**
+ * You can add/remove/reorder your Overlays using the List of
+ * {@link OpenStreetMapViewOverlay}. The first (index 0) Overlay gets drawn
+ * first, the one with the highest as the last one.
+ */
+ public List<OpenStreetMapViewOverlay> getOverlays() {
+ return this.mOverlays;
+ }
+
+ public double getLatitudeSpan() {
+ return this.getDrawnBoundingBoxE6().getLongitudeSpanE6() / 1E6;
+ }
+
+ public int getLatitudeSpanE6() {
+ return this.getDrawnBoundingBoxE6().getLatitudeSpanE6();
+ }
+
+ public double getLongitudeSpan() {
+ return this.getDrawnBoundingBoxE6().getLongitudeSpanE6() / 1E6;
+ }
+
+ public int getLongitudeSpanE6() {
+ return this.getDrawnBoundingBoxE6().getLatitudeSpanE6();
+ }
+
+ public BoundingBoxE6 getDrawnBoundingBoxE6() {
+ return getBoundingBox(this.getWidth(), this.getHeight());
+ }
+
+ public BoundingBoxE6 getVisibleBoundingBoxE6() {
+// final ViewParent parent = this.getParent();
+// if(parent instanceof RotateView){
+// final RotateView par = (RotateView)parent;
+// return getBoundingBox(par.getMeasuredWidth(), par.getMeasuredHeight());
+// }else{
+ return getBoundingBox(this.getWidth(), this.getHeight());
+// }
+ }
+
+ private BoundingBoxE6 getBoundingBox(final int pViewWidth, final int pViewHeight){
+ final int mapTileZoom = mMapOverlay.getRendererInfo().MAPTILE_ZOOM;
+ final int world_2 = (1 << mZoomLevel + mapTileZoom - 1);
+ final int north = world_2 + getScrollY() - getHeight()/2;
+ final int south = world_2 + getScrollY() + getHeight()/2;
+ final int west = world_2 + getScrollX() - getWidth()/2;
+ final int east = world_2 + getScrollX() + getWidth()/2;
+
+ return Mercator.getBoundingBoxFromCoords(west, north, east, south, mZoomLevel + mapTileZoom);
+ }
+
+ /**
+ * This class is only meant to be used during on call of onDraw(). Otherwise
+ * it may produce strange results.
+ *
+ * @return
+ */
+ public OpenStreetMapViewProjection getProjection() {
+ return mProjection;
+ }
+
+ public void setMapCenter(final GeoPoint aCenter) {
+ this.setMapCenter(aCenter.getLatitudeE6(), aCenter.getLongitudeE6());
+ }
+//
+// public void setMapCenter(final double aLatitude, final double aLongitude) {
+// this.setMapCenter((int) (aLatitude * 1E6), (int) (aLongitude * 1E6));
+// }
+//
+ public void setMapCenter(final int aLatitudeE6, final int aLongitudeE6) {
+ this.setMapCenter(aLatitudeE6, aLongitudeE6, true);
+ }
+
+ protected void setMapCenter(final int aLatitudeE6, final int aLongitudeE6,
+ final boolean doPassFurther) {
+ if (doPassFurther && this.mMiniMap != null)
+ this.mMiniMap.setMapCenter(aLatitudeE6, aLongitudeE6, false);
+ else if (this.mMaxiMap != null)
+ this.mMaxiMap.setMapCenter(aLatitudeE6, aLongitudeE6, false);
+
+ final int[] coords = Mercator.projectGeoPoint(aLatitudeE6, aLongitudeE6, getPixelZoomLevel(), null);
+ final int worldSize_2 = getWorldSizePx()/2;
+ if (getAnimation() == null || getAnimation().hasEnded()) {
+ mScroller.startScroll(getScrollX(), getScrollY(),
+ coords[MAPTILE_LONGITUDE_INDEX] - worldSize_2 - getScrollX(),
+ coords[MAPTILE_LATITUDE_INDEX] - worldSize_2 - getScrollY(), 500);
+ postInvalidate();
+ }
+ }
+
+ public OpenStreetMapRendererInfo getRenderer() {
+ return this.mMapOverlay.getRendererInfo();
+ }
+
+ public void setRenderer(final OpenStreetMapRendererInfo aRenderer) {
+ this.mMapOverlay.setRendererInfo(aRenderer);
+ this.checkZoomButtons();
+ postInvalidate();
+ }
+
+ /**
+ * @param aZoomLevel
+ * between 0 (equator) and 18/19(closest), depending on the
+ * Renderer chosen.
+ */
+ protected int setZoomLevel(final int aZoomLevel) {
+ final int minZoomLevel = this.mMapOverlay.getRendererInfo().ZOOM_MINLEVEL;
+ final int maxZoomLevel = this.mMapOverlay.getRendererInfo().ZOOM_MAXLEVEL;
+ final int newZoomLevel = Math.max(minZoomLevel, Math.min(maxZoomLevel, aZoomLevel));
+ final int curZoomLevel = this.mZoomLevel;
+
+ if (this.mMiniMap != null) {
+ if (this.mZoomLevel < this.mMiniMapZoomDiff) {
+ if (this.mMiniMapOverriddenVisibility == NOT_SET)
+ this.mMiniMap.setVisibility(View.INVISIBLE);
+ } else {
+ if (this.mMiniMapOverriddenVisibility == NOT_SET
+ && this.mMiniMap.getVisibility() != View.VISIBLE) {
+ this.mMiniMap.setVisibility(View.VISIBLE);
+ }
+ if (this.mMiniMapZoomDiff != NOT_SET)
+ this.mMiniMap.setZoomLevel(this.mZoomLevel - this.mMiniMapZoomDiff);
+ }
+ }
+
+ this.mZoomLevel = newZoomLevel;
+ this.checkZoomButtons();
+
+ if(newZoomLevel > curZoomLevel)
+ scrollTo(getScrollX()<<(newZoomLevel-curZoomLevel), getScrollY()<<(newZoomLevel-curZoomLevel));
+ else if(newZoomLevel < curZoomLevel)
+ scrollTo(getScrollX()>>(curZoomLevel-newZoomLevel), getScrollY()>>(curZoomLevel-newZoomLevel));
+
+ // TODO snap for all snappables
+ Point snapPoint = new Point();
+ mProjection = new OpenStreetMapViewProjection();
+ for (OpenStreetMapViewOverlay osmvo : this.mOverlays) {
+ if (osmvo instanceof Snappable &&
+ ((Snappable)osmvo).onSnapToItem(getScrollX(), getScrollY(), snapPoint, this)) {
+ scrollTo(snapPoint.x, snapPoint.y);
+ }
+ }
+ return this.mZoomLevel;
+ }
+
+ /**
+ * Get the current ZoomLevel for the map tiles.
+ * @return the current ZoomLevel between 0 (equator) and 18/19(closest),
+ * depending on the Renderer chosen.
+ */
+ public int getZoomLevel() {
+ return this.mZoomLevel;
+ }
+
+ /*
+ * Returns the maximum zoom level for the point currently at the center.
+ * @return The maximum zoom level for the map's current center.
+ */
+ public int getMaxZoomLevel() {
+ return getRenderer().ZOOM_MAXLEVEL;
+ }
+
+ public GeoPoint getMapCenter() {
+ return new GeoPoint(getMapCenterLatitudeE6(), getMapCenterLongitudeE6());
+ }
+
+ public int getMapCenterLatitudeE6() {
+ return (int)(Mercator.tile2lat(getScrollY() + getWorldSizePx()/2, getPixelZoomLevel()) * 1E6);
+ }
+
+ public int getMapCenterLongitudeE6() {
+ return (int)(Mercator.tile2lon(getScrollX() + getWorldSizePx()/2, getPixelZoomLevel()) * 1E6);
+ }
+
+ public void onSaveInstanceState(android.os.Bundle state) {
+ state.putInt(BUNDLE_RENDERER, getRenderer().ordinal());
+ state.putInt(BUNDLE_SCROLL_X, getScrollX());
+ state.putInt(BUNDLE_SCROLL_Y, getScrollY());
+ state.putInt(BUNDLE_ZOOM_LEVEL, getZoomLevel());
+ }
+
+ public void onRestoreInstanceState(android.os.Bundle state) {
+ setRenderer(OpenStreetMapRendererInfo.values()[state.getInt(BUNDLE_RENDERER, 0)]);
+ setZoomLevel(state.getInt(BUNDLE_ZOOM_LEVEL, 1));
+ scrollTo(state.getInt(BUNDLE_SCROLL_X, 0), state.getInt(BUNDLE_SCROLL_Y, 0));
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ public void onLongPress(MotionEvent e) {
+ for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
+ if (osmvo.onLongPress(e, this))
+ return;
+ }
+
+ public boolean onSingleTapUp(MotionEvent e) {
+ for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
+ if (osmvo.onSingleTapUp(e, this)) {
+ postInvalidate();
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
+ if (osmvo.onKeyDown(keyCode, event, this))
+ return true;
+
+ return super.onKeyDown(keyCode, event);
+ }
+
+ @Override
+ public boolean onKeyUp(int keyCode, KeyEvent event) {
+ for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
+ if (osmvo.onKeyUp(keyCode, event, this))
+ return true;
+
+ return super.onKeyUp(keyCode, event);
+ }
+
+ @Override
+ public boolean onTrackballEvent(MotionEvent event) {
+ for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
+ if (osmvo.onTrackballEvent(event, this))
+ return true;
+
+ scrollBy((int)(event.getX() * 25), (int)(event.getY() * 25));
+
+ return super.onTrackballEvent(event);
+ }
+
+ @Override
+ public boolean onTouchEvent(final MotionEvent event) {
+
+ Log.d(DEBUGTAG, "onTouchEvent(" + event + ")");
+
+ /*
+ * handle multi touch events:
+ * 1. mask out the action with the ACTION_MASK
+ * 2. measure the spreading
+ * 3. on ACTION_POINTER_DOWN remember the spreading in the
+ * pointerDownDistance and set multiDown mode to ACTIVE
+ * 4. on first move changing the spreading by a
+ * factor of 2 or a factor of 0.5 increase or
+ * decrease the zoom level
+ * switch off multiDown mode and set it to HANDLED
+ * 5. on ACTION_POINTER_UP also switch off the multiDown mode
+ * 6. in any of these cases: claim the event handled and
+ * return true
+ */
+ final int action = event.getAction() & ACTION_MASK;
+
+ if (action == ACTION_POINTER_DOWN) {
+ mPointerDownDistance = spreading(event);
+ mMultiMode = MULTI_ACTIVE;
+ return true;
+ } else if (action == ACTION_POINTER_UP) {
+ mMultiMode = MULTI_NONE;
+ return true;
+ } else if (mMultiMode != MULTI_NONE) {
+ if (mMultiMode == MULTI_ACTIVE && action == MotionEvent.ACTION_MOVE) {
+ final float pointerUpDistance = spreading(event);
+
+ if (pointerUpDistance > 2 * mPointerDownDistance) {
+ mMultiMode = MULTI_HANDLED;
+ setZoomLevel(mZoomLevel + 1);
+ } else if (pointerUpDistance < 0.5 * mPointerDownDistance) {
+ setZoomLevel(mZoomLevel - 1);
+ mMultiMode = MULTI_HANDLED;
+ }
+ }
+ return true;
+ }
+
+ for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
+ if (osmvo.onTouchEvent(event, this))
+ return true;
+
+ if (this.mGestureDetector.onTouchEvent(event))
+ return true;
+
+ return super.onTouchEvent(event);
+ }
+
+ @Override
+ public void computeScroll() {
+ if (mScroller.computeScrollOffset()) {
+// int oldX = getScrollX();
+// int oldY = getScrollY();
+// int x = mScroller.getCurrX();
+// int y = mScroller.getCurrY();
+// if (x != oldX || y != oldY)
+ if (mScroller.isFinished())
+ mController.onScrollingFinished();
+ else
+ scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
+ postInvalidate(); // Keep on drawing until the animation has finished.
+ }
+ }
+
+ private float spreading(final MotionEvent event) {
+ // TODO can do this directly if we upgrade to API level 5
+ try {
+ final float x0 = Float.valueOf(MotionEvent_getX.invoke(event, 0).toString());
+ final float x1 = Float.valueOf(MotionEvent_getX.invoke(event, 1).toString());
+ final float y0 = Float.valueOf(MotionEvent_getY.invoke(event, 0).toString());
+ final float y1 = Float.valueOf(MotionEvent_getY.invoke(event, 1).toString());
+ final float x = x0 - x1;
+ final float y = y0 - y1;
+ return FloatMath.sqrt(x * x + y * y);
+ } catch(final Exception e) {
+ return 1;
+ }
+ }
+
+ private void computeScale() {
+ if (mScaler.computeScale()) {
+ if (mScaler.isFinished())
+ mController.onScalingFinished();
+ else
+ postInvalidate();
+ }
+ }
+
+ @Override
+ public void scrollTo(int x, int y) {
+ final int worldSize = getWorldSizePx();
+ x %= worldSize;
+ y %= worldSize;
+ super.scrollTo(x, y);
+ }
+
+ @Override
+ protected void onSizeChanged(int w, int h, int oldw, int oldh) {
+ if(this.mBackBuffer != null) {
+ this.mBackBuffer.recycle();
+ this.mBackBuffer = null;
+ }
+ this.mBackBuffer = Bitmap.createBitmap(w, h, Config.ARGB_8888);
+ this.mBackCanvas = new Canvas(this.mBackBuffer);
+ super.onSizeChanged(w, h, oldw, oldh);
+ }
+
+ @Override
+ public void onDraw(final Canvas c) {
+ final long startMs = System.currentTimeMillis();
+
+ mProjection = new OpenStreetMapViewProjection();
+
+ c.translate(getWidth()/2, getHeight()/2);
+ if (!mScaler.isFinished()) {
+ Matrix m = c.getMatrix();
+ m.preScale(mScaler.mCurrScale, mScaler.mCurrScale, getScrollX(), getScrollY());
+ c.setMatrix(m);
+ }
+
+ /* Draw background */
+ c.drawColor(Color.LTGRAY);
+// This is to slow:
+// final Rect r = c.getClipBounds();
+// mPaint.setColor(Color.GRAY);
+// mPaint.setPathEffect(new DashPathEffect(new float[] {1, 1}, 0));
+// for (int x = r.left; x < r.right; x += 20)
+// c.drawLine(x, r.top, x, r.bottom, mPaint);
+// for (int y = r.top; y < r.bottom; y += 20)
+// c.drawLine(r.left, y, r.right, y, mPaint);
+
+ /* Draw all Overlays. */
+ for (OpenStreetMapViewOverlay osmvo : this.mOverlays)
+ osmvo.onManagedDraw(c, this);
+
+ if (this.mMaxiMap != null) { // If this is a MiniMap
+ this.mPaint.setColor(Color.RED);
+ this.mPaint.setStyle(Style.STROKE);
+ final int viewWidth = this.getWidth();
+ final int viewHeight = this.getHeight();
+ c.drawRect(0, 0, viewWidth, viewHeight, this.mPaint);
+ }
+
+ final long endMs = System.currentTimeMillis();
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "Rendering overall: " + (endMs - startMs) + "ms");
+ computeScale();
+ }
+
+ @Override
+ protected void onDetachedFromWindow() {
+ this.mZoomController.setVisible(false);
+ this.mMapOverlay.detach();
+ super.onDetachedFromWindow();
+ }
+
+ // ===========================================================
+ // Package Methods
+ // ===========================================================
+
+ /**
+ * Get the world size in pixels.
+ */
+ int getWorldSizePx() {
+ return (1 << getPixelZoomLevel());
+ }
+
+ /**
+ * Get the equivalent zoom level on pixel scale
+ */
+ int getPixelZoomLevel() {
+ return this.mZoomLevel + this.mMapOverlay.getRendererInfo().MAPTILE_ZOOM;
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ private void checkZoomButtons() {
+ final int maxZoomLevel = this.mMapOverlay.getRendererInfo().ZOOM_MAXLEVEL;
+ this.mZoomController.setZoomInEnabled(mZoomLevel < maxZoomLevel);
+ this.mZoomController.setZoomOutEnabled(mZoomLevel > 0);
+ }
+
+ private int[] getCenterMapTileCoords() {
+ final int mapTileZoom = this.mMapOverlay.getRendererInfo().MAPTILE_ZOOM;
+ final int worldTiles_2 = 1 << (mZoomLevel-1);
+ // convert to tile coordinate and make positive
+ return new int[] { (getScrollY() >> mapTileZoom) + worldTiles_2,
+ (getScrollX() >> mapTileZoom) + worldTiles_2 };
+ }
+
+ /**
+ * @param centerMapTileCoords
+ * @param tileSizePx
+ * @param reuse
+ * just pass null if you do not have a Point to be 'recycled'.
+ */
+ private Point getUpperLeftCornerOfCenterMapTileInScreen(final int[] centerMapTileCoords,
+ final int tileSizePx, final Point reuse) {
+ final Point out = (reuse != null) ? reuse : new Point();
+
+ final int worldTiles_2 = 1 << (mZoomLevel-1);
+ final int centerMapTileScreenLeft = (centerMapTileCoords[MAPTILE_LONGITUDE_INDEX] - worldTiles_2) * tileSizePx - tileSizePx/2;
+ final int centerMapTileScreenTop = (centerMapTileCoords[MAPTILE_LATITUDE_INDEX] - worldTiles_2) * tileSizePx - tileSizePx/2;
+
+ out.set(centerMapTileScreenLeft, centerMapTileScreenTop);
+ return out;
+ }
+
+ public void setBuiltInZoomControls(boolean on) {
+ this.mEnableZoomController = on;
+ this.checkZoomButtons();
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+
+ /**
+ * This class may return valid results until the underlying
+ * {@link OpenStreetMapView} gets modified in any way (i.e. new center).
+ *
+ * @author Nicolas Gramlich
+ * @author Manuel Stahl
+ */
+ public class OpenStreetMapViewProjection {
+
+ private final int viewWidth_2 = getWidth() / 2;
+ private final int viewHeight_2 = getHeight() / 2;
+ private final int worldSize_2 = getWorldSizePx()/2;
+ private final int offsetX = - worldSize_2;
+ private final int offsetY = - worldSize_2;
+
+ private final BoundingBoxE6 bb;
+ private final int zoomLevel;
+ private final int tileSizePx;
+ private final int[] centerMapTileCoords;
+ private final Point upperLeftCornerOfCenterMapTile;
+
+ private final int[] reuseInt2 = new int[2];
+
+ public OpenStreetMapViewProjection() {
+
+ /*
+ * Do some calculations and drag attributes to local variables to
+ * save some performance.
+ */
+ zoomLevel = OpenStreetMapView.this.mZoomLevel; // TODO Draw to
+ // attributes and so
+ // make it only
+ // 'valid' for a
+ // short time.
+ tileSizePx = getRenderer().MAPTILE_SIZEPX;
+
+ /*
+ * Get the center MapTile which is above this.mLatitudeE6 and
+ * this.mLongitudeE6 .
+ */
+ centerMapTileCoords = getCenterMapTileCoords();
+ upperLeftCornerOfCenterMapTile = getUpperLeftCornerOfCenterMapTileInScreen(
+ centerMapTileCoords, tileSizePx, null);
+
+ bb = OpenStreetMapView.this.getDrawnBoundingBoxE6();
+ }
+
+ /**
+ * Converts x/y ScreenCoordinates to the underlying GeoPoint.
+ *
+ * @param x
+ * @param y
+ * @return GeoPoint under x/y.
+ */
+ public GeoPoint fromPixels(float x, float y) {
+ return bb.getGeoPointOfRelativePositionWithLinearInterpolation(x / viewWidth_2, y
+ / viewHeight_2);
+ }
+
+ public Point fromMapPixels(int x, int y, Point reuse) {
+ final Point out = (reuse != null) ? reuse : new Point();
+ out.set(x - viewWidth_2, y - viewHeight_2);
+ out.offset(getScrollX(), getScrollY());
+ return out;
+ }
+
+ private static final int EQUATORCIRCUMFENCE = 40075004;
+
+ public float metersToEquatorPixels(final float aMeters) {
+ return aMeters / EQUATORCIRCUMFENCE * getWorldSizePx();
+ }
+
+ /**
+ * Converts a GeoPoint to its ScreenCoordinates. <br/>
+ * <br/>
+ * <b>CAUTION</b> ! Conversion currently has a large error on
+ * <code>zoomLevels <= 7</code>.<br/>
+ * The Error on ZoomLevels higher than 7, the error is below
+ * <code>1px</code>.<br/>
+ * TODO: Add a linear interpolation to minimize this error.
+ *
+ * <PRE>
+ * Zoom Error(m) Error(px)
+ * 11 6m 1/12px
+ * 10 24m 1/6px
+ * 8 384m 1/2px
+ * 6 6144m 3px
+ * 4 98304m 10px
+ * </PRE>
+ *
+ * @param in
+ * the GeoPoint you want the onScreenCoordinates of.
+ * @param reuse
+ * just pass null if you do not have a Point to be
+ * 'recycled'.
+ * @return the Point containing the approximated ScreenCoordinates of
+ * the GeoPoint passed.
+ */
+ public Point toMapPixels(final GeoPoint in, final Point reuse) {
+ final Point out = (reuse != null) ? reuse : new Point();
+
+ final int[] coords = Mercator.projectGeoPoint(in.getLatitudeE6(), in.getLongitudeE6(), getPixelZoomLevel(), null);
+ out.set(coords[MAPTILE_LONGITUDE_INDEX], coords[MAPTILE_LATITUDE_INDEX]);
+ out.offset(offsetX, offsetY);
+ return out;
+ }
+
+ /**
+ * Performs only the first computationally heavy part of the projection, needToCall toMapPixelsTranslated to get final position.
+ * @param latituteE6
+ * the latitute of the point
+ * @param longitudeE6
+ * the longitude of the point
+ * @param reuse
+ * just pass null if you do not have a Point to be
+ * 'recycled'.
+ * @return intermediate value to be stored and passed to toMapPixelsTranslated on paint.
+ */
+ public Point toMapPixelsProjected(final int latituteE6, final int longitudeE6, final Point reuse) {
+ final Point out = (reuse != null) ? reuse : new Point();
+
+ //26 is the biggest zoomlevel we can project
+ final int[] coords = Mercator.projectGeoPoint(latituteE6, longitudeE6, 28, this.reuseInt2);
+ out.set(coords[MAPTILE_LONGITUDE_INDEX], coords[MAPTILE_LATITUDE_INDEX]);
+ return out;
+ }
+
+ /**
+ * Performs the second computationally light part of the projection.
+ * @param in
+ * the Point calculated by the toMapPixelsProjected
+ * @param reuse
+ * just pass null if you do not have a Point to be
+ * 'recycled'.
+ * @return the Point containing the approximated ScreenCoordinates of
+ * the initial GeoPoint passed to the toMapPixelsProjected.
+ */
+ public Point toMapPixelsTranslated(final Point in, final Point reuse) {
+ final Point out = (reuse != null) ? reuse : new Point();
+
+ //26 is the biggest zoomlevel we can project
+ int zoomDifference = 28 - getPixelZoomLevel();
+ out.set((in.x >> zoomDifference) + offsetX , (in.y >> zoomDifference) + offsetY );
+ return out;
+ }
+
+
+ /**
+ * Translates a rectangle from screen coordinates to intermediate coordinates.
+ * @param in the rectangle in screen coordinates
+ * @return a rectangle in intermediate coords.
+ */
+ public Rect fromPixelsToProjected(final Rect in)
+ {
+ Rect result = new Rect();
+
+ //26 is the biggest zoomlevel we can project
+ int zoomDifference = 28 - getPixelZoomLevel();
+
+ int x0 = (in.left - offsetX) << zoomDifference;
+ int x1 = (in.right - offsetX) << zoomDifference;
+ int y0 = (in.bottom - offsetX) << zoomDifference;
+ int y1 = (in.top - offsetX) << zoomDifference;
+
+ result.set(Math.min(x0,x1), Math.min(y0,y1), Math.max(x0,x1), Math.max(y0,y1));
+ return result;
+ }
+
+ public Point toPixels(final int[] tileCoords, final Point reuse) {
+ return toPixels(tileCoords[MAPTILE_LONGITUDE_INDEX], tileCoords[MAPTILE_LATITUDE_INDEX], reuse);
+ }
+
+ public Point toPixels(int tileX, int tileY, final Point reuse) {
+ final Point out = (reuse != null) ? reuse : new Point();
+
+ out.set(tileX * tileSizePx, tileY * tileSizePx);
+ out.offset(offsetX, offsetY);
+
+ return out;
+ }
+
+ public Path toPixels(final List<? extends GeoPoint> in, final Path reuse) {
+ return toPixels(in, reuse, true);
+ }
+
+ protected Path toPixels(final List<? extends GeoPoint> in, final Path reuse, final boolean doGudermann)
+ throws IllegalArgumentException {
+ if (in.size() < 2)
+ throw new IllegalArgumentException("List of GeoPoints needs to be at least 2.");
+
+ final Path out = (reuse != null) ? reuse : new Path();
+ out.incReserve(in.size());
+
+ boolean first = true;
+ for (GeoPoint gp : in) {
+ final int[] underGeopointTileCoords = Mercator.projectGeoPoint(gp
+ .getLatitudeE6(), gp.getLongitudeE6(), zoomLevel, null);
+
+ /*
+ * Calculate the Latitude/Longitude on the left-upper
+ * ScreenCoords of the MapTile.
+ */
+ final BoundingBoxE6 bb = Mercator.getBoundingBoxFromMapTile(underGeopointTileCoords,
+ zoomLevel);
+
+ final float[] relativePositionInCenterMapTile;
+ if (doGudermann && zoomLevel < 7)
+ relativePositionInCenterMapTile = bb
+ .getRelativePositionOfGeoPointInBoundingBoxWithExactGudermannInterpolation(
+ gp.getLatitudeE6(), gp.getLongitudeE6(), null);
+ else
+ relativePositionInCenterMapTile = bb
+ .getRelativePositionOfGeoPointInBoundingBoxWithLinearInterpolation(gp
+ .getLatitudeE6(), gp.getLongitudeE6(), null);
+
+ final int tileDiffX = centerMapTileCoords[MAPTILE_LONGITUDE_INDEX]
+ - underGeopointTileCoords[MAPTILE_LONGITUDE_INDEX];
+ final int tileDiffY = centerMapTileCoords[MAPTILE_LATITUDE_INDEX]
+ - underGeopointTileCoords[MAPTILE_LATITUDE_INDEX];
+ final int underGeopointTileScreenLeft = upperLeftCornerOfCenterMapTile.x
+ - (tileSizePx * tileDiffX);
+ final int underGeopointTileScreenTop = upperLeftCornerOfCenterMapTile.y
+ - (tileSizePx * tileDiffY);
+
+ final int x = underGeopointTileScreenLeft
+ + (int) (relativePositionInCenterMapTile[MAPTILE_LONGITUDE_INDEX] * tileSizePx);
+ final int y = underGeopointTileScreenTop
+ + (int) (relativePositionInCenterMapTile[MAPTILE_LATITUDE_INDEX] * tileSizePx);
+
+ /* Add up the offset caused by touch. */
+ if (first)
+ out.moveTo(x, y);
+// out.moveTo(x + OpenStreetMapView.this.mTouchMapOffsetX, y
+// + OpenStreetMapView.this.mTouchMapOffsetY);
+ else
+ out.lineTo(x, y);
+ first = false;
+ }
+
+ return out;
+ }
+ }
+
+ private class OpenStreetMapViewGestureDetectorListener implements OnGestureListener {
+
+ @Override
+ public boolean onDown(MotionEvent e) {
+ mZoomController.setVisible(mEnableZoomController);
+ return true;
+ }
+
+ @Override
+ public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
+ final int worldSize = getWorldSizePx();
+ mScroller.fling(getScrollX(), getScrollY(), (int)-velocityX, (int)-velocityY, -worldSize, worldSize, -worldSize, worldSize);
+ return true;
+ }
+
+ @Override
+ public void onLongPress(MotionEvent e) {
+ OpenStreetMapView.this.onLongPress(e);
+ }
+
+ @Override
+ public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
+ scrollBy((int)distanceX, (int)distanceY);
+ return true;
+ }
+
+ @Override
+ public void onShowPress(MotionEvent e) {
+ }
+
+ @Override
+ public boolean onSingleTapUp(MotionEvent e) {
+ return OpenStreetMapView.this.onSingleTapUp(e);
+ }
+
+ }
+
+ private class OpenStreetMapViewZoomListener implements OnZoomListener {
+ @Override
+ public void onZoom(boolean zoomIn) {
+ if(zoomIn)
+ getController().zoomIn();
+ else
+ getController().zoomOut();
+ }
+ @Override
+ public void onVisibilityChanged(boolean visible) {}
+ }
+
+ class Scaler {
+
+ private float mStartScale;
+ private float mFinalScale;
+ private float mCurrScale;
+
+ private long mStartTime;
+ private int mDuration;
+ private float mDurationReciprocal;
+ private float mDeltaScale;
+ private boolean mFinished;
+ private Interpolator mInterpolator;
+
+ /**
+ * Create a Scaler with the specified interpolator.
+ */
+ public Scaler(Context context, Interpolator interpolator) {
+ mFinished = true;
+ mInterpolator = interpolator;
+ }
+
+ /**
+ *
+ * Returns whether the scaler has finished scaling.
+ *
+ * @return True if the scaler has finished scaling, false otherwise.
+ */
+ public final boolean isFinished() {
+ return mFinished;
+ }
+
+ /**
+ * Force the finished field to a particular value.
+ *
+ * @param finished The new finished value.
+ */
+ public final void forceFinished(boolean finished) {
+ mFinished = finished;
+ }
+
+ /**
+ * Returns how long the scale event will take, in milliseconds.
+ *
+ * @return The duration of the scale in milliseconds.
+ */
+ public final int getDuration() {
+ return mDuration;
+ }
+
+ /**
+ * Returns the current scale factor.
+ *
+ * @return The new scale factor.
+ */
+ public final float getCurrScale() {
+ return mCurrScale;
+ }
+
+ /**
+ * Returns the start scale factor.
+ *
+ * @return The start scale factor.
+ */
+ public final float getStartScale() {
+ return mStartScale;
+ }
+
+ /**
+ * Returns where the scale will end.
+ *
+ * @return The final scale factor.
+ */
+ public final float getFinalScale() {
+ return mFinalScale;
+ }
+
+ /**
+ * Sets the final scale for this scaler.
+ *
+ * @param newScale The new scale factor.
+ */
+ public void setFinalScale(float newScale) {
+ mFinalScale = newScale;
+ mDeltaScale = mFinalScale - mStartScale;
+ mFinished = false;
+ }
+
+
+ /**
+ * Call this when you want to know the new scale. If it returns true,
+ * the animation is not yet finished.
+ */
+ public boolean computeScale() {
+ if (mFinished) {
+ mCurrScale = 1.0f;
+ return false;
+ }
+
+ int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
+
+ if (timePassed < mDuration) {
+ float x = (float)timePassed * mDurationReciprocal;
+
+ x = mInterpolator.getInterpolation(x);
+
+ mCurrScale = mStartScale + x * mDeltaScale;
+ if (mCurrScale == mFinalScale)
+ mFinished = true;
+
+ } else {
+ mCurrScale = mFinalScale;
+ mFinished = true;
+ }
+ return true;
+ }
+
+ /**
+ * Start scaling by providing the starting scale and the final scale.
+ *
+ * @param startX Starting horizontal scroll offset in pixels. Positive
+ * numbers will scroll the content to the left.
+ * @param startY Starting vertical scroll offset in pixels. Positive numbers
+ * will scroll the content up.
+ * @param dx Horizontal distance to travel. Positive numbers will scroll the
+ * content to the left.
+ * @param dy Vertical distance to travel. Positive numbers will scroll the
+ * content up.
+ * @param duration Duration of the scroll in milliseconds.
+ */
+ public void startScale(float startScale, float finalScale, int duration) {
+ mFinished = false;
+ mDuration = duration;
+ mStartTime = AnimationUtils.currentAnimationTimeMillis();
+ mStartScale = startScale;
+ mFinalScale = finalScale;
+ mDeltaScale = finalScale - startScale;
+ mDurationReciprocal = 1.0f / (float) mDuration;
+ }
+
+ /**
+ * Extend the scale animation. This allows a running animation to scale
+ * further and longer, when used with {@link #setFinalScale(float)}.
+ *
+ * @param extend Additional time to scale in milliseconds.
+ * @see #setFinalScale(float)
+ */
+ public void extendDuration(int extend) {
+ int passed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
+ mDuration = passed + extend;
+ mDurationReciprocal = 1.0f / (float)mDuration;
+ mFinished = false;
+ }
+
+ }
+
+}
diff --git a/cardroid/src/org/andnav/osm/views/OpenStreetMapViewController.java b/cardroid/src/org/andnav/osm/views/OpenStreetMapViewController.java
new file mode 100644
index 0000000..f20b836
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/OpenStreetMapViewController.java
@@ -0,0 +1,629 @@
+// Created by plusminus on 21:37:08 - 27.09.2008
+package org.andnav.osm.views;
+
+import org.andnav.osm.util.BoundingBoxE6;
+import org.andnav.osm.util.GeoPoint;
+import org.andnav.osm.views.OpenStreetMapView.Scaler;
+import org.andnav.osm.views.util.MyMath;
+import org.andnav.osm.views.util.Mercator;
+import org.andnav.osm.views.util.constants.MathConstants;
+
+import android.graphics.Point;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ * TODO use same interface as google maps controller
+ */
+public class OpenStreetMapViewController {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ public static final int ANIMATION_SMOOTHNESS_LOW = 4;
+ public static final int ANIMATION_SMOOTHNESS_DEFAULT = 10;
+ public static final int ANIMATION_SMOOTHNESS_HIGH = 20;
+
+ public static final int ANIMATION_DURATION_SHORT = 500;
+ public static final int ANIMATION_DURATION_DEFAULT = 1000;
+ public static final int ANIMATION_DURATION_LONG = 2000;
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ private int mZoomLevel;
+ private final OpenStreetMapView mOsmv;
+ private AbstractAnimationRunner mCurrentAnimationRunner;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public OpenStreetMapViewController(final OpenStreetMapView osmv) {
+ this.mOsmv = osmv;
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ public void zoomToSpan(BoundingBoxE6 bb) {
+ zoomToSpan(bb.getLatitudeSpanE6(), bb.getLongitudeSpanE6());
+ }
+
+ // TODO rework zoomToSpan
+ public void zoomToSpan(final int reqLatSpan, final int reqLonSpan) {
+ if(reqLatSpan <= 0 || reqLonSpan <= 0 )
+ return;
+
+ final BoundingBoxE6 bb = this.mOsmv.getVisibleBoundingBoxE6();
+ final int curZoomLevel = this.mOsmv.getZoomLevel();
+
+ final int curLatSpan = bb.getLatitudeSpanE6();
+ final int curLonSpan = bb.getLongitudeSpanE6();
+
+ final float diffNeededLat = (float)reqLatSpan / curLatSpan; // i.e. 600/500 = 1,2
+ final float diffNeededLon = (float)reqLonSpan / curLonSpan; // i.e. 300/400 = 0,75
+
+ final float diffNeeded = Math.max(diffNeededLat, diffNeededLon); // i.e. 1,2
+
+ if(diffNeeded > 1){ // Zoom Out
+ this.mOsmv.setZoomLevel(curZoomLevel - MyMath.getNextSquareNumberAbove(diffNeeded));
+ }else if(diffNeeded < 0.5){ // Can Zoom in
+ this.mOsmv.setZoomLevel(curZoomLevel + MyMath.getNextSquareNumberAbove(1 / diffNeeded) - 1);
+ }
+ }
+
+ /**
+ * Start animating the map towards the given point.
+ */
+ public void animateTo(final GeoPoint point) {
+ final int x = mOsmv.getScrollX();
+ final int y = mOsmv.getScrollY();
+ final Point p = Mercator.projectGeoPoint(point, this.mOsmv.getPixelZoomLevel(), null);
+ final int worldSize_2 = this.mOsmv.getWorldSizePx()/2;
+ mOsmv.mScroller.startScroll(x, y, p.x - worldSize_2 - x, p.y - worldSize_2 - y, ANIMATION_DURATION_DEFAULT);
+ mOsmv.postInvalidate();
+ }
+
+ /**
+ * Animates the underlying {@link OpenStreetMapView} that it centers the passed {@link GeoPoint} in the end.
+ * Uses: {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT} and {@link OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT}.
+ * @param gp
+ */
+ public void animateTo(final GeoPoint gp, final AnimationType aAnimationType){
+ animateTo(gp.getLatitudeE6(), gp.getLongitudeE6(), aAnimationType, ANIMATION_DURATION_DEFAULT, ANIMATION_SMOOTHNESS_DEFAULT);
+ }
+
+ /**
+ * Animates the underlying {@link OpenStreetMapView} that it centers the passed {@link GeoPoint} in the end.
+ * @param gp GeoPoint to be centered in the end.
+ * @param aSmoothness steps made during animation. I.e.: {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_LOW}, {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT}, {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_HIGH}
+ * @param aDuration in Milliseconds. I.e.: {@link OpenStreetMapViewController.ANIMATION_DURATION_SHORT}, {@link OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT}, {@link OpenStreetMapViewController.ANIMATION_DURATION_LONG}
+ */
+ public void animateTo(final GeoPoint gp, final AnimationType aAnimationType, final int aSmoothness, final int aDuration){
+ animateTo(gp.getLatitudeE6(), gp.getLongitudeE6(), aAnimationType, aSmoothness, aDuration);
+ }
+
+ /**
+ * Animates the underlying {@link OpenStreetMapView} that it centers the passed coordinates in the end.
+ * Uses: {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT} and {@link OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT}.
+ * @param aLatitudeE6
+ * @param aLongitudeE6
+ */
+ public void animateTo(final int aLatitudeE6, final int aLongitudeE6, final AnimationType aAnimationType){
+ animateTo(aLatitudeE6, aLongitudeE6, aAnimationType, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
+ }
+
+ /**
+ * Animates the underlying {@link OpenStreetMapView} that it centers the passed coordinates in the end.
+ * @param aLatitudeE6
+ * @param aLongitudeE6
+ * @param aSmoothness steps made during animation. I.e.: {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_LOW}, {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT}, {@link OpenStreetMapViewController.ANIMATION_SMOOTHNESS_HIGH}
+ * @param aDuration in Milliseconds. I.e.: {@link OpenStreetMapViewController.ANIMATION_DURATION_SHORT}, {@link OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT}, {@link OpenStreetMapViewController.ANIMATION_DURATION_LONG}
+ */
+ public void animateTo(final int aLatitudeE6, final int aLongitudeE6, final AnimationType aAnimationType, final int aSmoothness, final int aDuration){
+ this.stopAnimation(false);
+
+ switch(aAnimationType){
+ case LINEAR:
+ this.mCurrentAnimationRunner = new LinearAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
+ break;
+ case EXPONENTIALDECELERATING:
+ this.mCurrentAnimationRunner = new ExponentialDeceleratingAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
+ break;
+ case QUARTERCOSINUSALDECELERATING:
+ this.mCurrentAnimationRunner = new QuarterCosinusalDeceleratingAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
+ break;
+ case HALFCOSINUSALDECELERATING:
+ this.mCurrentAnimationRunner = new HalfCosinusalDeceleratingAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
+ break;
+ case MIDDLEPEAKSPEED:
+ this.mCurrentAnimationRunner = new MiddlePeakSpeedAnimationRunner(aLatitudeE6, aLongitudeE6, aSmoothness, aDuration);
+ break;
+ }
+
+ this.mCurrentAnimationRunner.start();
+ }
+
+ public void scrollBy(int x, int y) {
+ this.mOsmv.scrollBy(x, y);
+ }
+
+ /**
+ * Set the map view to the given center. There will be no animation.
+ */
+ public void setCenter(final GeoPoint point) {
+ final Point p = Mercator.projectGeoPoint(point, this.mOsmv.getPixelZoomLevel(), null);
+ final int worldSize_2 = this.mOsmv.getWorldSizePx()/2;
+ this.mOsmv.scrollTo(p.x - worldSize_2, p.y - worldSize_2);
+ }
+
+ /**
+ * Stops a running animation.
+ * @param jumpToTarget
+ */
+ public void stopAnimation(final boolean jumpToTarget) {
+ final AbstractAnimationRunner currentAnimationRunner = this.mCurrentAnimationRunner;
+
+ if(currentAnimationRunner != null && !currentAnimationRunner.isDone()){
+ currentAnimationRunner.interrupt();
+ if(jumpToTarget)
+ setCenter(new GeoPoint(currentAnimationRunner.mTargetLatitudeE6, currentAnimationRunner.mTargetLongitudeE6));
+ }
+ }
+
+
+
+ public int setZoom(int zoomlevel) {
+ this.mZoomLevel = zoomlevel;
+ return mOsmv.setZoomLevel(zoomlevel);
+ }
+
+ /**
+ * Zoom in by one zoom level.
+ */
+ public boolean zoomIn() {
+
+ if (mZoomLevel >= mOsmv.getMaxZoomLevel()) {
+ mZoomLevel = mOsmv.getMaxZoomLevel();
+ return false;
+ }
+
+ mZoomLevel++;
+ final Scaler scaler = mOsmv.mScaler;
+ if (scaler.isFinished()) {
+ scaler.startScale(1.0f, 2.0f, ANIMATION_DURATION_SHORT);
+ mOsmv.postInvalidate();
+ } else {
+ scaler.extendDuration(ANIMATION_DURATION_SHORT);
+ scaler.setFinalScale(scaler.getFinalScale() * 2.0f);
+ }
+
+ return true;
+ }
+
+ public boolean zoomInFixing(int xPixel, int yPixel) {
+ // TODO implement
+ return zoomIn();
+ }
+
+ /**
+ * Zoom out by one zoom level.
+ */
+ public boolean zoomOut() {
+
+ if (mZoomLevel <= 0) {
+ mZoomLevel = 0;
+ return false;
+ }
+
+ mZoomLevel--;
+ final Scaler scaler = mOsmv.mScaler;
+ if (scaler.isFinished()) {
+ scaler.startScale(1.0f, 0.5f, ANIMATION_DURATION_SHORT);
+ mOsmv.postInvalidate();
+ } else {
+ scaler.extendDuration(ANIMATION_DURATION_SHORT);
+ scaler.setFinalScale(scaler.getFinalScale() * 0.5f);
+ }
+
+ return true;
+ }
+
+ public boolean zoomOutFixing(int xPixel, int yPixel) {
+ // TODO implement
+ return zoomOut();
+ }
+
+ void onScalingFinished() {
+ mOsmv.setZoomLevel(mZoomLevel);
+ }
+
+ void onScrollingFinished() {
+
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+
+ /**
+ * Choose on of the Styles of approacing the target Coordinates.
+ * <ul>
+ * <li><code>LINEAR</code>
+ * <ul>
+ * <li>Uses ses linear interpolation </li>
+ * <li>Values produced: 10%, 20%, 30%, 40%, 50%, ...</li>
+ * <li>Style: Always average speed.</li>
+ * </ul>
+ * </li>
+ * <li><code>EXPONENTIALDECELERATING</code>
+ * <ul>
+ * <li>Uses a exponential interpolation/li>
+ * <li>Values produced: 50%, 75%, 87.5%, 93.5%, ...</li>
+ * <li>Style: Starts very fast, really slow in the end.</li>
+ * </ul>
+ * </li>
+ * <li><code>QUARTERCOSINUSALDECELERATING</code>
+ * <ul>
+ * <li>Uses the first quarter of the cos curve (from zero to PI/2) for interpolation. </li>
+ * <li>Values produced: See cos curve :)</li>
+ * <li>Style: Average speed, slows out medium.</li>
+ * </ul>
+ * </li>
+ * <li><code>HALFCOSINUSALDECELERATING</code>
+ * <ul>
+ * <li>Uses the first half of the cos curve (from zero to PI) for interpolation</li>
+ * <li>Values produced: See cos curve :)</li>
+ * <li>Style: Average speed, slows out smoothly.</li>
+ * </ul>
+ * </li>
+ * <li><code>MIDDLEPEAKSPEED</code>
+ * <ul>
+ * <li>Uses the values of cos around the 0 (from -PI/2 to +PI/2) for interpolation</li>
+ * <li>Values produced: See cos curve :)</li>
+ * <li>Style: Starts medium, speeds high in middle, slows out medium.</li>
+ * </ul>
+ * </li>
+ * </ul>
+ */
+ public static enum AnimationType {
+ /**
+ * <ul>
+ * <li><code>LINEAR</code>
+ * <ul>
+ * <li>Uses ses linear interpolation </li>
+ * <li>Values produced: 10%, 20%, 30%, 40%, 50%, ...</li>
+ * <li>Style: Always average speed.</li>
+ * </ul>
+ * </li>
+ * </ul>
+ */
+ LINEAR,
+ /**
+ * <ul>
+ * <li><code>EXPONENTIALDECELERATING</code>
+ * <ul>
+ * <li>Uses a exponential interpolation/li>
+ * <li>Values produced: 50%, 75%, 87.5%, 93.5%, ...</li>
+ * <li>Style: Starts very fast, really slow in the end.</li>
+ * </ul>
+ * </li>
+ * </ul>
+ */
+ EXPONENTIALDECELERATING,
+ /**
+ * <ul>
+ * <li><code>QUARTERCOSINUSALDECELERATING</code>
+ * <ul>
+ * <li>Uses the first quarter of the cos curve (from zero to PI/2) for interpolation. </li>
+ * <li>Values produced: See cos curve :)</li>
+ * <li>Style: Average speed, slows out medium.</li>
+ * </ul>
+ * </li>
+ * </ul>
+ */
+ QUARTERCOSINUSALDECELERATING,
+ /** <ul>
+ * <li><code>HALFCOSINUSALDECELERATING</code>
+ * <ul>
+ * <li>Uses the first half of the cos curve (from zero to PI) for interpolation</li>
+ * <li>Values produced: See cos curve :)</li>
+ * <li>Style: Average speed, slows out smoothly.</li>
+ * </ul>
+ * </li>
+ * </ul>
+ */
+ HALFCOSINUSALDECELERATING,
+ /** <ul>
+ * <li><code>MIDDLEPEAKSPEED</code>
+ * <ul>
+ * <li>Uses the values of cos around the 0 (from -PI/2 to +PI/2) for interpolation</li>
+ * <li>Values produced: See cos curve :)</li>
+ * <li>Style: Starts medium, speeds high in middle, slows out medium.</li>
+ * </ul>
+ * </li>
+ * </ul>
+ */
+ MIDDLEPEAKSPEED;
+ }
+
+ private abstract class AbstractAnimationRunner extends Thread{
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final int mSmoothness, mDuration;
+ protected final int mTargetLatitudeE6, mTargetLongitudeE6;
+ protected boolean mDone = false;
+
+ protected final int mStepDuration;
+
+ protected final int mPanTotalLatitudeE6, mPanTotalLongitudeE6;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public AbstractAnimationRunner(OpenStreetMapViewController openStreetMapViewController, final int aTargetLatitudeE6, final int aTargetLongitudeE6){
+ this(aTargetLatitudeE6, aTargetLongitudeE6, OpenStreetMapViewController.ANIMATION_SMOOTHNESS_DEFAULT, OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT);
+ }
+
+ public AbstractAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
+ this.mTargetLatitudeE6 = aTargetLatitudeE6;
+ this.mTargetLongitudeE6 = aTargetLongitudeE6;
+ this.mSmoothness = aSmoothness;
+ this.mDuration = aDuration;
+
+ this.mStepDuration = aDuration / aSmoothness;
+
+
+ /* Get the current mapview-center. */
+ final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
+ int mapCenterLatE6 = mapview.getMapCenterLatitudeE6();
+ int mapCenterLonE6 = mapview.getMapCenterLongitudeE6();
+
+ this.mPanTotalLatitudeE6 = (mapCenterLatE6 - aTargetLatitudeE6);
+ this.mPanTotalLongitudeE6 = (mapCenterLonE6 - aTargetLongitudeE6);
+ }
+
+ public void run(){
+ onRunAnimation();
+ this.mDone = true;
+ }
+
+ public boolean isDone(){
+ return this.mDone;
+ }
+
+ public abstract void onRunAnimation();
+ }
+
+ private class LinearAnimationRunner extends AbstractAnimationRunner{
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final int mPanPerStepLatitudeE6, mPanPerStepLongitudeE6;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public LinearAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
+ this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
+ }
+
+ public LinearAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
+ super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration);
+
+ /* Get the current mapview-center. */
+ final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
+ int mapCenterLatE6 = mapview.getMapCenterLatitudeE6();
+ int mapCenterLonE6 = mapview.getMapCenterLongitudeE6();
+
+ this.mPanPerStepLatitudeE6 = (mapCenterLatE6 - aTargetLatitudeE6) / aSmoothness;
+ this.mPanPerStepLongitudeE6 = (mapCenterLonE6 - aTargetLongitudeE6) / aSmoothness;
+
+ this.setName("LinearAnimationRunner");
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ public void onRunAnimation(){
+ final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
+ final int panPerStepLatitudeE6 = this.mPanPerStepLatitudeE6;
+ final int panPerStepLongitudeE6 = this.mPanPerStepLongitudeE6;
+ final int stepDuration = this.mStepDuration;
+ try {
+ int newMapCenterLatE6;
+ int newMapCenterLonE6;
+
+ for(int i = this.mSmoothness; i > 0 ; i--){
+
+ newMapCenterLatE6 = mapview.getMapCenterLatitudeE6() - panPerStepLatitudeE6;
+ newMapCenterLonE6 = mapview.getMapCenterLongitudeE6() - panPerStepLongitudeE6;
+ mapview.setMapCenter(newMapCenterLatE6, newMapCenterLonE6);
+
+ Thread.sleep(stepDuration);
+ }
+ } catch (Exception e) {
+ this.interrupt();
+ }
+ }
+ }
+
+ private class ExponentialDeceleratingAnimationRunner extends AbstractAnimationRunner{
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public ExponentialDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
+ this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
+ }
+
+ public ExponentialDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
+ super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration);
+
+ this.setName("ExponentialDeceleratingAnimationRunner");
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ public void onRunAnimation(){
+ final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
+ final int stepDuration = this.mStepDuration;
+ try {
+ int newMapCenterLatE6;
+ int newMapCenterLonE6;
+
+ for(int i = 0; i < this.mSmoothness; i++){
+
+ final double delta = Math.pow(0.5, i + 1);
+ final int deltaLatitudeE6 = (int)(this.mPanTotalLatitudeE6 * delta);
+ final int detlaLongitudeE6 = (int)(this.mPanTotalLongitudeE6 * delta);
+
+ newMapCenterLatE6 = mapview.getMapCenterLatitudeE6() - deltaLatitudeE6;
+ newMapCenterLonE6 = mapview.getMapCenterLongitudeE6() - detlaLongitudeE6;
+ mapview.setMapCenter(newMapCenterLatE6, newMapCenterLonE6);
+
+ Thread.sleep(stepDuration);
+ }
+ mapview.setMapCenter(super.mTargetLatitudeE6, super.mTargetLongitudeE6);
+ } catch (Exception e) {
+ this.interrupt();
+ }
+ }
+ }
+
+ private class CosinusalBasedAnimationRunner extends AbstractAnimationRunner implements MathConstants{
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final float mStepIncrement, mAmountStretch;
+ protected final float mYOffset, mRange, mStart;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public CosinusalBasedAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final float aStart, final float aRange, final float aYOffset){
+ this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT, aStart, aRange, aYOffset);
+ }
+
+ public CosinusalBasedAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration, final float aStart, final float aRange, final float aYOffset){
+ super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration);
+ this.mYOffset = aYOffset;
+ this.mRange = aRange;
+ this.mStart = aStart;
+
+ this.mStepIncrement = aRange / aSmoothness;
+
+ /* We need to normalize the amount in the end, so wee need the the: sum^(-1) . */
+ float amountSum = 0;
+ for(int i = 0; i < aSmoothness; i++)
+ amountSum += aYOffset + Math.cos(this.mStepIncrement * i + aStart);
+
+ this.mAmountStretch = 1 / amountSum;
+
+ this.setName("QuarterCosinusalDeceleratingAnimationRunner");
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ public void onRunAnimation(){
+ final OpenStreetMapView mapview = OpenStreetMapViewController.this.mOsmv;
+ final int stepDuration = this.mStepDuration;
+ final float amountStretch = this.mAmountStretch;
+ try {
+ int newMapCenterLatE6;
+ int newMapCenterLonE6;
+
+ for(int i = 0; i < this.mSmoothness; i++){
+
+ final double delta = (this.mYOffset + Math.cos(this.mStepIncrement * i + this.mStart)) * amountStretch;
+ final int deltaLatitudeE6 = (int)(this.mPanTotalLatitudeE6 * delta);
+ final int deltaLongitudeE6 = (int)(this.mPanTotalLongitudeE6 * delta);
+
+ newMapCenterLatE6 = mapview.getMapCenterLatitudeE6() - deltaLatitudeE6;
+ newMapCenterLonE6 = mapview.getMapCenterLongitudeE6() - deltaLongitudeE6;
+ mapview.setMapCenter(newMapCenterLatE6, newMapCenterLonE6);
+
+ Thread.sleep(stepDuration);
+ }
+ mapview.setMapCenter(super.mTargetLatitudeE6, super.mTargetLongitudeE6);
+ } catch (Exception e) {
+ this.interrupt();
+ }
+ }
+ }
+
+ protected class QuarterCosinusalDeceleratingAnimationRunner extends CosinusalBasedAnimationRunner implements MathConstants{
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ protected QuarterCosinusalDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
+ this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
+ }
+
+ protected QuarterCosinusalDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
+ super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration, 0, PI_2, 0);
+ }
+ }
+
+ protected class HalfCosinusalDeceleratingAnimationRunner extends CosinusalBasedAnimationRunner implements MathConstants{
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ protected HalfCosinusalDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
+ this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
+ }
+
+ protected HalfCosinusalDeceleratingAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
+ super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration, 0, PI, 1);
+ }
+ }
+
+ protected class MiddlePeakSpeedAnimationRunner extends CosinusalBasedAnimationRunner implements MathConstants{
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ protected MiddlePeakSpeedAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6){
+ this(aTargetLatitudeE6, aTargetLongitudeE6, ANIMATION_SMOOTHNESS_DEFAULT, ANIMATION_DURATION_DEFAULT);
+ }
+
+ protected MiddlePeakSpeedAnimationRunner(final int aTargetLatitudeE6, final int aTargetLongitudeE6, final int aSmoothness, final int aDuration){
+ super(aTargetLatitudeE6, aTargetLongitudeE6, aSmoothness, aDuration, -PI_2, PI, 0);
+ }
+ }
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/MyLocationOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/MyLocationOverlay.java
new file mode 100644
index 0000000..4feb96c
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/MyLocationOverlay.java
@@ -0,0 +1,269 @@
+// Created by plusminus on 22:01:11 - 29.09.2008
+package org.andnav.osm.views.overlay;
+
+import java.util.LinkedList;
+
+import org.andnav.osm.R;
+import org.andnav.osm.util.GeoPoint;
+import org.andnav.osm.util.NetworkLocationIgnorer;
+import org.andnav.osm.views.OpenStreetMapView;
+import org.andnav.osm.views.OpenStreetMapViewController;
+import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
+import org.andnav.osm.views.overlay.OpenStreetMapViewOverlay.Snappable;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Canvas;
+import android.graphics.Matrix;
+import android.graphics.Paint;
+import android.graphics.Point;
+import android.graphics.Paint.Style;
+import android.location.Location;
+import android.location.LocationListener;
+import android.location.LocationManager;
+import android.location.LocationProvider;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.MotionEvent;
+
+/**
+ *
+ * @author Manuel Stahl
+ *
+ */
+public class MyLocationOverlay extends OpenStreetMapViewOverlay implements LocationListener, Snappable {
+
+ public static final String DEBUGTAG = "OPENSTREETMAP";
+
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final Paint mPaint = new Paint();
+ protected final Paint mCirclePaint = new Paint();
+
+ protected final Bitmap PERSON_ICON;
+ protected final Bitmap DIRECTION_ARROW;
+
+ private final OpenStreetMapView mMapView;
+ private final OpenStreetMapViewController mMapController;
+ private final LocationManager mLocationManager;
+ private boolean mMyLocationEnabled = false;
+ private LinkedList<Runnable> mRunOnFirstFix = new LinkedList<Runnable>();
+ private final Point mMapCoords = new Point();
+
+ private Location mLocation;
+ protected boolean mFollow = false; // follow location updates
+ private NetworkLocationIgnorer mIgnorer = new NetworkLocationIgnorer();
+
+ private final Matrix directionRotater = new Matrix();
+
+ /** Coordinates the feet of the person are located. */
+ protected final android.graphics.Point PERSON_HOTSPOT = new android.graphics.Point(24,39);
+
+ private final float DIRECTION_ARROW_CENTER_X;
+ private final float DIRECTION_ARROW_CENTER_Y;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public MyLocationOverlay(final Context ctx, final OpenStreetMapView mapView) {
+ mMapView = mapView;
+ mLocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
+ mMapController = mapView.getController();
+ mCirclePaint.setARGB(0, 100, 100, 255);
+ mCirclePaint.setAntiAlias(true);
+
+ PERSON_ICON = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.person);
+ DIRECTION_ARROW = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.direction_arrow);
+
+ DIRECTION_ARROW_CENTER_X = DIRECTION_ARROW.getWidth() / 2 - 0.5f;
+ DIRECTION_ARROW_CENTER_Y = DIRECTION_ARROW.getHeight() / 2 - 0.5f;
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public Location getLastFix() {
+ return mLocation;
+ }
+
+ /**
+ * Return a GeoPoint of the last known location, or null if not known.
+ */
+ public GeoPoint getMyLocation() {
+ if (mLocation == null) {
+ return null;
+ } else {
+ return new GeoPoint(mLocation);
+ }
+ }
+
+ public boolean isMyLocationEnabled() {
+ return mMyLocationEnabled;
+ }
+
+ public boolean isLocationFollowEnabled() {
+ return mFollow;
+ }
+
+ public void followLocation(boolean enable) {
+ mFollow = enable;
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {}
+
+ @Override
+ public void onDraw(final Canvas c, final OpenStreetMapView osmv) {
+ if(this.mLocation != null) {
+ final OpenStreetMapViewProjection pj = osmv.getProjection();
+ pj.toMapPixels(new GeoPoint(mLocation), mMapCoords);
+ final float radius = pj.metersToEquatorPixels(this.mLocation.getAccuracy());
+
+ this.mCirclePaint.setAlpha(50);
+ this.mCirclePaint.setStyle(Style.FILL);
+ c.drawCircle(mMapCoords.x, mMapCoords.y, radius, this.mCirclePaint);
+
+ this.mCirclePaint.setAlpha(150);
+ this.mCirclePaint.setStyle(Style.STROKE);
+ c.drawCircle(mMapCoords.x, mMapCoords.y, radius, this.mCirclePaint);
+
+ float[] mtx = new float[9];
+ c.getMatrix().getValues(mtx);
+
+ if (DEBUGMODE) {
+ float tx = (-mtx[Matrix.MTRANS_X]+20)/mtx[Matrix.MSCALE_X];
+ float ty = (-mtx[Matrix.MTRANS_Y]+90)/mtx[Matrix.MSCALE_Y];
+ c.drawText("Lat: " + mLocation.getLatitude(), tx, ty + 5, this.mPaint);
+ c.drawText("Lon: " + mLocation.getLongitude(), tx, ty + 20, this.mPaint);
+ c.drawText("Alt: " + mLocation.getAltitude(), tx, ty + 35, this.mPaint);
+ c.drawText("Acc: " + mLocation.getAccuracy(), tx, ty + 50, this.mPaint);
+ }
+
+ if (mLocation.hasSpeed() && mLocation.getSpeed() > 1) {
+ /* Rotate the direction-Arrow according to the bearing we are driving. And draw it to the canvas. */
+ this.directionRotater.setRotate(this.mLocation.getBearing(), DIRECTION_ARROW_CENTER_X , DIRECTION_ARROW_CENTER_Y);
+ this.directionRotater.postTranslate(-DIRECTION_ARROW_CENTER_X, -DIRECTION_ARROW_CENTER_Y);
+ this.directionRotater.postScale(1/mtx[Matrix.MSCALE_X], 1/mtx[Matrix.MSCALE_Y]);
+ this.directionRotater.postTranslate(mMapCoords.x, mMapCoords.y);
+ c.drawBitmap(DIRECTION_ARROW, this.directionRotater, this.mPaint);
+ } else {
+ this.directionRotater.setTranslate(-PERSON_HOTSPOT.x, -PERSON_HOTSPOT.y);
+ this.directionRotater.postScale(1/mtx[Matrix.MSCALE_X], 1/mtx[Matrix.MSCALE_Y]);
+ this.directionRotater.postTranslate(mMapCoords.x, mMapCoords.y);
+ c.drawBitmap(PERSON_ICON, this.directionRotater, this.mPaint);
+ }
+ }
+ }
+
+ @Override
+ public void onLocationChanged(final Location location) {
+ if (DEBUGMODE) {
+ Log.d(DEBUGTAG, "onLocationChanged(" + location + ")");
+ }
+
+ // ignore temporary non-gps fix
+ if (mIgnorer.shouldIgnore(location.getProvider(), System.currentTimeMillis())) {
+ Log.d(DEBUGTAG, "Ignore temporary non-gps location");
+ return;
+ }
+
+ mLocation = location;
+ if (mFollow) {
+ mMapController.animateTo(new GeoPoint(location));
+ } else {
+ mMapView.invalidate(); // redraw the my location icon
+ }
+ }
+
+ @Override
+ public void onProviderDisabled(String provider) {
+ }
+
+ @Override
+ public void onProviderEnabled(String provider) {
+ }
+
+ @Override
+ public void onStatusChanged(String provider, int status, Bundle extras) {
+ if(status == LocationProvider.AVAILABLE) {
+ final Thread t = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ for(Runnable runnable: mRunOnFirstFix) {
+ runnable.run();
+ }
+ mRunOnFirstFix.clear();
+ }
+ });
+ t.run();
+ }
+ }
+
+ @Override
+ public boolean onSnapToItem(int x, int y, Point snapPoint, OpenStreetMapView mapView) {
+ if(this.mLocation != null) {
+ final OpenStreetMapViewProjection pj = mapView.getProjection();
+ pj.toMapPixels(new GeoPoint(mLocation), mMapCoords);
+ snapPoint.x = mMapCoords.x;
+ snapPoint.y = mMapCoords.y;
+
+ boolean snap = (x - mMapCoords.x)*(x - mMapCoords.x) + (y - mMapCoords.y)*(y - mMapCoords.y) < 64;
+ return snap;
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent event, OpenStreetMapView mapView) {
+ if (event.getAction() == MotionEvent.ACTION_MOVE)
+ mFollow = false;
+
+ return super.onTouchEvent(event, mapView);
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ public void disableMyLocation() {
+ mLocationManager.removeUpdates(this);
+ mMyLocationEnabled = false;
+ }
+
+ public boolean enableMyLocation() {
+ if (!mMyLocationEnabled) {
+ for (final String provider : mLocationManager.getAllProviders()) {
+ mLocationManager.requestLocationUpdates(provider, 0, 0, this);
+ }
+ }
+ return mMyLocationEnabled = true;
+ }
+
+ public boolean runOnFirstFix(Runnable runnable) {
+ if(mMyLocationEnabled) {
+ runnable.run();
+ return true;
+ } else {
+ mRunOnFirstFix.addLast(runnable);
+ return false;
+ }
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapTilesOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapTilesOverlay.java
new file mode 100644
index 0000000..21baae9
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapTilesOverlay.java
@@ -0,0 +1,141 @@
+package org.andnav.osm.views.overlay;
+
+import org.andnav.osm.tileprovider.OpenStreetMapTile;
+import org.andnav.osm.util.GeoPoint;
+import org.andnav.osm.util.MyMath;
+import org.andnav.osm.views.OpenStreetMapView;
+import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
+import org.andnav.osm.views.util.OpenStreetMapRendererInfo;
+import org.andnav.osm.views.util.OpenStreetMapTileProvider;
+
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+
+public class OpenStreetMapTilesOverlay extends OpenStreetMapViewOverlay {
+
+ protected OpenStreetMapView mOsmv;
+ protected OpenStreetMapRendererInfo mRendererInfo;
+
+ /** Current renderer */
+ protected final OpenStreetMapTileProvider mTileProvider;
+ protected final Paint mPaint = new Paint();
+
+ public OpenStreetMapTilesOverlay(final OpenStreetMapView aOsmv,
+ final OpenStreetMapRendererInfo aRendererInfo,
+ final OpenStreetMapTileProvider aTileProvider) {
+ this.mOsmv = aOsmv;
+ this.mRendererInfo = aRendererInfo;
+ if(aTileProvider == null)
+ mTileProvider = OpenStreetMapTileProvider.getInstance(mOsmv.getContext(), new SimpleInvalidationHandler());
+ else
+ this.mTileProvider = aTileProvider;
+ }
+
+ public void detach()
+ {
+ this.mTileProvider.detach();
+ }
+
+ public OpenStreetMapRendererInfo getRendererInfo() {
+ return mRendererInfo;
+ }
+
+ public void setRendererInfo(final OpenStreetMapRendererInfo aRendererInfo) {
+ this.mRendererInfo = aRendererInfo;
+ // XXX perhaps we should set the cache capacity back to default here
+ }
+
+ public void setAlpha(int a) {
+ this.mPaint.setAlpha(a);
+ }
+
+ @Override
+ protected void onDraw(Canvas c, OpenStreetMapView osmv) {
+
+ if(DEBUGMODE)
+ Log.v(DEBUGTAG, "onDraw");
+
+ /*
+ * Do some calculations and drag attributes to local variables to save
+ * some performance.
+ */
+ final OpenStreetMapViewProjection pj = osmv.getProjection();
+ final int zoomLevel = osmv.getZoomLevel();
+ final Rect viewPort = c.getClipBounds();
+ final int tileSizePx = this.mRendererInfo.MAPTILE_SIZEPX;
+ final int tileZoom = this.mRendererInfo.MAPTILE_ZOOM;
+ final int worldSize_2 = 1 << (zoomLevel + this.mRendererInfo.MAPTILE_ZOOM - 1);
+ final int rendererId = this.mRendererInfo.ordinal(); // TODO get from service
+
+ /*
+ * Calculate the amount of tiles needed for each side around the center
+ * one.
+ */
+ viewPort.offset(worldSize_2, worldSize_2);
+ final int tileNeededToLeftOfCenter = (viewPort.left >> tileZoom) - 1;
+ final int tileNeededToRightOfCenter = viewPort.right >> tileZoom;
+ final int tileNeededToTopOfCenter = (viewPort.top >> tileZoom) - 1;
+ final int tileNeededToBottomOfCenter = viewPort.bottom >> tileZoom;
+
+ final int mapTileUpperBound = 1 << zoomLevel;
+ final Point tilePos = new Point();
+
+ // make sure the cache is big enough for all the tiles
+ final int numNeeded = (tileNeededToBottomOfCenter - tileNeededToTopOfCenter + 1)
+ * (tileNeededToRightOfCenter - tileNeededToLeftOfCenter + 1);
+ mTileProvider.ensureCapacity(numNeeded);
+
+ /* Draw all the MapTiles (from the upper left to the lower right). */
+ for (int y = tileNeededToTopOfCenter; y <= tileNeededToBottomOfCenter; y++) {
+ for (int x = tileNeededToLeftOfCenter; x <= tileNeededToRightOfCenter; x++) {
+ /* Construct a URLString, which represents the MapTile. */
+ final int tileY = MyMath.mod(y, mapTileUpperBound);
+ final int tileX = MyMath.mod(x, mapTileUpperBound);
+ final OpenStreetMapTile tile = new OpenStreetMapTile(rendererId, zoomLevel, tileX, tileY);
+
+ pj.toPixels(x, y, tilePos);
+ final Bitmap currentMapTile = mTileProvider.getMapTile(tile);
+ if (currentMapTile != null) {
+ c.drawBitmap(currentMapTile, tilePos.x, tilePos.y, mPaint);
+ }
+
+ if (DEBUGMODE) {
+ c.drawText(tile.toString(), tilePos.x + 1, tilePos.y + mPaint.getTextSize(), mPaint);
+ c.drawLine(tilePos.x, tilePos.y, tilePos.x + tileSizePx, tilePos.y, mPaint);
+ c.drawLine(tilePos.x, tilePos.y, tilePos.x, tilePos.y + tileSizePx, mPaint);
+ }
+ }
+ }
+
+ // draw a cross at center in debug mode
+ if (DEBUGMODE) {
+ final GeoPoint center = osmv.getMapCenter();
+ final Point centerPoint = pj.toMapPixels(center, null);
+ c.drawLine(centerPoint.x, centerPoint.y - 9, centerPoint.x, centerPoint.y + 9, mPaint);
+ c.drawLine(centerPoint.x - 9, centerPoint.y, centerPoint.x + 9, centerPoint.y, mPaint);
+ }
+
+ }
+
+ @Override
+ protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
+ }
+
+ private class SimpleInvalidationHandler extends Handler {
+
+ @Override
+ public void handleMessage(final Message msg) {
+ switch (msg.what) {
+ case OpenStreetMapTile.MAPTILE_SUCCESS_ID:
+ mOsmv.invalidate();
+ break;
+ }
+ }
+ }
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewDirectedLocationOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewDirectedLocationOverlay.java
new file mode 100644
index 0000000..d00143c
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewDirectedLocationOverlay.java
@@ -0,0 +1,101 @@
+// Created by plusminus on 22:01:11 - 29.09.2008
+package org.andnav.osm.views.overlay;
+
+import org.andnav.osm.R;
+import org.andnav.osm.util.GeoPoint;
+import org.andnav.osm.views.OpenStreetMapView;
+import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Canvas;
+import android.graphics.Matrix;
+import android.graphics.Paint;
+import android.graphics.Point;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class OpenStreetMapViewDirectedLocationOverlay extends OpenStreetMapViewOverlay {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final Paint mPaint = new Paint();
+
+ protected final Bitmap DIRECTION_ARROW;
+
+ protected GeoPoint mLocation;
+ protected float mBearing;
+
+ private final Matrix directionRotater = new Matrix();
+
+ private final float DIRECTION_ARROW_CENTER_X;
+ private final float DIRECTION_ARROW_CENTER_Y;
+ private final int DIRECTION_ARROW_WIDTH;
+ private final int DIRECTION_ARROW_HEIGHT;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public OpenStreetMapViewDirectedLocationOverlay(final Context ctx){
+ this.DIRECTION_ARROW = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.direction_arrow);
+
+ this.DIRECTION_ARROW_CENTER_X = this.DIRECTION_ARROW.getWidth() / 2 - 0.5f;
+ this.DIRECTION_ARROW_CENTER_Y = this.DIRECTION_ARROW.getHeight() / 2 - 0.5f;
+ this.DIRECTION_ARROW_HEIGHT = this.DIRECTION_ARROW.getHeight();
+ this.DIRECTION_ARROW_WIDTH = this.DIRECTION_ARROW.getWidth();
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public void setLocation(final GeoPoint mp){
+ this.mLocation = mp;
+ }
+
+ public void setBearing(final float aHeading){
+ this.mBearing = aHeading;
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
+ return;
+ }
+
+ @Override
+ public void onDraw(final Canvas c, final OpenStreetMapView osmv) {
+ if(this.mLocation != null){
+ final OpenStreetMapViewProjection pj = osmv.getProjection();
+ final Point screenCoords = new Point();
+ pj.toMapPixels(this.mLocation, screenCoords);
+
+
+ /* Rotate the direction-Arrow according to the bearing we are driving. And draw it to the canvas. */
+ this.directionRotater.setRotate(this.mBearing, DIRECTION_ARROW_CENTER_X , DIRECTION_ARROW_CENTER_Y);
+ Bitmap rotatedDirection = Bitmap.createBitmap(DIRECTION_ARROW, 0, 0, DIRECTION_ARROW_WIDTH, DIRECTION_ARROW_HEIGHT, this.directionRotater, false);
+ c.drawBitmap(rotatedDirection, screenCoords.x - rotatedDirection.getWidth() / 2, screenCoords.y - rotatedDirection.getHeight() / 2, this.mPaint);
+ }
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlay.java
new file mode 100644
index 0000000..49b6d06
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlay.java
@@ -0,0 +1,158 @@
+// Created by plusminus on 23:18:23 - 02.10.2008
+package org.andnav.osm.views.overlay;
+
+import java.util.List;
+
+import org.andnav.osm.R;
+import org.andnav.osm.views.OpenStreetMapView;
+import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.graphics.drawable.Drawable;
+import android.view.MotionEvent;
+
+/**
+ * Draws a list of {@link OpenStreetMapViewOverlayItem} as markers to a map.
+ * The item with the lowest index is drawn as last and therefore the 'topmost' marker. It also gets checked for onTap first.
+ * This class is generic, because you then you get your custom item-class passed back in onTap().
+ * @author Nicolas Gramlich
+ *
+ * @param <T>
+ */
+public class OpenStreetMapViewItemizedOverlay<T extends OpenStreetMapViewOverlayItem> extends OpenStreetMapViewOverlay {
+
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ protected static final Point DEFAULTMARKER_HOTSPOT = new Point(13, 47);
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected OnItemTapListener<T> mOnItemTapListener;
+ protected final List<T> mItemList;
+ protected final Point mMarkerHotSpot;
+ protected final Drawable mMarker;
+ protected final int mMarkerWidth, mMarkerHeight;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public OpenStreetMapViewItemizedOverlay(final Context ctx, final List<T> aList, final OnItemTapListener<T> aOnItemTapListener) {
+ this(ctx, aList, null, null, aOnItemTapListener);
+ }
+
+ public OpenStreetMapViewItemizedOverlay(final Context ctx, final List<T> aList, final Drawable pMarker, final Point pMarkerHotspot, final OnItemTapListener<T> aOnItemTapListener) {
+ assert(ctx != null);
+ assert(aList != null);
+
+ this.mMarker = (pMarker != null) ? pMarker : ctx.getResources().getDrawable(R.drawable.marker_default);
+
+ this.mMarkerHotSpot = (pMarkerHotspot != null) ? pMarkerHotspot : DEFAULTMARKER_HOTSPOT;
+
+ this.mOnItemTapListener = aOnItemTapListener;
+
+ this.mMarkerWidth = this.mMarker.getIntrinsicWidth();
+ this.mMarkerHeight = this.mMarker.getIntrinsicHeight();
+
+ // Add one sample item.
+ this.mItemList = aList;
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
+ return;
+ }
+
+ @Override
+ public void onDraw(final Canvas c, final OpenStreetMapView mapView) {
+ final OpenStreetMapViewProjection pj = mapView.getProjection();
+
+ final Point curScreenCoords = new Point();
+
+ /* Draw in backward cycle, so the items with the least index are on the front. */
+ for(int i = this.mItemList.size() - 1; i >= 0; i--){
+ T item = this.mItemList.get(i);
+ pj.toMapPixels(item.mGeoPoint, curScreenCoords);
+
+ onDrawItem(c, i, curScreenCoords);
+ }
+ }
+
+ protected void onDrawItem(final Canvas c, final int index, final Point curScreenCoords) {
+ final int left = curScreenCoords.x - this.mMarkerHotSpot.x;
+ final int right = left + this.mMarkerWidth;
+ final int top = curScreenCoords.y - this.mMarkerHotSpot.y;
+ final int bottom = top + this.mMarkerHeight;
+
+ this.mMarker.setBounds(left, top, right, bottom);
+
+ this.mMarker.draw(c);
+ }
+
+ @Override
+ public boolean onSingleTapUp(final MotionEvent event, final OpenStreetMapView mapView) {
+ final OpenStreetMapViewProjection pj = mapView.getProjection();
+ final int eventX = (int) event.getX();
+ final int eventY = (int) event.getY();
+ final int markerWidth = this.mMarker.getIntrinsicWidth();
+ final int markerHeight = this.mMarker.getIntrinsicHeight();
+
+ /* These objects are created to avoid construct new ones every cycle. */
+ final Rect curMarkerBounds = new Rect();
+ final Point curScreenCoords = new Point();
+ final Point curScreenCoords2 = new Point();
+
+ for(int i = 0; i < this.mItemList.size(); i++){
+ final T item = this.mItemList.get(i);
+
+ pj.toMapPixels(item.mGeoPoint, curScreenCoords);
+
+ final int left = (curScreenCoords.x - this.mMarkerHotSpot.x);
+ final int right = left + markerWidth;
+ final int top = (curScreenCoords.y - this.mMarkerHotSpot.y);
+ final int bottom = top + markerHeight;
+ curMarkerBounds.set(left, top, right, bottom);
+
+ pj.fromMapPixels(eventX, eventY, curScreenCoords2);
+ if (curMarkerBounds.contains(curScreenCoords2.x, curScreenCoords2.y)) {
+ if (onTap(i)) {
+ return true;
+ }
+ }
+ }
+ return super.onSingleTapUp(event, mapView);
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ protected boolean onTap(int pIndex) {
+ if(this.mOnItemTapListener != null)
+ return this.mOnItemTapListener.onItemTap(pIndex, this.mItemList.get(pIndex));
+ else
+ return false;
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+ public static interface OnItemTapListener<T>{
+ public boolean onItemTap(final int aIndex, final T aItem);
+ }
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayControlView.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayControlView.java
new file mode 100644
index 0000000..3025cc1
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayControlView.java
@@ -0,0 +1,127 @@
+// Created by plusminus on 22:59:38 - 12.09.2008
+package org.andnav.osm.views.overlay;
+
+import org.andnav.osm.R;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.ImageButton;
+import android.widget.LinearLayout;
+
+public class OpenStreetMapViewItemizedOverlayControlView extends LinearLayout{
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected ImageButton mPreviousButton;
+ protected ImageButton mNextButton;
+ protected ImageButton mCenterToButton;
+ protected ImageButton mNavToButton;
+
+ protected ItemizedOverlayControlViewListener mLis;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public OpenStreetMapViewItemizedOverlayControlView(Context context, AttributeSet attrs) {
+ super(context, attrs);
+
+ this.mPreviousButton = new ImageButton(context);
+ this.mPreviousButton.setImageDrawable(context.getResources().getDrawable(R.drawable.previous));
+
+ this.mNextButton = new ImageButton(context);
+ this.mNextButton.setImageDrawable(context.getResources().getDrawable(R.drawable.next));
+
+ this.mCenterToButton = new ImageButton(context);
+ this.mCenterToButton.setImageDrawable(context.getResources().getDrawable(R.drawable.center));
+
+ this.mNavToButton = new ImageButton(context);
+ this.mNavToButton.setImageDrawable(context.getResources().getDrawable(R.drawable.navto_small));
+
+ this.addView(mPreviousButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
+ this.addView(mCenterToButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
+ this.addView(mNavToButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
+ this.addView(mNextButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
+
+ initViewListeners();
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public void setItemizedOverlayControlViewListener(final ItemizedOverlayControlViewListener lis) {
+ this.mLis = lis;
+ }
+
+ public void setNextEnabled(final boolean pEnabled){
+ this.mNextButton.setEnabled(pEnabled);
+ }
+
+ public void setPreviousEnabled(final boolean pEnabled){
+ this.mPreviousButton.setEnabled(pEnabled);
+ }
+
+ public void setNavToVisible(final int pVisibility){
+ this.mNavToButton.setVisibility(pVisibility);
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ private void initViewListeners(){
+ this.mNextButton.setOnClickListener(new OnClickListener(){
+ @Override
+ public void onClick(View v) {
+ if(OpenStreetMapViewItemizedOverlayControlView.this.mLis != null)
+ OpenStreetMapViewItemizedOverlayControlView.this.mLis.onNext();
+ }
+ });
+
+ this.mPreviousButton.setOnClickListener(new OnClickListener(){
+ @Override
+ public void onClick(View v) {
+ if(OpenStreetMapViewItemizedOverlayControlView.this.mLis != null)
+ OpenStreetMapViewItemizedOverlayControlView.this.mLis.onPrevious();
+ }
+ });
+
+ this.mCenterToButton.setOnClickListener(new OnClickListener(){
+ @Override
+ public void onClick(View v) {
+ if(OpenStreetMapViewItemizedOverlayControlView.this.mLis != null)
+ OpenStreetMapViewItemizedOverlayControlView.this.mLis.onCenter();
+ }
+ });
+
+ this.mNavToButton.setOnClickListener(new OnClickListener(){
+ @Override
+ public void onClick(View v) {
+ if(OpenStreetMapViewItemizedOverlayControlView.this.mLis != null)
+ OpenStreetMapViewItemizedOverlayControlView.this.mLis.onNavTo();
+ }
+ });
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+
+ public interface ItemizedOverlayControlViewListener{
+ public void onPrevious();
+ public void onNext();
+ public void onCenter();
+ public void onNavTo();
+ }
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayWithFocus.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayWithFocus.java
new file mode 100644
index 0000000..0eb2de4
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewItemizedOverlayWithFocus.java
@@ -0,0 +1,243 @@
+// Created by plusminus on 20:50:06 - 03.10.2008
+package org.andnav.osm.views.overlay;
+
+import java.util.List;
+
+import org.andnav.osm.R;
+import org.andnav.osm.views.OpenStreetMapView;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.graphics.Point;
+import android.graphics.RectF;
+import android.graphics.drawable.Drawable;
+
+
+public class OpenStreetMapViewItemizedOverlayWithFocus<T extends OpenStreetMapViewOverlayItem> extends OpenStreetMapViewItemizedOverlay<T> {
+
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ public static final int DESCRIPTION_BOX_PADDING = 3;
+ public static final int DESCRIPTION_BOX_CORNERWIDTH = 3;
+
+ public static final int DESCRIPTION_LINE_HEIGHT = 12;
+ /** Additional to <code>DESCRIPTION_LINE_HEIGHT</code>. */
+ public static final int DESCRIPTION_TITLE_EXTRA_LINE_HEIGHT = 2;
+
+
+ protected static final Point DEFAULTMARKER_FOCUSED_HOTSPOT = new Point(10, 19);
+ protected static final int DEFAULTMARKER_BACKGROUNDCOLOR = Color.rgb(101, 185, 74);
+
+ protected static final int DESCRIPTION_MAXWIDTH = 200;
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final Point mMarkerFocusedHotSpot;
+ protected final Drawable mMarkerFocusedBase;
+ protected final int mMarkerFocusedBackgroundColor;
+ protected final int mMarkerFocusedWidth, mMarkerFocusedHeight;
+ protected final Paint mMarkerBackgroundPaint, mDescriptionPaint, mTitlePaint;
+
+ protected int mFocusedItemIndex;
+ protected boolean mFocusItemsOnTap;
+ private Point mFocusedScreenCoords = new Point();
+
+ private final String UNKNOWN;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public OpenStreetMapViewItemizedOverlayWithFocus(final Context ctx, final List<T> aList, final OnItemTapListener<T> aOnItemTapListener) {
+ this(ctx, aList, null, null, null, null, NOT_SET, aOnItemTapListener);
+ }
+
+ public OpenStreetMapViewItemizedOverlayWithFocus(final Context ctx, final List<T> aList, final Drawable pMarker, final Point pMarkerHotspot, final Drawable pMarkerFocusedBase, final Point pMarkerFocusedHotSpot, final int pFocusedBackgroundColor, final OnItemTapListener<T> aOnItemTapListener) {
+ super(ctx, aList, pMarkerFocusedBase, pMarkerHotspot, aOnItemTapListener);
+
+ UNKNOWN = ctx.getString(R.string.unknown);
+
+ this.mMarkerFocusedBase = (pMarkerFocusedBase != null) ? pMarkerFocusedBase : ctx.getResources().getDrawable(R.drawable.marker_default_focused_base);
+
+ this.mMarkerFocusedHotSpot = (pMarkerFocusedHotSpot != null) ? pMarkerFocusedHotSpot : DEFAULTMARKER_FOCUSED_HOTSPOT;
+
+ if(pFocusedBackgroundColor != NOT_SET)
+ this.mMarkerFocusedBackgroundColor = pFocusedBackgroundColor;
+ else
+ this.mMarkerFocusedBackgroundColor = DEFAULTMARKER_BACKGROUNDCOLOR;
+
+ this.mMarkerBackgroundPaint = new Paint(); // Color is set in onDraw(...)
+
+ this.mDescriptionPaint = new Paint();
+ this.mDescriptionPaint.setAntiAlias(true);
+ this.mTitlePaint = new Paint();
+ this.mTitlePaint.setFakeBoldText(true);
+ this.mTitlePaint.setAntiAlias(true);
+
+ this.mMarkerFocusedWidth = this.mMarkerFocusedBase.getIntrinsicWidth();
+ this.mMarkerFocusedHeight = this.mMarkerFocusedBase.getIntrinsicHeight();
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public void setFocusedItem(final int pIndex){
+ this.mFocusedItemIndex = pIndex;
+ }
+
+ public void unSetFocusedItem(){
+ this.mFocusedItemIndex = NOT_SET;
+ }
+
+ public void setFocusedItem(final T pItem){
+ final int indexFound = super.mItemList.indexOf(pItem);
+ if(indexFound < 0)
+ throw new IllegalArgumentException();
+
+ this.setFocusedItem(indexFound);
+ }
+
+ public void setFocusItemsOnTap(final boolean doit) {
+ this.mFocusItemsOnTap = doit;
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ protected boolean onTap(int pIndex) {
+ if(this.mFocusItemsOnTap)
+ this.mFocusedItemIndex = pIndex;
+
+ return super.onTap(pIndex);
+ }
+
+ @Override
+ protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
+ if(this.mFocusedItemIndex != NOT_SET){
+ /* Calculate and set the bounds of the marker. */
+ final int left = this.mFocusedScreenCoords.x - this.mMarkerFocusedHotSpot.x;
+ final int right = left + this.mMarkerFocusedWidth;
+ final int top = this.mFocusedScreenCoords.y - this.mMarkerFocusedHotSpot.y;
+ final int bottom = top + this.mMarkerFocusedHeight;
+ this.mMarkerFocusedBase.setBounds(left, top, right, bottom);
+
+ /* Strings of the OverlayItem, we need. */
+ final T focusedItem = super.mItemList.get(this.mFocusedItemIndex);
+ final String itemTitle = (focusedItem.mTitle == null) ? UNKNOWN : focusedItem.mTitle;
+ final String itemDescription = (focusedItem.mDescription == null) ? UNKNOWN : focusedItem.mDescription;
+
+ /* Store the width needed for each char in the description to a float array. This is pretty efficient. */
+ final float[] widths = new float[itemDescription.length()];
+ this.mDescriptionPaint.getTextWidths(itemDescription, widths);
+
+ final StringBuilder sb = new StringBuilder();
+ int maxWidth = 0;
+ int curLineWidth = 0;
+ int lastStop = 0;
+ int i;
+ int lastwhitespace = 0;
+ /* Loop through the charwidth array and harshly insert a linebreak,
+ * when the width gets bigger than DESCRIPTION_MAXWIDTH. */
+ for (i = 0; i < widths.length; i++) {
+ if(!Character.isLetter(itemDescription.charAt(i)))
+ lastwhitespace = i;
+
+ float charwidth = widths[i];
+
+ if(curLineWidth + charwidth> DESCRIPTION_MAXWIDTH){
+ if(lastStop == lastwhitespace)
+ i--;
+ else
+ i = lastwhitespace;
+
+
+ sb.append(itemDescription.subSequence(lastStop, i));
+ sb.append('\n');
+
+ lastStop = i;
+ maxWidth = Math.max(maxWidth, curLineWidth);
+ curLineWidth = 0;
+ }
+
+ curLineWidth += charwidth;
+ }
+ /* Add the last line to the rest to the buffer. */
+ if(i != lastStop){
+ final String rest = itemDescription.substring(lastStop, i);
+
+ maxWidth = Math.max(maxWidth, (int)this.mDescriptionPaint.measureText(rest));
+
+ sb.append(rest);
+ }
+ final String[] lines = sb.toString().split("\n");
+
+ /* The title also needs to be taken into consideration for the width calculation. */
+ final int titleWidth = (int)this.mDescriptionPaint.measureText(itemTitle);
+
+ maxWidth = Math.max(maxWidth, titleWidth);
+ final int descWidth = Math.min(maxWidth, DESCRIPTION_MAXWIDTH);
+
+ /* Calculate the bounds of the Description box that needs to be drawn. */
+ final int descBoxLeft = left - descWidth / 2 - DESCRIPTION_BOX_PADDING + this.mMarkerFocusedWidth / 2;
+ final int descBoxRight = descBoxLeft + descWidth + 2 * DESCRIPTION_BOX_PADDING;
+ final int descBoxBottom = top;
+ final int descBoxTop = descBoxBottom
+ - DESCRIPTION_TITLE_EXTRA_LINE_HEIGHT
+ - (lines.length + 1) * DESCRIPTION_LINE_HEIGHT /* +1 because of the title. */
+ - 2 * DESCRIPTION_BOX_PADDING;
+
+ /* Twice draw a RoundRect, once in black with 1px as a small border. */
+ this.mMarkerBackgroundPaint.setColor(Color.BLACK);
+ c.drawRoundRect(new RectF(descBoxLeft - 1, descBoxTop - 1, descBoxRight + 1, descBoxBottom + 1),
+ DESCRIPTION_BOX_CORNERWIDTH, DESCRIPTION_BOX_CORNERWIDTH,
+ this.mDescriptionPaint);
+ this.mMarkerBackgroundPaint.setColor(this.mMarkerFocusedBackgroundColor);
+ c.drawRoundRect(new RectF(descBoxLeft, descBoxTop, descBoxRight, descBoxBottom),
+ DESCRIPTION_BOX_CORNERWIDTH, DESCRIPTION_BOX_CORNERWIDTH,
+ this.mMarkerBackgroundPaint);
+
+ final int descLeft = descBoxLeft + DESCRIPTION_BOX_PADDING;
+ int descTextLineBottom = descBoxBottom - DESCRIPTION_BOX_PADDING;
+
+ /* Draw all the lines of the description. */
+ for(int j = lines.length - 1; j >= 0; j--){
+ c.drawText(lines[j].trim(), descLeft, descTextLineBottom, this.mDescriptionPaint);
+ descTextLineBottom -= DESCRIPTION_LINE_HEIGHT;
+ }
+ /* Draw the title. */
+ c.drawText(itemTitle, descLeft, descTextLineBottom - DESCRIPTION_TITLE_EXTRA_LINE_HEIGHT, this.mTitlePaint);
+ c.drawLine(descBoxLeft, descTextLineBottom, descBoxRight, descTextLineBottom, mDescriptionPaint);
+
+ /* Finally draw the marker base. This is done in the end to make it look better. */
+ this.mMarkerFocusedBase.draw(c);
+ }
+ }
+
+ @Override
+ protected void onDrawItem(final Canvas c, final int index, final Point screenCoords) {
+ if(this.mFocusedItemIndex != NOT_SET && index == this.mFocusedItemIndex){
+ /* Actual draw will take place in onDrawFinished. */
+ /* Because we are reusing the screencoords apssed here, we cannot simply store the reference. */
+ this.mFocusedScreenCoords.set(screenCoords.x, screenCoords.y);
+ }else{
+ super.onDrawItem(c, index, screenCoords);
+ }
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlay.java
new file mode 100644
index 0000000..a5830ac
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlay.java
@@ -0,0 +1,150 @@
+// Created by plusminus on 20:32:01 - 27.09.2008
+package org.andnav.osm.views.overlay;
+
+import org.andnav.osm.views.OpenStreetMapView;
+import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
+
+import android.graphics.Canvas;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+
+/**
+ * Base class representing an overlay which may be displayed on top of a
+ * {@link OpenStreetMapView}. To add an overlay, subclass this class, create an
+ * instance, and add it to the list obtained from getOverlays() of
+ * {@link OpenStreetMapView}.
+ *
+ * @author Nicolas Gramlich
+ */
+public abstract class OpenStreetMapViewOverlay implements OpenStreetMapViewConstants {
+
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods for SuperClass/Interfaces
+ // ===========================================================
+
+ /**
+ * Managed Draw calls gives Overlays the possibility to first draw manually
+ * and after that do a final draw. This is very useful, i sth. to be drawn
+ * needs to be <b>topmost</b>.
+ */
+ public void onManagedDraw(final Canvas c, final OpenStreetMapView osmv) {
+ onDraw(c, osmv);
+ onDrawFinished(c, osmv);
+ }
+
+ protected abstract void onDraw(final Canvas c, final OpenStreetMapView osmv);
+
+ protected abstract void onDrawFinished(final Canvas c,
+ final OpenStreetMapView osmv);
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ /**
+ * By default does nothing (<code>return false</code>). If you handled the
+ * Event, return <code>true</code>, otherwise return <code>false</code>. If
+ * you returned <code>true</code> none of the following Overlays or the
+ * underlying {@link OpenStreetMapView} has the chance to handle this event.
+ */
+ public boolean onKeyDown(final int keyCode, KeyEvent event,
+ final OpenStreetMapView mapView) {
+ return false;
+ }
+
+ /**
+ * By default does nothing (<code>return false</code>). If you handled the
+ * Event, return <code>true</code>, otherwise return <code>false</code>. If
+ * you returned <code>true</code> none of the following Overlays or the
+ * underlying {@link OpenStreetMapView} has the chance to handle this event.
+ */
+ public boolean onKeyUp(final int keyCode, KeyEvent event,
+ final OpenStreetMapView mapView) {
+ return false;
+ }
+
+ /**
+ * <b>You can prevent all(!) other Touch-related events from happening!</b><br />
+ * By default does nothing (<code>return false</code>). If you handled the
+ * Event, return <code>true</code>, otherwise return <code>false</code>. If
+ * you returned <code>true</code> none of the following Overlays or the
+ * underlying {@link OpenStreetMapView} has the chance to handle this event.
+ */
+ public boolean onTouchEvent(final MotionEvent event,
+ final OpenStreetMapView mapView) {
+ return false;
+ }
+
+ /**
+ * By default does nothing (<code>return false</code>). If you handled the
+ * Event, return <code>true</code>, otherwise return <code>false</code>. If
+ * you returned <code>true</code> none of the following Overlays or the
+ * underlying {@link OpenStreetMapView} has the chance to handle this event.
+ */
+ public boolean onTrackballEvent(final MotionEvent event,
+ final OpenStreetMapView mapView) {
+ return false;
+ }
+
+ /**
+ * By default does nothing (<code>return false</code>). If you handled the
+ * Event, return <code>true</code>, otherwise return <code>false</code>. If
+ * you returned <code>true</code> none of the following Overlays or the
+ * underlying {@link OpenStreetMapView} has the chance to handle this event.
+ */
+ public boolean onSingleTapUp(MotionEvent e,
+ OpenStreetMapView openStreetMapView) {
+ return false;
+ }
+
+ /**
+ * By default does nothing (<code>return false</code>). If you handled the
+ * Event, return <code>true</code>, otherwise return <code>false</code>. If
+ * you returned <code>true</code> none of the following Overlays or the
+ * underlying {@link OpenStreetMapView} has the chance to handle this event.
+ */
+ public boolean onLongPress(MotionEvent e,
+ OpenStreetMapView openStreetMapView) {
+ return false;
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+
+ /**
+ * Interface definition for overlays that contain items that can be snapped
+ * to (for example, when the user invokes a zoom, this could be called
+ * allowing the user to snap the zoom to an interesting point.)
+ */
+ public interface Snappable {
+
+ /**
+ * Checks to see if the given x and y are close enough to an item resulting in snapping the current action (e.g. zoom) to the item.
+ * @param x The x in screen coordinates.
+ * @param y The y in screen coordinates.
+ * @param snapPoint To be filled with the the interesting point (in screen coordinates) that is closest to the given x and y. Can be untouched if not snapping.
+ * @param mapView The OpenStreetMapView that is requesting the snap. Use MapView.getProjection() to convert between on-screen pixels and latitude/longitude pairs.
+ * @return Whether or not to snap to the interesting point.
+ */
+ boolean onSnapToItem(int x, int y, android.graphics.Point snapPoint,
+ OpenStreetMapView mapView);
+ }
+
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlayItem.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlayItem.java
new file mode 100644
index 0000000..d48d3f9
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewOverlayItem.java
@@ -0,0 +1,54 @@
+// Created by plusminus on 00:02:58 - 03.10.2008
+package org.andnav.osm.views.overlay;
+
+import org.andnav.osm.util.GeoPoint;
+
+/**
+ * Immutable class describing a GeoPoint with a Title and a Description.
+ * @author Nicolas Gramlich
+ *
+ */
+public class OpenStreetMapViewOverlayItem {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ public final String mTitle;
+ public final String mDescription;
+ public final GeoPoint mGeoPoint;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ /**
+ * @param aTitle this should be <b>singleLine</b> (no <code>'\n'</code> )
+ * @param aDescription a <b>multiLine</b> description ( <code>'\n'</code> possible)
+ * @param aGeoPoint
+ */
+ public OpenStreetMapViewOverlayItem(final String aTitle, final String aDescription, final GeoPoint aGeoPoint) {
+ this.mTitle = aTitle;
+ this.mDescription = aDescription;
+ this.mGeoPoint = aGeoPoint;
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewPathOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewPathOverlay.java
new file mode 100644
index 0000000..6d045b9
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewPathOverlay.java
@@ -0,0 +1,203 @@
+package org.andnav.osm.views.overlay;
+
+import java.util.ArrayList;
+
+import org.andnav.osm.views.OpenStreetMapView;
+import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
+import org.andnav.osm.util.GeoPoint;
+
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Point;
+import android.graphics.Rect;
+
+
+/**
+ *
+ * @author Viesturs Zarins
+ *
+ * This class draws a path line in given color.
+ */
+public class OpenStreetMapViewPathOverlay extends OpenStreetMapViewOverlay
+{
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ /**
+ * Stores points, converted to the map projection.
+ */
+ private ArrayList<Point> mPoints;
+
+ /**
+ * Number of points that have precomputed values.
+ */
+ private int mPointsPrecomputed;
+
+ /**
+ * Paint settings.
+ */
+ protected final Paint mPaint = new Paint();
+
+
+ /**
+ * Point cache for Canvas.drawLines.
+ */
+ static final int POINT_BUFFER_SIZE = 256; //should be a multiple of 4
+ private float[] mPointBuffer = new float[POINT_BUFFER_SIZE];
+
+ private final Point mTempPoint1 = new Point();
+ private final Point mTempPoint2 = new Point();
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+
+ public OpenStreetMapViewPathOverlay(int color)
+ {
+ this.mPaint.setColor(color);
+ this.mPaint.setStrokeWidth(2.0f);
+
+ this.clearPath();
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public void setColor(int color)
+ {
+ this.mPaint.setColor(color);
+ }
+
+ public void setAlpha(int a)
+ {
+ this.mPaint.setAlpha(a);
+ }
+
+ public void clearPath()
+ {
+ this.mPoints = new ArrayList<Point>();
+ this.mPointsPrecomputed = 0;
+ }
+
+ public void addPoint(GeoPoint pt)
+ {
+ this.addPoint(pt.getLatitudeE6(), pt.getLongitudeE6());
+ }
+
+ public void addPoint(int latitudeE6, int longitudeE6)
+ {
+ this.mPoints.add(new Point(latitudeE6, longitudeE6));
+ }
+
+ public int getNumberOfPoints() {
+ return this.mPoints.size();
+ }
+
+
+ /**
+ * This method draws the line.
+ * Note - highly optimized to handle long paths, proceed with care. Should be fine up to 10K points.
+ */
+ @Override
+ protected void onDraw(Canvas canvas, OpenStreetMapView mapView)
+ {
+ if (this.mPoints.size() < 2)
+ {
+ //nothing to paint
+ return;
+ }
+
+ final OpenStreetMapViewProjection pj = mapView.getProjection();
+
+ //precompute new points to the intermediate projection.
+ int size = this.mPoints.size();
+
+ while (this.mPointsPrecomputed < size)
+ {
+ Point pt = this.mPoints.get(this.mPointsPrecomputed);
+ pj.toMapPixelsProjected(pt.x, pt.y, pt);
+
+ this.mPointsPrecomputed ++;
+ }
+
+ Point screenPoint0 = null; //points on screen
+ Point screenPoint1 = null;
+ Point projectedPoint0; //points from the points list
+ Point projectedPoint1;
+
+ float [] buffer = this.mPointBuffer;
+ int bufferCount = 0;
+ Rect clipBounds = pj.fromPixelsToProjected(canvas.getClipBounds()); // clipping rectangle in the intermediate projection, to avoid performing projection.
+ Rect lineBounds = new Rect(); // bounding rectangle for the current line segment.
+
+ projectedPoint0 = this.mPoints.get(size - 1);
+ lineBounds.set(projectedPoint0.x, projectedPoint0.y, projectedPoint0.x, projectedPoint0.y);
+
+ for(int i = size - 2; i >= 0; i--)
+ {
+ //compute next points
+ projectedPoint1 = this.mPoints.get(i);
+ lineBounds.union(projectedPoint1.x, projectedPoint1.y);
+
+ if (!Rect.intersects(clipBounds, lineBounds))
+ {
+ //skip this line, move to next point
+ projectedPoint0 = projectedPoint1;
+ screenPoint0 = null;
+ continue;
+ }
+
+ // the starting point may be not calculated, because previous segment was out of clip bounds
+ if (screenPoint0 == null)
+ {
+ screenPoint0 = pj.toMapPixelsTranslated(projectedPoint0, this.mTempPoint1);
+ }
+
+ screenPoint1 = pj.toMapPixelsTranslated(projectedPoint1, this.mTempPoint2);
+
+ //skip this point, too close to previous point
+ if (Math.abs(screenPoint1.x - screenPoint0.x) + Math.abs(screenPoint1.y - screenPoint0.y) <= 1)
+ {
+ continue;
+ }
+
+ //add new line to buffer
+ buffer[bufferCount] = screenPoint0.x;
+ buffer[bufferCount + 1] = screenPoint0.y;
+ buffer[bufferCount + 2] = screenPoint1.x;
+ buffer[bufferCount + 3] = screenPoint1.y;
+ bufferCount += 4;
+
+ if (bufferCount == POINT_BUFFER_SIZE)
+ {
+ canvas.drawLines(buffer, this.mPaint);
+ bufferCount = 0;
+ }
+
+ //update starting point to next position
+ projectedPoint0 = projectedPoint1;
+ screenPoint0.x = screenPoint1.x;
+ screenPoint0.y = screenPoint1.y;
+ lineBounds.set(projectedPoint0.x, projectedPoint0.y, projectedPoint0.x, projectedPoint0.y);
+ }
+
+ if (bufferCount >0 )
+ {
+ canvas.drawLines(buffer, 0, bufferCount, this.mPaint);
+ }
+ }
+
+ @Override
+ protected void onDrawFinished(Canvas c, OpenStreetMapView osmv)
+ {
+ //nothing here
+ }
+
+}
diff --git a/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewSimpleLocationOverlay.java b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewSimpleLocationOverlay.java
new file mode 100644
index 0000000..c6cfd20
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/overlay/OpenStreetMapViewSimpleLocationOverlay.java
@@ -0,0 +1,81 @@
+// Created by plusminus on 22:01:11 - 29.09.2008
+package org.andnav.osm.views.overlay;
+
+import org.andnav.osm.R;
+import org.andnav.osm.util.GeoPoint;
+import org.andnav.osm.views.OpenStreetMapView;
+import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Point;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class OpenStreetMapViewSimpleLocationOverlay extends OpenStreetMapViewOverlay {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected final Paint mPaint = new Paint();
+
+ protected final Bitmap PERSON_ICON;
+ /** Coordinates the feet of the person are located. */
+ protected final android.graphics.Point PERSON_HOTSPOT = new android.graphics.Point(24,39);
+
+ protected GeoPoint mLocation;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public OpenStreetMapViewSimpleLocationOverlay(final Context ctx){
+ this.PERSON_ICON = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.person);
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public void setLocation(final GeoPoint mp){
+ this.mLocation = mp;
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ protected void onDrawFinished(Canvas c, OpenStreetMapView osmv) {
+ return;
+ }
+
+ @Override
+ public void onDraw(final Canvas c, final OpenStreetMapView osmv) {
+ if(this.mLocation != null){
+ final OpenStreetMapViewProjection pj = osmv.getProjection();
+ final Point screenCoords = new Point();
+ pj.toMapPixels(this.mLocation, screenCoords);
+
+ c.drawBitmap(PERSON_ICON, screenCoords.x - PERSON_HOTSPOT.x, screenCoords.y - PERSON_HOTSPOT.y, this.mPaint);
+ }
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/LRUMapTileCache.java b/cardroid/src/org/andnav/osm/views/util/LRUMapTileCache.java
new file mode 100644
index 0000000..bc7ea8a
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/LRUMapTileCache.java
@@ -0,0 +1,58 @@
+package org.andnav.osm.views.util;
+
+import java.util.ConcurrentModificationException;
+import java.util.LinkedHashMap;
+
+import org.andnav.osm.tileprovider.OpenStreetMapTile;
+import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
+
+import android.graphics.Bitmap;
+import android.util.Log;
+
+public class LRUMapTileCache extends LinkedHashMap<OpenStreetMapTile, Bitmap> implements OpenStreetMapViewConstants {
+
+ private static final long serialVersionUID = -541142277575493335L;
+
+ private int mCapacity;
+
+ public LRUMapTileCache(final int aCapacity) {
+ super(aCapacity + 2, 0.1f, true);
+ mCapacity = aCapacity;
+ }
+
+ public void ensureCapacity(final int aCapacity) {
+ if (aCapacity > mCapacity) {
+ mCapacity = aCapacity;
+ }
+ }
+
+ @Override
+ public Bitmap remove(final Object aKey) {
+ final Bitmap bm = super.remove(aKey);
+ if (bm != null) {
+ bm.recycle();
+ }
+ return bm;
+ }
+
+ @Override
+ public void clear() {
+ // remove them all individually so that they get recycled
+ try {
+ for (final OpenStreetMapTile key : keySet()) {
+ remove(key);
+ }
+ } catch (final ConcurrentModificationException ignore) {
+ Log.i(DEBUGTAG, "ConcurrentModificationException clearing tile cache");
+ }
+
+ // and then clear
+ super.clear();
+ }
+
+ @Override
+ protected boolean removeEldestEntry(final Entry<OpenStreetMapTile, Bitmap> aEldest) {
+ return size() > mCapacity;
+ }
+
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/Mercator.java b/cardroid/src/org/andnav/osm/views/util/Mercator.java
new file mode 100644
index 0000000..1ebe12f
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/Mercator.java
@@ -0,0 +1,134 @@
+// Created by plusminus on 17:53:07 - 25.09.2008
+package org.andnav.osm.views.util;
+
+import org.andnav.osm.util.BoundingBoxE6;
+import org.andnav.osm.util.GeoPoint;
+import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
+
+import android.graphics.Point;
+
+/**
+ * http://wiki.openstreetmap.org/index.php/Mercator
+ * @author Nicolas Gramlich
+ *
+ */
+public class Mercator implements OpenStreetMapViewConstants {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ final static double DEG2RAD = Math.PI / 180;
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ /**
+ * Mercator projection of GeoPoint at given zoom level
+ * @param aLat latitude in degrees [-89000000 to 89000000]
+ * @param aLon longitude in degrees [-180000000 to 180000000]
+ * @param zoom zoom level
+ * @param aUseAsReturnValue
+ * @return Point with x,y in the range [-2^(zoom-1) to 2^(zoom-1)]
+ */
+ public static int[] projectGeoPoint(final int aLatE6, final int aLonE6, final int aZoom, final int[] reuse) {
+ return projectGeoPoint(aLatE6 * 1E-6, aLonE6 * 1E-6, aZoom, reuse);
+ }
+
+ /**
+ * Mercator projection of GeoPoint at given zoom level
+ * @param aLat latitude in degrees [-89 to 89]
+ * @param aLon longitude in degrees [-180 to 180]
+ * @param zoom zoom level
+ * @param aUseAsReturnValue
+ * @return Point with x,y in the range [-2^(zoom-1) to 2^(zoom-1)]
+ */
+ public static int[] projectGeoPoint(final double aLat, final double aLon, final int aZoom, final int[] aUseAsReturnValue) {
+ final int[] out = (aUseAsReturnValue != null) ? aUseAsReturnValue : new int[2];
+
+ out[MAPTILE_LONGITUDE_INDEX] = (int) Math.floor((aLon + 180) / 360 * (1 << aZoom));
+ out[MAPTILE_LATITUDE_INDEX] = (int) Math.floor((1 - Math.log(Math.tan(aLat * DEG2RAD) + 1 / Math.cos(aLat * DEG2RAD)) / Math.PI) / 2 * (1 << aZoom));
+
+ return out;
+ }
+
+ /**
+ * Mercator projection of GeoPoint at given zoom level
+ * @param aGeoPoint
+ * @param zoom zoom level
+ * @param aUseAsReturnValue
+ * @return Point with x,y in the range [-2^(zoom-1) to 2^(zoom-1)]
+ */
+ public static Point projectGeoPoint(final GeoPoint aGeoPoint, final int aZoom, final Point aUseAsReturnValue) {
+ final Point p = (aUseAsReturnValue != null) ? aUseAsReturnValue : new Point();
+
+ final double aLon = aGeoPoint.getLongitudeE6()*1E-6;
+ final double aLat = aGeoPoint.getLatitudeE6()*1E-6;
+ p.x = (int) Math.floor((aLon + 180) / 360 * (1 << aZoom));
+ p.y = (int) Math.floor((1 - Math.log(Math.tan(aLat * DEG2RAD) + 1 / Math.cos(aLat * DEG2RAD)) / Math.PI) / 2 * (1 << aZoom));
+
+ return p;
+ }
+
+ /**
+ * Get bounding box from reverse Mercator projection.
+ * @param left
+ * @param top
+ * @param right
+ * @param bottom
+ * @param zoom
+ * @return
+ */
+ public static BoundingBoxE6 getBoundingBoxFromCoords(final int left, final int top, final int right, final int bottom, final int zoom) {
+ return new BoundingBoxE6(tile2lat(top, zoom), tile2lon(right, zoom), tile2lat(bottom, zoom), tile2lon(left, zoom));
+ }
+
+ /**
+ * Get bounding box from reverse Mercator projection.
+ * @param aMapTile
+ * @param aZoom
+ * @return
+ */
+ public static BoundingBoxE6 getBoundingBoxFromMapTile(final int[] aMapTile, final int aZoom) {
+ final int y = aMapTile[MAPTILE_LATITUDE_INDEX];
+ final int x = aMapTile[MAPTILE_LONGITUDE_INDEX];
+ return new BoundingBoxE6(tile2lat(y, aZoom), tile2lon(x + 1, aZoom), tile2lat(y + 1, aZoom), tile2lon(x, aZoom));
+ }
+
+ /**
+ * Reverse Mercator projection of Point at given zoom level
+ *
+ */
+ public static GeoPoint projectPoint(int x, int y, int aZoom) {
+ return new GeoPoint((int)(tile2lat(y, aZoom)*1E6), (int)(tile2lon(x, aZoom)*1E6));
+ }
+
+ public static double tile2lon(int x, int aZoom) {
+ return ((double)x / (1 << aZoom) * 360.0) - 180;
+ }
+
+ public static double tile2lat(int y, int aZoom) {
+ final double n = Math.PI - ((2.0 * Math.PI * y) / (1 << aZoom));
+ return 180.0 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/MyMath.java b/cardroid/src/org/andnav/osm/views/util/MyMath.java
new file mode 100644
index 0000000..408bf9b
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/MyMath.java
@@ -0,0 +1,70 @@
+// Created by plusminus on 20:36:01 - 26.09.2008
+package org.andnav.osm.views.util;
+
+import org.andnav.osm.views.util.constants.MathConstants;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class MyMath implements MathConstants {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ /**
+ * Calculates i.e. the increase of zoomlevel needed when the visible latitude needs to be bigger by <code>factor</code>.
+ *
+ * Assert.assertEquals(1, getNextSquareNumberAbove(1.1f));
+ * Assert.assertEquals(2, getNextSquareNumberAbove(2.1f));
+ * Assert.assertEquals(2, getNextSquareNumberAbove(3.9f));
+ * Assert.assertEquals(3, getNextSquareNumberAbove(4.1f));
+ * Assert.assertEquals(3, getNextSquareNumberAbove(7.9f));
+ * Assert.assertEquals(4, getNextSquareNumberAbove(8.1f));
+ * Assert.assertEquals(5, getNextSquareNumberAbove(16.1f));
+ *
+ * Assert.assertEquals(-1, - getNextSquareNumberAbove(1 / 0.4f) + 1);
+ * Assert.assertEquals(-2, - getNextSquareNumberAbove(1 / 0.24f) + 1);
+ *
+ * @param factor
+ * @return
+ */
+ public static int getNextSquareNumberAbove(final float factor){
+ int out = 0;
+ int cur = 1;
+ int i = 1;
+ while(true){
+ if(cur > factor)
+ return out;
+
+ out = i;
+ cur *= 2;
+ i++;
+ }
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapRendererInfo.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapRendererInfo.java
new file mode 100644
index 0000000..bec8c98
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapRendererInfo.java
@@ -0,0 +1,96 @@
+// Created by plusminus on 18:23:16 - 25.09.2008
+package org.andnav.osm.views.util;
+
+import java.util.Random;
+
+import org.andnav.osm.R;
+import org.andnav.osm.tileprovider.OpenStreetMapTile;
+
+/**
+ * The OpenStreetMapRendererInfo stores information about available tile servers.
+ * @author Nicolas Gramlich
+ *
+ */
+public enum OpenStreetMapRendererInfo {
+ OSMARENDER(R.string.osmarender, ".png", 0, 17, 8, CodeScheme.X_Y,"http://tah.openstreetmap.org/Tiles/tile/"),
+ MAPNIK(R.string.mapnik, ".png", 0, 18, 8, CodeScheme.X_Y,"http://tile.openstreetmap.org/"),
+ CYCLEMAP(R.string.cyclemap, ".png", 0, 17, 8, CodeScheme.X_Y,
+ "http://a.andy.sandbox.cloudmade.com/tiles/cycle/",
+ "http://b.andy.sandbox.cloudmade.com/tiles/cycle/",
+ "http://c.andy.sandbox.cloudmade.com/tiles/cycle/"),
+ OPENARIELMAP( R.string.openareal_sat, ".jpg", 0, 13, 8, CodeScheme.X_Y,"http://tile.openaerialmap.org/tiles/1.0.0/openaerialmap-900913/"),
+ BASE( R.string.base, ".png", 4, 17, 8, CodeScheme.X_Y,"http://topo.openstreetmap.de/base/"),
+ TOPO(R.string.topo, ".png", 4, 17, 8, CodeScheme.X_Y,"http://topo.openstreetmap.de/topo/"),
+ HILLS(R.string.hills, ".png", 8, 17, 8, CodeScheme.X_Y,"http://topo.geofabrik.de/hills/"),
+ CLOUDMADESMALLTILES(R.string.cloudmade_small, ".png", 0, 13, 6, CodeScheme.X_Y,"http://tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/2/64/"),
+ CLOUDMADESTANDARDTILES(R.string.cloudmade_standard, ".png", 0, 18, 8, CodeScheme.X_Y,"http://tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/2/256/");
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ public enum CodeScheme { X_Y, QUAD_TREE };
+
+ public final String BASEURLS[], IMAGE_FILENAMEENDING;
+ public final int NAME, ZOOM_MINLEVEL, ZOOM_MAXLEVEL, MAPTILE_ZOOM, MAPTILE_SIZEPX;
+ public final CodeScheme CODE_SCHEME;
+ private final Random random;
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ private OpenStreetMapRendererInfo(final int aName,
+ final String aImageFilenameEnding, final int aZoomMin,
+ final int aZoomMax, final int aTileZoom, final CodeScheme aCodeScheme,final String ...aBaseUrl) {
+ this.BASEURLS = aBaseUrl;
+ this.NAME = aName;
+ this.ZOOM_MINLEVEL = aZoomMin;
+ this.ZOOM_MAXLEVEL = aZoomMax;
+ this.IMAGE_FILENAMEENDING = aImageFilenameEnding;
+ this.MAPTILE_ZOOM = aTileZoom;
+ this.MAPTILE_SIZEPX = 1<<aTileZoom;
+ this.CODE_SCHEME = aCodeScheme;
+ this.random = new Random();
+ }
+
+ public static OpenStreetMapRendererInfo getDefault() {
+ return MAPNIK;
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ public String getTileURLString(final OpenStreetMapTile aTile) {
+ final CodeScheme cs = this.CODE_SCHEME;
+ final String baseurl = BASEURLS[random.nextInt()%BASEURLS.length];
+ switch (cs) {
+ case QUAD_TREE:
+ return String.format("%s%s%s", baseurl, quadTree(aTile), this.IMAGE_FILENAMEENDING);
+ case X_Y:
+ default:
+ return String.format("%s%d/%d/%d%s", baseurl, aTile.getZoomLevel(), aTile.getX(), aTile.getY(), this.IMAGE_FILENAMEENDING);
+ }
+ }
+
+ /**
+ * Converts TMS tile coordinates to QuadTree
+ * @param aTile The tile coordinates to convert
+ * @return The QuadTree as String.
+ */
+ private String quadTree(final OpenStreetMapTile aTile) {
+ final StringBuilder quadKey = new StringBuilder();
+ for (int i = aTile.getZoomLevel(); i > 0; i--) {
+ int digit = 0;
+ int mask = 1 << (i - 1);
+ if ((aTile.getX() & mask) != 0)
+ digit += 1;
+ if ((aTile.getY() & mask) != 0)
+ digit += 2;
+ quadKey.append("" + digit);
+ }
+
+ return quadKey.toString();
+ }
+
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java
new file mode 100644
index 0000000..7c426e4
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java
@@ -0,0 +1,77 @@
+// Created by plusminus on 17:58:57 - 25.09.2008
+package org.andnav.osm.views.util;
+
+import org.andnav.osm.tileprovider.OpenStreetMapTile;
+import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
+
+import android.graphics.Bitmap;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public class OpenStreetMapTileCache implements OpenStreetMapViewConstants {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+
+ protected LRUMapTileCache mCachedTiles;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public OpenStreetMapTileCache() {
+ this(CACHE_MAPTILECOUNT_DEFAULT);
+ }
+
+ /**
+ * @param aMaximumCacheSize Maximum amount of MapTiles to be hold within.
+ */
+ public OpenStreetMapTileCache(final int aMaximumCacheSize){
+ this.mCachedTiles = new LRUMapTileCache(aMaximumCacheSize);
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ public void ensureCapacity(final int aCapacity) {
+ mCachedTiles.ensureCapacity(aCapacity);
+ }
+
+ public synchronized Bitmap getMapTile(final OpenStreetMapTile aTile) {
+ return this.mCachedTiles.get(aTile);
+ }
+
+ public synchronized void putTile(final OpenStreetMapTile aTile, final Bitmap aImage) {
+ if (aImage != null) {
+ this.mCachedTiles.put(aTile, aImage);
+ }
+ }
+
+ // ===========================================================
+ // Methods from SuperClass/Interfaces
+ // ===========================================================
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ public boolean containsTile(final OpenStreetMapTile aTile) {
+ return this.mCachedTiles.containsKey(aTile);
+ }
+
+ public void clear() {
+ this.mCachedTiles.clear();
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java
new file mode 100644
index 0000000..498af84
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java
@@ -0,0 +1,95 @@
+// Created by plusminus on 21:46:22 - 25.09.2008
+package org.andnav.osm.views.util;
+
+import java.io.File;
+
+import org.andnav.osm.services.IOpenStreetMapTileProviderService;
+import org.andnav.osm.tileprovider.OpenStreetMapTile;
+import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ResolveInfo;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.os.Handler;
+import android.util.Log;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public abstract class OpenStreetMapTileProvider implements OpenStreetMapViewConstants {
+
+ protected final OpenStreetMapTileCache mTileCache;
+ protected final Handler mDownloadFinishedHandler;
+
+ public OpenStreetMapTileProvider(final Handler pDownloadFinishedListener) {
+ mTileCache = new OpenStreetMapTileCache();
+ mDownloadFinishedHandler = pDownloadFinishedListener;
+ }
+
+ /**
+ * Get a tile provider.
+ * If a tile provider service exists then it will use the service,
+ * otherwise it'll use a direct tile provider that doesn't use a service
+ * @param pContext
+ * @param pDownloadFinishedListener
+ * @return
+ */
+ public static OpenStreetMapTileProvider getInstance(final Context pContext,
+ final Handler pDownloadFinishedListener) {
+ final Intent intent = new Intent(IOpenStreetMapTileProviderService.class.getName());
+ final ResolveInfo ri = pContext.getPackageManager().resolveService(intent, 0);
+ if (ri == null) {
+ Log.i(DEBUGTAG, "Service not found - using direct tile provider");
+ return new OpenStreetMapTileProviderDirect(pDownloadFinishedListener);
+ } else {
+ Log.i(DEBUGTAG, "Using tile provider service");
+ return new OpenStreetMapTileProviderService(pContext, pDownloadFinishedListener);
+ // XXX Perhaps we should pass the Intent or the class name (action) into
+ // this constructor since we do the same again in there.
+ // That will also give the option of specifying something else.
+ }
+ }
+
+ public void mapTileRequestCompleted(final OpenStreetMapTile pTile, final String pTilePath) {
+
+ // if the tile path has been returned, add the tile to the cache
+ if (pTilePath != null) {
+ try {
+ final Bitmap bitmap = BitmapFactory.decodeFile(pTilePath);
+ if (bitmap != null) {
+ mTileCache.putTile(pTile, bitmap);
+ } else {
+ // if we couldn't load it then it's invalid - delete it
+ try {
+ new File(pTilePath).delete();
+ } catch (Throwable e) {
+ Log.e(DEBUGTAG, "Error deleting invalid file: " + pTilePath, e);
+ }
+ }
+ } catch (final OutOfMemoryError e) {
+ Log.e(DEBUGTAG, "OutOfMemoryError putting tile in cache: " + pTile);
+ mTileCache.clear();
+ System.gc();
+ }
+ }
+
+ // tell our caller we've finished and it should update its view
+ mDownloadFinishedHandler.sendEmptyMessage(OpenStreetMapTile.MAPTILE_SUCCESS_ID);
+
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "MapTile request complete: " + pTile);
+ }
+
+ public void ensureCapacity(final int aCapacity) {
+ mTileCache.ensureCapacity(aCapacity);
+ }
+
+ public abstract Bitmap getMapTile(OpenStreetMapTile pTile);
+
+ public abstract void detach();
+
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderDirect.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderDirect.java
new file mode 100644
index 0000000..53a7e42
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderDirect.java
@@ -0,0 +1,37 @@
+package org.andnav.osm.views.util;
+
+import org.andnav.osm.tileprovider.IOpenStreetMapTileProviderCallback;
+import org.andnav.osm.tileprovider.OpenStreetMapTile;
+import org.andnav.osm.tileprovider.OpenStreetMapTileFilesystemProvider;
+
+import android.graphics.Bitmap;
+import android.os.Handler;
+import android.util.Log;
+
+public class OpenStreetMapTileProviderDirect extends OpenStreetMapTileProvider implements IOpenStreetMapTileProviderCallback {
+
+ private final OpenStreetMapTileFilesystemProvider mFileSystemProvider;
+
+ public OpenStreetMapTileProviderDirect(final Handler pDownloadFinishedListener) {
+ super(pDownloadFinishedListener);
+ mFileSystemProvider = new OpenStreetMapTileFilesystemProvider(this);
+ }
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public Bitmap getMapTile(final OpenStreetMapTile pTile) {
+ if (mTileCache.containsTile(pTile)) {
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "MapTileCache succeeded for: " + pTile);
+ return mTileCache.getMapTile(pTile);
+ } else {
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "Cache failed, trying from FS: " + pTile);
+ mFileSystemProvider.loadMapTileAsync(pTile);
+ return null;
+ }
+ }
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderService.java b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderService.java
new file mode 100644
index 0000000..9f318e3
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/OpenStreetMapTileProviderService.java
@@ -0,0 +1,143 @@
+package org.andnav.osm.views.util;
+
+import org.andnav.osm.services.IOpenStreetMapTileProviderService;
+import org.andnav.osm.services.IOpenStreetMapTileProviderServiceCallback;
+import org.andnav.osm.tileprovider.OpenStreetMapTile;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.graphics.Bitmap;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.util.Log;
+
+public class OpenStreetMapTileProviderService extends OpenStreetMapTileProvider implements ServiceConnection {
+
+ private final Context mContext;
+
+ private IOpenStreetMapTileProviderService mTileService;
+
+ /**
+ * Service is bound, but maybe not still connected.
+ */
+ private boolean mServiceBound;
+
+ public OpenStreetMapTileProviderService(final Context pContext, final Handler pDownloadFinishedListener) {
+ super(pDownloadFinishedListener);
+ mContext = pContext;
+ bindToService();
+ }
+
+ public void onServiceConnected(final ComponentName name, final IBinder service) {
+ Log.d(DEBUGTAG, "onServiceConnected(" + name + ")");
+
+ mTileService = IOpenStreetMapTileProviderService.Stub.asInterface(service);
+
+ try {
+ mTileService.setCallback(mServiceCallback);
+ } catch (RemoteException e) {
+ Log.e(DEBUGTAG, "Error setting callback", e);
+ }
+
+ try {
+ mDownloadFinishedHandler.sendEmptyMessage(OpenStreetMapTile.MAPTILE_SUCCESS_ID);
+ } catch(Exception e) {
+ Log.e(DEBUGTAG, "Error sending success message on connect", e);
+ }
+ };
+
+ @Override
+ public void onServiceDisconnected(final ComponentName name) {
+ onDisconnect();
+ Log.d(DEBUGTAG, "disconnected");
+ }
+
+ /**
+ * Get the tile from the cache.
+ * If it's in the cache then it will be returned.
+ * If not it will return null and request it from the service.
+ * In turn, the service will request it from the file system.
+ * If it's found in the file system it will notify the callback.
+ * If not it will initiate a download.
+ * When the download has finished it will notify the callback.
+ * @param aTile the tile being requested
+ * @return the tile bitmap if found in the cache, null otherwise
+ */
+ @Override
+ public Bitmap getMapTile(final OpenStreetMapTile aTile) {
+ if (mTileCache.containsTile(aTile)) { // from cache
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "MapTileCache succeeded for: " + aTile);
+ return mTileCache.getMapTile(aTile);
+ } else { // from service
+ if (mTileService != null) {
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "Cache failed, trying from FS: " + aTile);
+ try {
+ mTileService.requestMapTile(aTile.getRendererId(), aTile.getZoomLevel(), aTile.getX(), aTile.getY());
+ } catch (Throwable e) {
+ Log.e(DEBUGTAG, "Error getting map tile from tile service: " + aTile, e);
+ }
+ } else {
+ // try to reconnect, but the connection will take time.
+ if (!bindToService()) {
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "Cache failed, can't get from FS because no tile service: " + aTile);
+ } else {
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "Cache failed, tile service still not woken up: " + aTile);
+ }
+ }
+
+ return null;
+ }
+ }
+
+ /***
+ * Disconnects from the tile downloader service.
+ */
+ @Override
+ public void detach()
+ {
+ if (mServiceBound)
+ {
+ if (DEBUGMODE)
+ Log.d(DEBUGTAG, "Unbinding service");
+ mContext.unbindService(this);
+ onDisconnect();
+ }
+ }
+
+ private boolean bindToService()
+ {
+ if (mServiceBound)
+ return true;
+
+ boolean success = mContext.bindService(new Intent(IOpenStreetMapTileProviderService.class.getName()), this, Context.BIND_AUTO_CREATE);
+
+ if (!success)
+ Log.e(DEBUGTAG, "Could not bind to " + IOpenStreetMapTileProviderService.class.getName());
+
+ mServiceBound = success;
+
+ return success;
+ }
+
+ private void onDisconnect()
+ {
+ mServiceBound = false;
+ mTileService = null;
+ }
+
+ IOpenStreetMapTileProviderServiceCallback mServiceCallback = new IOpenStreetMapTileProviderServiceCallback.Stub() {
+ @Override
+ public void mapTileRequestCompleted(final int aRendererID, final int aZoomLevel, final int aTileX, final int aTileY, final String aTilePath) throws RemoteException {
+ final OpenStreetMapTile tile = new OpenStreetMapTile(aRendererID, aZoomLevel, aTileX, aTileY);
+ OpenStreetMapTileProviderService.this.mapTileRequestCompleted(tile, aTilePath);
+ }
+ };
+
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/constants/MathConstants.java b/cardroid/src/org/andnav/osm/views/util/constants/MathConstants.java
new file mode 100644
index 0000000..8e235d5
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/constants/MathConstants.java
@@ -0,0 +1,24 @@
+// Created by plusminus on 17:27:54 - 30.09.2008
+package org.andnav.osm.views.util.constants;
+
+/**
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public interface MathConstants {
+ // ===========================================================
+ // Final Fields
+ // ===========================================================
+
+ public static final float DEG2RAD = (float)(Math.PI / 180.0);
+ public static final float RAD2DEG = (float)(180.0 / Math.PI);
+
+ public static final float PI = (float)Math.PI;
+ public static final float PI_2 = PI / 2.0f;
+ public static final float PI_4 = PI / 4.0f;
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+}
diff --git a/cardroid/src/org/andnav/osm/views/util/constants/OpenStreetMapViewConstants.java b/cardroid/src/org/andnav/osm/views/util/constants/OpenStreetMapViewConstants.java
new file mode 100644
index 0000000..ce3aeea
--- /dev/null
+++ b/cardroid/src/org/andnav/osm/views/util/constants/OpenStreetMapViewConstants.java
@@ -0,0 +1,30 @@
+// Created by plusminus on 18:00:24 - 25.09.2008
+package org.andnav.osm.views.util.constants;
+
+/**
+ *
+ * This class contains constants used by the map view.
+ *
+ * @author Nicolas Gramlich
+ *
+ */
+public interface OpenStreetMapViewConstants {
+ // ===========================================================
+ // Final Fields
+ // ===========================================================
+
+ public static final boolean DEBUGMODE = false;
+
+ public static final String DEBUGTAG = "OPENSTREETMAP_VIEW";
+
+ public static final int NOT_SET = Integer.MIN_VALUE;
+
+ public static final int CACHE_MAPTILECOUNT_DEFAULT = 40;
+
+ public static final int MAPTILE_LATITUDE_INDEX = 0;
+ public static final int MAPTILE_LONGITUDE_INDEX = 1;
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+}
|
cstim/carcomm
|
9a41e81fe0b2f8ae916ab18f3072d7f6be9d87c0
|
Initial android app.
|
diff --git a/cardroid/.gitignore b/cardroid/.gitignore
new file mode 100644
index 0000000..07eee84
--- /dev/null
+++ b/cardroid/.gitignore
@@ -0,0 +1,3 @@
+bin
+build.xml
+local.properties
\ No newline at end of file
diff --git a/cardroid/AndroidManifest.xml b/cardroid/AndroidManifest.xml
new file mode 100644
index 0000000..314b76e
--- /dev/null
+++ b/cardroid/AndroidManifest.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="de.cstimming.carinfo"
+ android:versionCode="1"
+ android:versionName="1.0">
+ <application android:label="@string/app_name">
+ <activity android:name=".CarinfoActivity"
+ android:label="@string/app_name">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+</manifest>
diff --git a/cardroid/build.properties b/cardroid/build.properties
new file mode 100644
index 0000000..35bb90e
--- /dev/null
+++ b/cardroid/build.properties
@@ -0,0 +1,20 @@
+# This file is used to override default values used by the Ant build system.
+#
+# This file must be checked in Version Control Systems, as it is
+# integral to the build system of your project.
+
+# This file is only used by the Ant script.
+
+# You can use this to override default values such as
+# 'source.dir' for the location of your java source folder and
+# 'out.dir' for the location of your output folder.
+
+# You can also use it define how the release builds are signed by declaring
+# the following properties:
+# 'key.store' for the location of your keystore and
+# 'key.alias' for the name of the key to use.
+# The password will be asked during the build when you use the 'release' target.
+
+# The name of your application package as defined in the manifest.
+# Used by the 'uninstall' rule.
+application.package=de.cstimming.carinfo
diff --git a/cardroid/cmdline.txt b/cardroid/cmdline.txt
new file mode 100644
index 0000000..7c6447e
--- /dev/null
+++ b/cardroid/cmdline.txt
@@ -0,0 +1,34 @@
+## To have SUN java in path:
+#export PATH=/usr/lib/jvm/java-6-sun-1.6.0.15/jre/bin:$PATH
+
+# Creating the project:
+ANDROIDROOT=$HOME/android-sdk-linux_86
+cd $ANDROIDROOT/tools
+./android list targets
+./android create project \
+ --target android-3 \
+ --name carinfo \
+ --path /home/chs/carinfo \
+ --activity CarinfoActivity \
+ --package de.cstimming.carinfo
+
+PROJDIR=$HOME/carinfo
+cd $PROJDIR
+
+# Building in debug mode
+ant debug
+
+# Starting an emulator
+cd $ANDROIDROOT/tools
+./android list avds
+# I have one Android Virtual Device (AVD) named "test1"; start this
+# AVD:
+./emulator -avd test1
+
+# Install the application on the currently running emulator
+./adb install $PROJDIR/bin/carinfo-debug.apk
+
+# Building my application and installing it to the currently running
+# emulator in one step
+cd $PROJDIR
+ant install
diff --git a/cardroid/default.properties b/cardroid/default.properties
new file mode 100644
index 0000000..4513a1e
--- /dev/null
+++ b/cardroid/default.properties
@@ -0,0 +1,11 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system use,
+# "build.properties", and override values to adapt the script to your
+# project structure.
+
+# Project target.
+target=android-3
diff --git a/cardroid/gen/de/cstimming/carinfo/R.java b/cardroid/gen/de/cstimming/carinfo/R.java
new file mode 100644
index 0000000..326ae46
--- /dev/null
+++ b/cardroid/gen/de/cstimming/carinfo/R.java
@@ -0,0 +1,20 @@
+/* AUTO-GENERATED FILE. DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found. It
+ * should not be modified by hand.
+ */
+
+package de.cstimming.carinfo;
+
+public final class R {
+ public static final class attr {
+ }
+ public static final class layout {
+ public static final int main=0x7f020000;
+ }
+ public static final class string {
+ public static final int app_name=0x7f030000;
+ public static final int hello=0x7f030001;
+ }
+}
diff --git a/cardroid/res/layout/main.xml b/cardroid/res/layout/main.xml
new file mode 100644
index 0000000..5f4c383
--- /dev/null
+++ b/cardroid/res/layout/main.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="vertical"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ >
+<TextView
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:text="@string/hello"
+ />
+</LinearLayout>
+
diff --git a/cardroid/res/values-de/strings.xml b/cardroid/res/values-de/strings.xml
new file mode 100644
index 0000000..7ae9de7
--- /dev/null
+++ b/cardroid/res/values-de/strings.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Meine CarinfoActivity</string>
+<string name="hello">Hallo Welt, CarinfoActivity</string>
+</resources>
diff --git a/cardroid/res/values/strings.xml b/cardroid/res/values/strings.xml
new file mode 100644
index 0000000..2d0d21c
--- /dev/null
+++ b/cardroid/res/values/strings.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">My CarinfoActivity</string>
+<string name="hello">Hello World, CarinfoActivity</string>
+</resources>
diff --git a/cardroid/src/de/cstimming/carinfo/CarinfoActivity.java b/cardroid/src/de/cstimming/carinfo/CarinfoActivity.java
new file mode 100644
index 0000000..f256a90
--- /dev/null
+++ b/cardroid/src/de/cstimming/carinfo/CarinfoActivity.java
@@ -0,0 +1,15 @@
+package de.cstimming.carinfo;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+public class CarinfoActivity extends Activity
+{
+ /** Called when the activity is first created. */
+ @Override
+ public void onCreate(Bundle savedInstanceState)
+ {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.main);
+ }
+}
|
cstim/carcomm
|
8528f857c7a70960e9e806d00263391a2c846491
|
Sanity check to avoid outdated GPS points.
|
diff --git a/webapp/public/map.html b/webapp/public/map.html
index f66112c..2d62680 100644
--- a/webapp/public/map.html
+++ b/webapp/public/map.html
@@ -1,438 +1,430 @@
<html>
<head>
<meta name="viewport" content="width = device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
<title>Car Communication App</title>
<script src="http://code.google.com/apis/gears/gears_init.js"></script>
<!-- bring in the OpenLayers javascript library
(here we bring it from the remote site, but you could
easily serve up this javascript yourself) -->
<script src="OpenLayers.js"></script>
<!--script src="http://www.openlayers.org/api/OpenLayers.js"></script-->
<!-- bring in the OpenStreetMap OpenLayers layers.
Using this hosted file will make sure we are kept up
to date with any necessary changes -->
<script src="OpenStreetMap.js"></script>
<!--script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script-->
<!-- The geo-location-javascript code -->
<script src="geo.js"></script>
<!-- The personal functions from CS -->
<script src="csfuncs.js"></script>
<!-- ------------------------------------------------------ -->
<script type="text/javascript">
function setStatus(id, text, bgcolor) {
var td = document.getElementById(id);
var div = document.getElementById(id + "Text");
if (td && div) {
if (text) {
div.firstChild.nodeValue = text;
}
if (bgcolor) {
td.setAttribute("bgcolor", bgcolor);
}
} else {
window.onerror ("Function setStatus() was called with non-existing ID of html element, \"" + id + "\"");
}
}
function csErrorHandler (msg, file, line) {
var fullMsg = "General Error: " + msg + " in file: " + file + ":" + line;
setStatus("GPSStatus", "General", "red");
var span2 = document.getElementById("GeneralError");
if (span2) {
span2.firstChild.nodeValue = fullMsg;
}
return true;
}
OpenLayers.Util.onImageLoadError = function() {
setStatus("MapStatus", "Map: Cannot load images", "red");
};
// Complex object of type OpenLayers.Map
var map;
var layerGpx1;
var layerGpx2;
var useLayerGpx1;
var gpxStyleMap;
var serverUrl;
var initialized;
var lastPos;
var currentPos;
var sendInterval;
// Global error handler
window.onerror = csErrorHandler;
function setLatLon(lat, lon) {
var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
var currentZoom = map.getZoom();
map.setCenter (lonLat, currentZoom);
}
function zoomTo(lat, lon, zoom) {
var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.setCenter (lonLat, zoom);
}
function zoomToHamburg() {
// Start position for the map (hardcoded here for simplicity)
zoomTo(53.5514, 9.99, 12);
}
function on_gpx_loadstart() {
var numWays = this.features.length;
setStatus("SliceStatus", "Loading... " + numWays, "lightyellow");
}
function on_gpx_loadend() {
var numWays = this.features.length;
if (numWays > 0) {
setStatus("SliceStatus", "Ways ok: " + numWays + " lines", "lightgreen");
} else {
setStatus("SliceStatus", "No Ways received", "yellow");
}
if (useLayerGpx1) {
if (layerGpx1) {
layerGpx1.destroy();
}
} else {
if (layerGpx2) {
layerGpx2.destroy();
}
}
}
function loadWaysLayer(min_time, max_time) {
var lonLatUR = map.getLonLatFromPixel(new OpenLayers.Pixel(0,0))
.transform(map.getProjectionObject(),
new OpenLayers.Projection("EPSG:4326"));
var mapSize = map.getSize();
var lonLatLL = map.getLonLatFromPixel(new OpenLayers.Pixel(mapSize.w, mapSize.h))
.transform(map.getProjectionObject(),
new OpenLayers.Projection("EPSG:4326"));
var min_lat = lonLatLL.lat;
var max_lon = lonLatLL.lon;
var max_lat = lonLatUR.lat;
var min_lon = lonLatUR.lon;
// Add the Layer with GPX Track
var layerGpx = csCreateLayerGpx(serverUrl,
min_lat, max_lat,
min_lon, max_lon,
min_time, max_time);
layerGpx.events.register("loadend", layerGpx, on_gpx_loadend);
layerGpx.events.register("loadstart", layerGpx, on_gpx_loadstart);
return layerGpx;
}
function loadWays(min_time, max_time) {
if (useLayerGpx1) {
useLayerGpx1 = false;
if (layerGpx1) {
layerGpx1.destroy();
}
layerGpx1 = loadWaysLayer(min_time, max_time);
map.addLayer(layerGpx1);
} else {
useLayerGpx1 = true;
if (layerGpx2) {
layerGpx2.destroy();
}
layerGpx2 = loadWaysLayer(min_time, max_time);
map.addLayer(layerGpx2);
}
}
function loadWaysDefault() {
if (!document.forms.checkboxes.elements.SliceCheck.checked) {
setStatus("SliceStatus", "Ways disabled", "yellow");
return;
}
var num_minutes = 20220; // 2 weeks + 1 hour
var max_time = new Date();
var min_time = new Date(max_time.getDate() - num_minutes * 60 * 1000);
loadWays(dateToString(min_time), dateToString(max_time));
}
function sendDataNow() {
if (!document.forms.checkboxes.elements.SendCheck.checked) {
setStatus("SendStatus", "Sending disabled", "yellow");
return;
}
if (!currentPos) {
setStatus("SendStatus", "No Valid Positions to send", "red");
return;
}
if (!lastPos) {
lastPos = currentPos;
}
setStatus("SendStatus", "Sending...", "lightgreen");
var endTimestamp = currentPos.timestamp;
var diffsec = (endTimestamp - lastPos.timestamp) / 1000;
if (diffsec == 0) {
endTimestamp = (new Date()).getTime();
diffsec = (endTimestamp - lastPos.timestamp) / 1000;
}
var endLat = currentPos.coords.latitude.toFixed(6);
var endLon = currentPos.coords.longitude.toFixed(6);
var startLat = lastPos.coords.latitude.toFixed(6);
var startLon = lastPos.coords.longitude.toFixed(6);
var time = dateToString(new Date(endTimestamp));
if (diffsec == 0) {
setStatus("SendStatus", "Oops, diffsec = 0", "red");
alert("currentPos.timestamp=" + currentPos.timestamp + " lastPos.timestamp=" + lastPos.timestamp + " date=" + (new Date()).getTime());
return;
}
var dur = diffsec.toFixed(2);
var url = serverUrl + "slices";
var params = "slice[lat]=" + endLat
+ "&slice[lon]=" + endLon
+ "&slice[time]=" + time
+ "&slice[duration]=" + dur
+ "&slice[startlat]=" + startLat
+ "&slice[startlon]=" + startLon;
var http = new XMLHttpRequest();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() { //Call a function when the state changes.
if (http.readyState) {
if (http.status >= 200 && http.status <= 210) {
setStatus("SendStatus", "Sent", "lightgreen");
//alert(http.responseText);
} else {
setStatus("SendStatus", "Position not sent (" + http.status + ")", "yellow");
//alert(http.responseText);
}
}
};
http.send(params);
//alert("Will send: " + url + "?" + params);
lastPos = currentPos;
}
function sendDataMaybe() {
if (currentPos) {
if (!lastPos) {
lastPos = currentPos;
}
var diffmsec = currentPos.timestamp - lastPos.timestamp;
var diffsec = diffmsec / 1000;
- if (diffsec >= sendInterval) {
+ if (diffsec >= 2 * sendInterval) {
+ // The position difference is too large, forget about the
+ // old one
+ lastPos = currentPos;
+ } else if (diffsec >= sendInterval) {
sendDataNow();
}
}
}
function on_geo_error(p) {
setStatus("GPSStatus", "GPS Error", "red");
}
function on_geo_success(p) {
setStatus("GPSStatus", "GPS ok", "lightgreen");
setLatLon(p.coords.latitude, p.coords.longitude);
currentPos = p;
sendDataMaybe();
loadWaysDefault();
}
function requestPos() {
if (!document.forms.checkboxes.elements.GPSCheck.checked) {
setStatus("GPSStatus", "GPS disabled", "yellow");
} else {
setStatus("GPSStatus", "Request GPS...", "lightgreen");
geo_position_js.getCurrentPosition(on_geo_success, on_geo_error,
{enableHighAccuracy : true,
timeout : 15000,
maximumAge : 30000});
//{enableHighAccuracy : true});
// timeout : 1000, // milliseconds
// maximumAge : 10000 // milliseconds
// });
//setStatus("MapStatus", "Map: 3b", "yellow");
}
}
function on_interval() {
if (!document.forms.checkboxes.elements.GPSCheck.checked) {
//setStatus("GPSStatus", "GPS disabled", "yellow");
return;
}
if (currentPos) {
var now = new Date();
var diffmsec = now.getTime() - currentPos.timestamp;
var diffsec = diffmsec / 1000;
var diffstr = diffsec.toFixed(1);
setStatus("GPSStatus",
"GPS ok", //; " + diffstr + "s old",
"lightgreen");
- if (diffsec > 7) {
- requestPos();
- }
if (diffsec >= sendInterval) {
- // Uh, we need to create a new object here
+ // The currentPos is rather old - we assume it were still
+ // valid right now and fake a new object. FIXME: Maybe
+ // this isn't such a good idea?
currentPos = { timestamp: now.getTime(),
coords : {
latitude : currentPos.coords.latitude,
longitude : currentPos.coords.longitude
}};
sendDataMaybe();
+ } else if (diffsec > 7) {
+ requestPos();
}
} else {
setStatus("SendStatus",
"Waiting for GPS",
"yellow");
requestPos();
}
}
//Initialise the 'map' object
function init() {
sendInterval = 60;
serverUrl = "";
useLayerGpx1 = true;
// Did we get our auxiliary files? Then switch General to green
if (OpenLayers && csCreateMap) {
//setStatus("GeneralStatus", null, "lightgreen");
}
if (typeof(window.google) != "undefined" && typeof(window.google.gears) != "undefined"){
setStatus("GPSStatus", "GPS: Google Gears", "lightyellow");
} else if (typeof(navigator.geolocation) != "undefined") {
setStatus("GPSStatus", "GPS: Mozilla Navigator available", "lightyellow");
} else {
setStatus("GPSStatus", "GPS: Please install Google Gears, http://gears.google.com", "yellow");
}
//setStatus("MapStatus", "Map: 1", "yellow");
// Define the map layer
map = csCreateMap();
//setStatus("MapStatus", "Map: 2", "yellow");
// Define the styles for the way slices
gpxStyleMap = csCreateGpxStyleMap();
- //setStatus("MapStatus", "Map: 3", "yellow");
-
- //determine if the handset has client side geo location capabilities
- if (geo_position_js.init()) {
- //setStatus("MapStatus", "Map: 3a", "yellow");
- requestPos();
- //setStatus("MapStatus", "Map: 3b", "yellow");
- }
- else{
- //setStatus("MapStatus", "Map: 3c", "yellow");
- on_geo_error({message: "No GPS available"});
- }
-
- //setStatus("MapStatus", "Map: 4", "yellow");
// Choose Hamburg as center
zoomToHamburg();
initialized = 1;
loadWaysDefault();
setInterval(on_interval, 2500); // milliseconds
+ //determine if the handset has client side geo location capabilities
if (geo_position_js.init()) {
requestPos();
} else {
on_geo_error({message: "No GPS available"});
}
}
function setServerUrl(value) {
serverUrl = value;
}
function on_osm_loadstart() {
setStatus("MapStatus", "Loading...", "yellow");
setStatus("SendStatus", "", "lightyellow");
}
function on_osm_tileloaded() {
var numRemainingTiles = this.numLoadingTiles;
if (numRemainingTiles > 0) {
setStatus("MapStatus", "Loading; " + this.numLoadingTiles + " images remaining", "lightgreen");
}
else {
setStatus("MapStatus", "Loaded", "lightgreen");
}
}
function toggleCheckBox(cbox) {
if (cbox) {
cbox.checked = !cbox.checked;
}
}
</script>
<!-- ------------------------------------------------------ -->
</head>
<!-- body.onload is called once the page is loaded (call the 'init' function) -->
<body onload="init();">
<form name="checkboxes" action="">
<table border="1" width="100%"><tr>
<td align="center" id="GPSStatus" bgcolor="lightyellow" onclick="toggleCheckBox(document.forms.checkboxes.elements.GPSCheck);">
- <input type="checkbox" name="GPSCheck" value="1" checked="checked" onchange="requestPos();">
+ <input type="checkbox" name="GPSCheck" value="1" checked="checked"/>
<span id="GPSStatusText">GPS</span>
</td>
<td align="center" id="MapStatus" bgcolor="yellow">
<span id="MapStatusText">Map</span>
</td>
<td align="center" id="SliceStatus" bgcolor="lightyellow" onclick="toggleCheckBox(document.forms.checkboxes.elements.SliceCheck);">
- <input type="checkbox" name="SliceCheck" value="1" checked="checked" onchange="loadWaysDefault();">
+ <input type="checkbox" name="SliceCheck" value="1" checked="checked">
<span id="SliceStatusText">Ways</span>
</td>
<td align="center" id="SendStatus" onclick="toggleCheckBox(document.forms.checkboxes.elements.SendCheck);">
- <input type="checkbox" name="SendCheck" value="1" checked="checked" onchange="sendDataNow();">
+ <input type="checkbox" name="SendCheck" value="1" checked="checked">
<span id="SendStatusText">Sending</span>
</td>
</tr>
</table>
</form>
<!-- define a DIV into which the map will appear. Make it take up 400 pixels -->
<div id="map"></div>
<span name="GeneralError"></span>
</body>
</html>
<!-- Local Variables: -->
<!-- mode: javascript -->
<!-- indent-tabs-mode:nil -->
<!-- c-basic-offset:4 -->
<!-- tab-width:8 -->
<!-- End: -->
|
cstim/carcomm
|
989b14156e7f050b6fb4f6f668e646c2aa03d010
|
Decrease GPS error verbosity. Make the full td fields clickable.
|
diff --git a/webapp/public/map.html b/webapp/public/map.html
index 314d185..f66112c 100644
--- a/webapp/public/map.html
+++ b/webapp/public/map.html
@@ -1,432 +1,438 @@
<html>
<head>
<meta name="viewport" content="width = device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
<title>Car Communication App</title>
<script src="http://code.google.com/apis/gears/gears_init.js"></script>
<!-- bring in the OpenLayers javascript library
(here we bring it from the remote site, but you could
easily serve up this javascript yourself) -->
<script src="OpenLayers.js"></script>
<!--script src="http://www.openlayers.org/api/OpenLayers.js"></script-->
<!-- bring in the OpenStreetMap OpenLayers layers.
Using this hosted file will make sure we are kept up
to date with any necessary changes -->
<script src="OpenStreetMap.js"></script>
<!--script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script-->
<!-- The geo-location-javascript code -->
<script src="geo.js"></script>
<!-- The personal functions from CS -->
<script src="csfuncs.js"></script>
<!-- ------------------------------------------------------ -->
<script type="text/javascript">
function setStatus(id, text, bgcolor) {
var td = document.getElementById(id);
var div = document.getElementById(id + "Text");
if (td && div) {
if (text) {
div.firstChild.nodeValue = text;
}
if (bgcolor) {
td.setAttribute("bgcolor", bgcolor);
}
} else {
window.onerror ("Function setStatus() was called with non-existing ID of html element, \"" + id + "\"");
}
}
function csErrorHandler (msg, file, line) {
var fullMsg = "General Error: " + msg + " in file: " + file + ":" + line;
- setStatus("GPSStatus", "General: " + fullMsg, "red");
+ setStatus("GPSStatus", "General", "red");
var span2 = document.getElementById("GeneralError");
if (span2) {
span2.firstChild.nodeValue = fullMsg;
}
return true;
}
OpenLayers.Util.onImageLoadError = function() {
setStatus("MapStatus", "Map: Cannot load images", "red");
};
// Complex object of type OpenLayers.Map
var map;
var layerGpx1;
var layerGpx2;
var useLayerGpx1;
var gpxStyleMap;
var serverUrl;
var initialized;
var lastPos;
var currentPos;
var sendInterval;
// Global error handler
window.onerror = csErrorHandler;
function setLatLon(lat, lon) {
var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
var currentZoom = map.getZoom();
map.setCenter (lonLat, currentZoom);
}
function zoomTo(lat, lon, zoom) {
var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.setCenter (lonLat, zoom);
}
function zoomToHamburg() {
// Start position for the map (hardcoded here for simplicity)
zoomTo(53.5514, 9.99, 12);
}
function on_gpx_loadstart() {
var numWays = this.features.length;
setStatus("SliceStatus", "Loading... " + numWays, "lightyellow");
}
function on_gpx_loadend() {
var numWays = this.features.length;
if (numWays > 0) {
setStatus("SliceStatus", "Ways ok: " + numWays + " lines", "lightgreen");
} else {
setStatus("SliceStatus", "No Ways received", "yellow");
}
if (useLayerGpx1) {
if (layerGpx1) {
layerGpx1.destroy();
}
} else {
if (layerGpx2) {
layerGpx2.destroy();
}
}
}
function loadWaysLayer(min_time, max_time) {
var lonLatUR = map.getLonLatFromPixel(new OpenLayers.Pixel(0,0))
.transform(map.getProjectionObject(),
new OpenLayers.Projection("EPSG:4326"));
var mapSize = map.getSize();
var lonLatLL = map.getLonLatFromPixel(new OpenLayers.Pixel(mapSize.w, mapSize.h))
.transform(map.getProjectionObject(),
new OpenLayers.Projection("EPSG:4326"));
var min_lat = lonLatLL.lat;
var max_lon = lonLatLL.lon;
var max_lat = lonLatUR.lat;
var min_lon = lonLatUR.lon;
// Add the Layer with GPX Track
var layerGpx = csCreateLayerGpx(serverUrl,
min_lat, max_lat,
min_lon, max_lon,
min_time, max_time);
layerGpx.events.register("loadend", layerGpx, on_gpx_loadend);
layerGpx.events.register("loadstart", layerGpx, on_gpx_loadstart);
return layerGpx;
}
function loadWays(min_time, max_time) {
if (useLayerGpx1) {
useLayerGpx1 = false;
if (layerGpx1) {
layerGpx1.destroy();
}
layerGpx1 = loadWaysLayer(min_time, max_time);
map.addLayer(layerGpx1);
} else {
useLayerGpx1 = true;
if (layerGpx2) {
layerGpx2.destroy();
}
layerGpx2 = loadWaysLayer(min_time, max_time);
map.addLayer(layerGpx2);
}
}
function loadWaysDefault() {
if (!document.forms.checkboxes.elements.SliceCheck.checked) {
setStatus("SliceStatus", "Ways disabled", "yellow");
return;
}
var num_minutes = 20220; // 2 weeks + 1 hour
var max_time = new Date();
var min_time = new Date(max_time.getDate() - num_minutes * 60 * 1000);
loadWays(dateToString(min_time), dateToString(max_time));
}
function sendDataNow() {
if (!document.forms.checkboxes.elements.SendCheck.checked) {
setStatus("SendStatus", "Sending disabled", "yellow");
return;
}
if (!currentPos) {
setStatus("SendStatus", "No Valid Positions to send", "red");
return;
}
if (!lastPos) {
lastPos = currentPos;
}
setStatus("SendStatus", "Sending...", "lightgreen");
var endTimestamp = currentPos.timestamp;
var diffsec = (endTimestamp - lastPos.timestamp) / 1000;
if (diffsec == 0) {
endTimestamp = (new Date()).getTime();
diffsec = (endTimestamp - lastPos.timestamp) / 1000;
}
var endLat = currentPos.coords.latitude.toFixed(6);
var endLon = currentPos.coords.longitude.toFixed(6);
var startLat = lastPos.coords.latitude.toFixed(6);
var startLon = lastPos.coords.longitude.toFixed(6);
var time = dateToString(new Date(endTimestamp));
if (diffsec == 0) {
setStatus("SendStatus", "Oops, diffsec = 0", "red");
alert("currentPos.timestamp=" + currentPos.timestamp + " lastPos.timestamp=" + lastPos.timestamp + " date=" + (new Date()).getTime());
return;
}
var dur = diffsec.toFixed(2);
var url = serverUrl + "slices";
var params = "slice[lat]=" + endLat
+ "&slice[lon]=" + endLon
+ "&slice[time]=" + time
+ "&slice[duration]=" + dur
+ "&slice[startlat]=" + startLat
+ "&slice[startlon]=" + startLon;
var http = new XMLHttpRequest();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() { //Call a function when the state changes.
if (http.readyState) {
if (http.status >= 200 && http.status <= 210) {
setStatus("SendStatus", "Sent", "lightgreen");
//alert(http.responseText);
} else {
setStatus("SendStatus", "Position not sent (" + http.status + ")", "yellow");
//alert(http.responseText);
}
}
};
http.send(params);
//alert("Will send: " + url + "?" + params);
lastPos = currentPos;
}
function sendDataMaybe() {
if (currentPos) {
if (!lastPos) {
lastPos = currentPos;
}
var diffmsec = currentPos.timestamp - lastPos.timestamp;
var diffsec = diffmsec / 1000;
if (diffsec >= sendInterval) {
sendDataNow();
}
}
}
function on_geo_error(p) {
- setStatus("GPSStatus", "GPS Error: " + p.message, "red");
+ setStatus("GPSStatus", "GPS Error", "red");
}
function on_geo_success(p) {
setStatus("GPSStatus", "GPS ok", "lightgreen");
setLatLon(p.coords.latitude, p.coords.longitude);
currentPos = p;
sendDataMaybe();
loadWaysDefault();
}
function requestPos() {
if (!document.forms.checkboxes.elements.GPSCheck.checked) {
setStatus("GPSStatus", "GPS disabled", "yellow");
} else {
setStatus("GPSStatus", "Request GPS...", "lightgreen");
geo_position_js.getCurrentPosition(on_geo_success, on_geo_error,
{enableHighAccuracy : true,
timeout : 15000,
maximumAge : 30000});
//{enableHighAccuracy : true});
// timeout : 1000, // milliseconds
// maximumAge : 10000 // milliseconds
// });
//setStatus("MapStatus", "Map: 3b", "yellow");
}
}
function on_interval() {
if (!document.forms.checkboxes.elements.GPSCheck.checked) {
//setStatus("GPSStatus", "GPS disabled", "yellow");
return;
}
if (currentPos) {
var now = new Date();
var diffmsec = now.getTime() - currentPos.timestamp;
var diffsec = diffmsec / 1000;
var diffstr = diffsec.toFixed(1);
setStatus("GPSStatus",
- "GPS ok; " + diffstr + "s old",
+ "GPS ok", //; " + diffstr + "s old",
"lightgreen");
if (diffsec > 7) {
requestPos();
}
if (diffsec >= sendInterval) {
// Uh, we need to create a new object here
currentPos = { timestamp: now.getTime(),
coords : {
latitude : currentPos.coords.latitude,
longitude : currentPos.coords.longitude
}};
sendDataMaybe();
}
} else {
setStatus("SendStatus",
"Waiting for GPS",
"yellow");
requestPos();
}
}
//Initialise the 'map' object
function init() {
sendInterval = 60;
serverUrl = "";
useLayerGpx1 = true;
// Did we get our auxiliary files? Then switch General to green
if (OpenLayers && csCreateMap) {
//setStatus("GeneralStatus", null, "lightgreen");
}
if (typeof(window.google) != "undefined" && typeof(window.google.gears) != "undefined"){
setStatus("GPSStatus", "GPS: Google Gears", "lightyellow");
} else if (typeof(navigator.geolocation) != "undefined") {
setStatus("GPSStatus", "GPS: Mozilla Navigator available", "lightyellow");
} else {
setStatus("GPSStatus", "GPS: Please install Google Gears, http://gears.google.com", "yellow");
}
//setStatus("MapStatus", "Map: 1", "yellow");
// Define the map layer
map = csCreateMap();
//setStatus("MapStatus", "Map: 2", "yellow");
// Define the styles for the way slices
gpxStyleMap = csCreateGpxStyleMap();
//setStatus("MapStatus", "Map: 3", "yellow");
//determine if the handset has client side geo location capabilities
if (geo_position_js.init()) {
//setStatus("MapStatus", "Map: 3a", "yellow");
requestPos();
//setStatus("MapStatus", "Map: 3b", "yellow");
}
else{
//setStatus("MapStatus", "Map: 3c", "yellow");
on_geo_error({message: "No GPS available"});
}
//setStatus("MapStatus", "Map: 4", "yellow");
// Choose Hamburg as center
zoomToHamburg();
initialized = 1;
loadWaysDefault();
setInterval(on_interval, 2500); // milliseconds
if (geo_position_js.init()) {
requestPos();
} else {
on_geo_error({message: "No GPS available"});
}
}
function setServerUrl(value) {
serverUrl = value;
}
function on_osm_loadstart() {
setStatus("MapStatus", "Loading...", "yellow");
setStatus("SendStatus", "", "lightyellow");
}
function on_osm_tileloaded() {
var numRemainingTiles = this.numLoadingTiles;
if (numRemainingTiles > 0) {
setStatus("MapStatus", "Loading; " + this.numLoadingTiles + " images remaining", "lightgreen");
}
else {
setStatus("MapStatus", "Loaded", "lightgreen");
}
}
+function toggleCheckBox(cbox) {
+ if (cbox) {
+ cbox.checked = !cbox.checked;
+ }
+}
+
</script>
<!-- ------------------------------------------------------ -->
</head>
<!-- body.onload is called once the page is loaded (call the 'init' function) -->
<body onload="init();">
<form name="checkboxes" action="">
<table border="1" width="100%"><tr>
- <td align="center" id="GPSStatus" bgcolor="lightyellow">
+ <td align="center" id="GPSStatus" bgcolor="lightyellow" onclick="toggleCheckBox(document.forms.checkboxes.elements.GPSCheck);">
<input type="checkbox" name="GPSCheck" value="1" checked="checked" onchange="requestPos();">
- <span id="GPSStatusText" onclick="requestPos();">GPS</span>
+ <span id="GPSStatusText">GPS</span>
</td>
<td align="center" id="MapStatus" bgcolor="yellow">
<span id="MapStatusText">Map</span>
</td>
- <td align="center" id="SliceStatus" bgcolor="lightyellow">
+ <td align="center" id="SliceStatus" bgcolor="lightyellow" onclick="toggleCheckBox(document.forms.checkboxes.elements.SliceCheck);">
<input type="checkbox" name="SliceCheck" value="1" checked="checked" onchange="loadWaysDefault();">
- <span id="SliceStatusText" onclick="loadWaysDefault();">Ways</span>
+ <span id="SliceStatusText">Ways</span>
</td>
- <td align="center" id="SendStatus">
+ <td align="center" id="SendStatus" onclick="toggleCheckBox(document.forms.checkboxes.elements.SendCheck);">
<input type="checkbox" name="SendCheck" value="1" checked="checked" onchange="sendDataNow();">
- <span id="SendStatusText" onclick="sendDataNow();">Sending</span>
+ <span id="SendStatusText">Sending</span>
</td>
</tr>
</table>
</form>
<!-- define a DIV into which the map will appear. Make it take up 400 pixels -->
<div id="map"></div>
<span name="GeneralError"></span>
</body>
</html>
<!-- Local Variables: -->
<!-- mode: javascript -->
<!-- indent-tabs-mode:nil -->
<!-- c-basic-offset:4 -->
<!-- tab-width:8 -->
<!-- End: -->
|
cstim/carcomm
|
102e8b414a2b9faf61656490502995704b9e489c
|
Code cleanup according to jslint.com
|
diff --git a/webapp/public/csfuncs.js b/webapp/public/csfuncs.js
index 1d2ca16..28cc902 100644
--- a/webapp/public/csfuncs.js
+++ b/webapp/public/csfuncs.js
@@ -1,147 +1,149 @@
function csCreateMap() {
var map = new OpenLayers.Map ("map", {
controls:
[
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.Attribution()
],
maxExtent:
new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
maxResolution:
156543.0399,
numZoomLevels:
19,
units:
'm',
projection:
new OpenLayers.Projection("EPSG:900913"),
displayProjection:
new OpenLayers.Projection("EPSG:4326")
}
);
// Define the map layer
// Other defined layers are OpenLayers.Layer.OSM.Mapnik, OpenLayers.Layer.OSM.Maplint and OpenLayers.Layer.OSM.CycleMap
var layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
//layerMapnik.attribution = "";
- if (typeof(on_osm_tileloaded) != "undefined")
+ if (typeof(on_osm_tileloaded) != "undefined") {
layerMapnik.events.register("tileloaded", layerMapnik, on_osm_tileloaded);
- if (typeof(on_osm_loadstart) != "undefined")
+ }
+ if (typeof(on_osm_loadstart) != "undefined") {
layerMapnik.events.register("loadstart", layerMapnik, on_osm_loadstart);
+ }
map.addLayer(layerMapnik);
return map;
}
function csCreateGpxStyleMap() {
// Create the style for the GPX traces
var gpxStyle = new OpenLayers.Style(
{ //strokeColor: "green",
strokeOpacity: 0.5,
strokeWidth: 10 //'${avgvel}'
});
var ruleStopping = new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LESS_THAN,
property: "avgvel",
value: 18 / 3.6
}),
symbolizer: { strokeColor: "red" }
});
var ruleCitySlow = new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.BETWEEN,
property: "avgvel",
lowerBoundary: 18 / 3.6,
upperBoundary: 40 / 3.6
}),
symbolizer: { strokeColor: "yellow" }
});
var ruleCityFast = new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.BETWEEN,
property: "avgvel",
lowerBoundary: 40 / 3.6,
upperBoundary: 65 / 3.6
}),
symbolizer: { strokeColor: "green" }
});
var ruleHighwaySlow = new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.BETWEEN,
property: "avgvel",
lowerBoundary: 65 / 3.6,
upperBoundary: 95 / 3.6
}),
symbolizer: { strokeColor: "cyan" }
});
var ruleHighwayFast = new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.GREATER_THAN,
property: "avgvel",
value: 95 / 3.6
}),
symbolizer: { strokeColor: "blue" }
});
gpxStyle.addRules([ruleStopping,
ruleCitySlow,
ruleCityFast,
ruleHighwaySlow,
ruleHighwayFast]);
var gpxStyleMap = new OpenLayers.StyleMap({'default': gpxStyle});
return gpxStyleMap;
}
function csCreateLayerGpx(serverUrl, min_lat, max_lat,
min_lon, max_lon,
min_time, max_time) {
var layerGpx =
new OpenLayers.Layer.GML
("GML",
serverUrl + "slices.gpx?"
+ "min_lat=" + min_lat
+ "&max_lat=" + max_lat
+ "&min_lon=" + min_lon
+ "&max_lon=" + max_lon
+ "&min_time=" + min_time
+ "&max_time=" + max_time
, {
format:
OpenLayers.Format.GPX,
styleMap:
gpxStyleMap,
projection:
new OpenLayers.Projection("EPSG:4326")
});
// layerGpx.requestSuccess = function (request) {
// window.onerror("Yepp, GML worked fine");
// this.prototype.requestSuccess(request);
// }
return layerGpx;
}
function dateToString(date) {
- var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; }
+ var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; };
// 2009-05-01T00:00:00Z
var timestring = String(date.getUTCFullYear())
+ "-" + zeropad(date.getUTCMonth() + 1)
+ "-" + zeropad(date.getUTCDate())
+ "T" + zeropad(date.getUTCHours())
+ ":" + zeropad(date.getUTCMinutes())
+ ":" + zeropad(date.getUTCSeconds())
+ "Z";
return timestring;
}
// Local Variables:
// indent-tabs-mode:nil
// c-basic-offset:4
// tab-width:8
// End:
diff --git a/webapp/public/map.html b/webapp/public/map.html
index d60a863..314d185 100644
--- a/webapp/public/map.html
+++ b/webapp/public/map.html
@@ -1,423 +1,432 @@
<html>
<head>
<meta name="viewport" content="width = device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
<title>Car Communication App</title>
<script src="http://code.google.com/apis/gears/gears_init.js"></script>
<!-- bring in the OpenLayers javascript library
(here we bring it from the remote site, but you could
easily serve up this javascript yourself) -->
<script src="OpenLayers.js"></script>
<!--script src="http://www.openlayers.org/api/OpenLayers.js"></script-->
<!-- bring in the OpenStreetMap OpenLayers layers.
Using this hosted file will make sure we are kept up
to date with any necessary changes -->
<script src="OpenStreetMap.js"></script>
<!--script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script-->
<!-- The geo-location-javascript code -->
<script src="geo.js"></script>
<!-- The personal functions from CS -->
<script src="csfuncs.js"></script>
+ <!-- ------------------------------------------------------ -->
<script type="text/javascript">
+function setStatus(id, text, bgcolor) {
+ var td = document.getElementById(id);
+ var div = document.getElementById(id + "Text");
+ if (td && div) {
+ if (text) {
+ div.firstChild.nodeValue = text;
+ }
+ if (bgcolor) {
+ td.setAttribute("bgcolor", bgcolor);
+ }
+ } else {
+ window.onerror ("Function setStatus() was called with non-existing ID of html element, \"" + id + "\"");
+ }
+}
+
function csErrorHandler (msg, file, line) {
- var fullMsg = "General Error: " + msg + " in file: " + file + ":" + line;
- setStatus("GPSStatus", "General: " + fullMsg, "red");
+ var fullMsg = "General Error: " + msg + " in file: " + file + ":" + line;
+ setStatus("GPSStatus", "General: " + fullMsg, "red");
- var span2 = document.getElementById("GeneralError");
- if (span2) {
- span2.firstChild.nodeValue = fullMsg;
- }
- return true;
-};
+ var span2 = document.getElementById("GeneralError");
+ if (span2) {
+ span2.firstChild.nodeValue = fullMsg;
+ }
+ return true;
+}
OpenLayers.Util.onImageLoadError = function() {
- setStatus("MapStatus", "Map: Cannot load images", "red");
+ setStatus("MapStatus", "Map: Cannot load images", "red");
};
// Complex object of type OpenLayers.Map
var map;
var layerGpx1;
var layerGpx2;
var useLayerGpx1;
var gpxStyleMap;
var serverUrl;
var initialized;
var lastPos;
var currentPos;
var sendInterval;
// Global error handler
window.onerror = csErrorHandler;
function setLatLon(lat, lon) {
- var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
- var currentZoom = map.getZoom();
- map.setCenter (lonLat, currentZoom);
+ var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
+ var currentZoom = map.getZoom();
+ map.setCenter (lonLat, currentZoom);
}
function zoomTo(lat, lon, zoom) {
- var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
- map.setCenter (lonLat, zoom);
+ var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
+ map.setCenter (lonLat, zoom);
}
function zoomToHamburg() {
- // Start position for the map (hardcoded here for simplicity)
- zoomTo(53.5514, 9.99, 12);
+ // Start position for the map (hardcoded here for simplicity)
+ zoomTo(53.5514, 9.99, 12);
}
-function on_geo_error(p) {
- setStatus("GPSStatus", "GPS Error: " + p.message, "red");
+function on_gpx_loadstart() {
+ var numWays = this.features.length;
+ setStatus("SliceStatus", "Loading... " + numWays, "lightyellow");
}
-function on_geo_success(p) {
- setStatus("GPSStatus", "GPS ok", "lightgreen");
- setLatLon(p.coords.latitude, p.coords.longitude);
- currentPos = p;
- sendDataMaybe();
- loadWaysDefault();
-}
+function on_gpx_loadend() {
+ var numWays = this.features.length;
+ if (numWays > 0) {
+ setStatus("SliceStatus", "Ways ok: " + numWays + " lines", "lightgreen");
+ } else {
+ setStatus("SliceStatus", "No Ways received", "yellow");
+ }
-function requestPos() {
- if (!document.forms.checkboxes.elements.GPSCheck.checked) {
- setStatus("GPSStatus", "GPS disabled", "yellow");
+ if (useLayerGpx1) {
+ if (layerGpx1) {
+ layerGpx1.destroy();
+ }
} else {
- setStatus("GPSStatus", "Request GPS...", "lightgreen");
- geo_position_js.getCurrentPosition(on_geo_success, on_geo_error,
- {enableHighAccuracy : true,
- timeout : 10000,
- maximumAge : 20000});
- //{enableHighAccuracy : true});
-// timeout : 1000, // milliseconds
-// maximumAge : 10000 // milliseconds
-// });
- //setStatus("MapStatus", "Map: 3b", "yellow");
+ if (layerGpx2) {
+ layerGpx2.destroy();
+ }
}
}
-function on_interval() {
- if (!document.forms.checkboxes.elements.GPSCheck.checked) {
- //setStatus("GPSStatus", "GPS disabled", "yellow");
- return;
- }
+function loadWaysLayer(min_time, max_time) {
+ var lonLatUR = map.getLonLatFromPixel(new OpenLayers.Pixel(0,0))
+ .transform(map.getProjectionObject(),
+ new OpenLayers.Projection("EPSG:4326"));
+
+ var mapSize = map.getSize();
+ var lonLatLL = map.getLonLatFromPixel(new OpenLayers.Pixel(mapSize.w, mapSize.h))
+ .transform(map.getProjectionObject(),
+ new OpenLayers.Projection("EPSG:4326"));
+
+ var min_lat = lonLatLL.lat;
+ var max_lon = lonLatLL.lon;
+ var max_lat = lonLatUR.lat;
+ var min_lon = lonLatUR.lon;
+
+ // Add the Layer with GPX Track
+ var layerGpx = csCreateLayerGpx(serverUrl,
+ min_lat, max_lat,
+ min_lon, max_lon,
+ min_time, max_time);
+
+ layerGpx.events.register("loadend", layerGpx, on_gpx_loadend);
+ layerGpx.events.register("loadstart", layerGpx, on_gpx_loadstart);
+
+ return layerGpx;
+}
- if (currentPos) {
- var now = new Date();
- var diffmsec = now.getTime() - currentPos.timestamp;
- var diffsec = diffmsec / 1000;
- var diffstr = diffsec.toFixed(1);
- setStatus("GPSStatus",
- "GPS ok; " + diffstr + "s old",
- "lightgreen");
- if (diffsec > 7)
- requestPos();
- if (diffsec >= sendInterval) {
- // Uh, we need to create a new object here
- currentPos = { timestamp: now.getTime(),
- coords : {
- latitude : currentPos.coords.latitude,
- longitude : currentPos.coords.longitude
- }};
- sendDataMaybe();
+function loadWays(min_time, max_time) {
+ if (useLayerGpx1) {
+ useLayerGpx1 = false;
+ if (layerGpx1) {
+ layerGpx1.destroy();
}
+ layerGpx1 = loadWaysLayer(min_time, max_time);
+ map.addLayer(layerGpx1);
} else {
- setStatus("SendStatus",
- "Waiting for GPS",
- "yellow");
- requestPos();
+ useLayerGpx1 = true;
+ if (layerGpx2) {
+ layerGpx2.destroy();
+ }
+ layerGpx2 = loadWaysLayer(min_time, max_time);
+ map.addLayer(layerGpx2);
}
}
-function sendDataMaybe() {
- if (currentPos) {
- if (!lastPos)
- lastPos = currentPos;
- var diffmsec = currentPos.timestamp - lastPos.timestamp;
- var diffsec = diffmsec / 1000;
- if (diffsec >= sendInterval) {
- sendDataNow();
- }
+function loadWaysDefault() {
+ if (!document.forms.checkboxes.elements.SliceCheck.checked) {
+ setStatus("SliceStatus", "Ways disabled", "yellow");
+ return;
}
+
+ var num_minutes = 20220; // 2 weeks + 1 hour
+ var max_time = new Date();
+ var min_time = new Date(max_time.getDate() - num_minutes * 60 * 1000);
+ loadWays(dateToString(min_time), dateToString(max_time));
}
function sendDataNow() {
if (!document.forms.checkboxes.elements.SendCheck.checked) {
setStatus("SendStatus", "Sending disabled", "yellow");
return;
}
if (!currentPos) {
setStatus("SendStatus", "No Valid Positions to send", "red");
return;
}
if (!lastPos) {
lastPos = currentPos;
}
setStatus("SendStatus", "Sending...", "lightgreen");
var endTimestamp = currentPos.timestamp;
var diffsec = (endTimestamp - lastPos.timestamp) / 1000;
if (diffsec == 0) {
endTimestamp = (new Date()).getTime();
diffsec = (endTimestamp - lastPos.timestamp) / 1000;
}
var endLat = currentPos.coords.latitude.toFixed(6);
var endLon = currentPos.coords.longitude.toFixed(6);
var startLat = lastPos.coords.latitude.toFixed(6);
var startLon = lastPos.coords.longitude.toFixed(6);
var time = dateToString(new Date(endTimestamp));
if (diffsec == 0) {
setStatus("SendStatus", "Oops, diffsec = 0", "red");
alert("currentPos.timestamp=" + currentPos.timestamp + " lastPos.timestamp=" + lastPos.timestamp + " date=" + (new Date()).getTime());
return;
}
var dur = diffsec.toFixed(2);
var url = serverUrl + "slices";
var params = "slice[lat]=" + endLat
+ "&slice[lon]=" + endLon
+ "&slice[time]=" + time
+ "&slice[duration]=" + dur
+ "&slice[startlat]=" + startLat
+ "&slice[startlon]=" + startLon;
var http = new XMLHttpRequest();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() { //Call a function when the state changes.
if (http.readyState) {
if (http.status >= 200 && http.status <= 210) {
setStatus("SendStatus", "Sent", "lightgreen");
//alert(http.responseText);
} else {
setStatus("SendStatus", "Position not sent (" + http.status + ")", "yellow");
//alert(http.responseText);
}
}
- }
+ };
http.send(params);
//alert("Will send: " + url + "?" + params);
lastPos = currentPos;
}
-//Initialise the 'map' object
-function init() {
-
- sendInterval = 60;
- serverUrl = "";
- useLayerGpx1 = true;
-
- // Did we get our auxiliary files? Then switch General to green
- if (OpenLayers && csCreateMap) {
- //setStatus("GeneralStatus", null, "lightgreen");
- }
-
- if (typeof(window.google) != "undefined" && typeof(window.google.gears) != "undefined"){
- setStatus("GPSStatus", "GPS: Google Gears", "lightyellow");
- } else if (typeof(navigator.geolocation) != "undefined") {
- setStatus("GPSStatus", "GPS: Mozilla Navigator available", "lightyellow");
- } else {
- setStatus("GPSStatus", "GPS: Please install Google Gears, http://gears.google.com", "yellow");
+function sendDataMaybe() {
+ if (currentPos) {
+ if (!lastPos) {
+ lastPos = currentPos;
}
+ var diffmsec = currentPos.timestamp - lastPos.timestamp;
+ var diffsec = diffmsec / 1000;
+ if (diffsec >= sendInterval) {
+ sendDataNow();
+ }
+ }
+}
- //setStatus("MapStatus", "Map: 1", "yellow");
- // Define the map layer
- map = csCreateMap();
+function on_geo_error(p) {
+ setStatus("GPSStatus", "GPS Error: " + p.message, "red");
+}
- //setStatus("MapStatus", "Map: 2", "yellow");
- // Define the styles for the way slices
- gpxStyleMap = csCreateGpxStyleMap();
+function on_geo_success(p) {
+ setStatus("GPSStatus", "GPS ok", "lightgreen");
+ setLatLon(p.coords.latitude, p.coords.longitude);
+ currentPos = p;
+ sendDataMaybe();
+ loadWaysDefault();
+}
- //setStatus("MapStatus", "Map: 3", "yellow");
+function requestPos() {
+ if (!document.forms.checkboxes.elements.GPSCheck.checked) {
+ setStatus("GPSStatus", "GPS disabled", "yellow");
+ } else {
+ setStatus("GPSStatus", "Request GPS...", "lightgreen");
+ geo_position_js.getCurrentPosition(on_geo_success, on_geo_error,
+ {enableHighAccuracy : true,
+ timeout : 15000,
+ maximumAge : 30000});
+ //{enableHighAccuracy : true});
+// timeout : 1000, // milliseconds
+// maximumAge : 10000 // milliseconds
+// });
+ //setStatus("MapStatus", "Map: 3b", "yellow");
+ }
+}
- //determine if the handset has client side geo location capabilities
- if (geo_position_js.init()) {
- //setStatus("MapStatus", "Map: 3a", "yellow");
+function on_interval() {
+ if (!document.forms.checkboxes.elements.GPSCheck.checked) {
+ //setStatus("GPSStatus", "GPS disabled", "yellow");
+ return;
+ }
+
+ if (currentPos) {
+ var now = new Date();
+ var diffmsec = now.getTime() - currentPos.timestamp;
+ var diffsec = diffmsec / 1000;
+ var diffstr = diffsec.toFixed(1);
+ setStatus("GPSStatus",
+ "GPS ok; " + diffstr + "s old",
+ "lightgreen");
+ if (diffsec > 7) {
requestPos();
- //setStatus("MapStatus", "Map: 3b", "yellow");
}
- else{
- //setStatus("MapStatus", "Map: 3c", "yellow");
- on_geo_error({message: "No GPS available"});
+ if (diffsec >= sendInterval) {
+ // Uh, we need to create a new object here
+ currentPos = { timestamp: now.getTime(),
+ coords : {
+ latitude : currentPos.coords.latitude,
+ longitude : currentPos.coords.longitude
+ }};
+ sendDataMaybe();
}
+ } else {
+ setStatus("SendStatus",
+ "Waiting for GPS",
+ "yellow");
+ requestPos();
+ }
+}
- //setStatus("MapStatus", "Map: 4", "yellow");
- // Choose Hamburg as center
- zoomToHamburg();
-
- initialized = 1;
+//Initialise the 'map' object
+function init() {
+
+ sendInterval = 60;
+ serverUrl = "";
+ useLayerGpx1 = true;
- loadWaysDefault();
+ // Did we get our auxiliary files? Then switch General to green
+ if (OpenLayers && csCreateMap) {
+ //setStatus("GeneralStatus", null, "lightgreen");
+ }
- setInterval(on_interval, 2500); // milliseconds
+ if (typeof(window.google) != "undefined" && typeof(window.google.gears) != "undefined"){
+ setStatus("GPSStatus", "GPS: Google Gears", "lightyellow");
+ } else if (typeof(navigator.geolocation) != "undefined") {
+ setStatus("GPSStatus", "GPS: Mozilla Navigator available", "lightyellow");
+ } else {
+ setStatus("GPSStatus", "GPS: Please install Google Gears, http://gears.google.com", "yellow");
+ }
- if (geo_position_js.init()) {
- requestPos();
- } else {
- on_geo_error({message: "No GPS available"});
- }
+ //setStatus("MapStatus", "Map: 1", "yellow");
+ // Define the map layer
+ map = csCreateMap();
-}
+ //setStatus("MapStatus", "Map: 2", "yellow");
+ // Define the styles for the way slices
+ gpxStyleMap = csCreateGpxStyleMap();
-function setServerUrl(value) {
- serverUrl = value;
-}
+ //setStatus("MapStatus", "Map: 3", "yellow");
-function loadWaysDefault() {
- if (!document.forms.checkboxes.elements.SliceCheck.checked) {
- setStatus("SliceStatus", "Ways disabled", "yellow");
- return;
+ //determine if the handset has client side geo location capabilities
+ if (geo_position_js.init()) {
+ //setStatus("MapStatus", "Map: 3a", "yellow");
+ requestPos();
+ //setStatus("MapStatus", "Map: 3b", "yellow");
+ }
+ else{
+ //setStatus("MapStatus", "Map: 3c", "yellow");
+ on_geo_error({message: "No GPS available"});
}
- var num_minutes = 20220; // 2 weeks + 1 hour
- var max_time = new Date();
- var min_time = new Date(max_time.getDate() - num_minutes * 60 * 1000);
- loadWays(dateToString(min_time), dateToString(max_time));
-}
+ //setStatus("MapStatus", "Map: 4", "yellow");
+ // Choose Hamburg as center
+ zoomToHamburg();
-function loadWays(min_time, max_time) {
- if (useLayerGpx1) {
- useLayerGpx1 = false;
- if (layerGpx1) {
- layerGpx1.destroy();
- }
- layerGpx1 = loadWaysLayer(min_time, max_time);
- map.addLayer(layerGpx1);
- } else {
- useLayerGpx1 = true;
- if (layerGpx2) {
- layerGpx2.destroy();
- }
- layerGpx2 = loadWaysLayer(min_time, max_time);
- map.addLayer(layerGpx2);
- }
-}
+ initialized = 1;
-function on_gpx_loadstart() {
- var numWays = this.features.length;
- setStatus("SliceStatus", "Loading... " + numWays, "lightyellow");
-}
+ loadWaysDefault();
-function on_gpx_loadend() {
- var numWays = this.features.length;
- if (numWays > 0)
- setStatus("SliceStatus", "Ways ok: " + numWays + " lines", "lightgreen");
- else
- setStatus("SliceStatus", "No Ways received", "yellow");
+ setInterval(on_interval, 2500); // milliseconds
- if (useLayerGpx1) {
- if (layerGpx1) {
- layerGpx1.destroy();
- }
+ if (geo_position_js.init()) {
+ requestPos();
} else {
- if (layerGpx2) {
- layerGpx2.destroy();
- }
+ on_geo_error({message: "No GPS available"});
}
+
+}
+
+function setServerUrl(value) {
+ serverUrl = value;
}
function on_osm_loadstart() {
setStatus("MapStatus", "Loading...", "yellow");
setStatus("SendStatus", "", "lightyellow");
}
function on_osm_tileloaded() {
var numRemainingTiles = this.numLoadingTiles;
- if (numRemainingTiles > 0)
+ if (numRemainingTiles > 0) {
setStatus("MapStatus", "Loading; " + this.numLoadingTiles + " images remaining", "lightgreen");
- else
+ }
+ else {
setStatus("MapStatus", "Loaded", "lightgreen");
-}
-
-function loadWaysLayer(min_time, max_time) {
- var lonLatUR = map.getLonLatFromPixel(new OpenLayers.Pixel(0,0))
- .transform(map.getProjectionObject(),
- new OpenLayers.Projection("EPSG:4326"));
-
- var mapSize = map.getSize();
- var lonLatLL = map.getLonLatFromPixel(new OpenLayers.Pixel(mapSize.w, mapSize.h))
- .transform(map.getProjectionObject(),
- new OpenLayers.Projection("EPSG:4326"));
-
- var min_lat = lonLatLL.lat;
- var max_lon = lonLatLL.lon;
- var max_lat = lonLatUR.lat;
- var min_lon = lonLatUR.lon;
-
- // Add the Layer with GPX Track
- var layerGpx = csCreateLayerGpx(serverUrl,
- min_lat, max_lat,
- min_lon, max_lon,
- min_time, max_time);
-
- layerGpx.events.register("loadend", layerGpx, on_gpx_loadend);
- layerGpx.events.register("loadstart", layerGpx, on_gpx_loadstart);
-
- return layerGpx;
-}
-
-function setStatus(id, text, bgcolor) {
- var td = document.getElementById(id);
- var div = document.getElementById(id + "Text");
- if (td && div) {
- if (text)
- div.firstChild.nodeValue = text;
- if (bgcolor)
- td.setAttribute("bgcolor", bgcolor);
- } else {
- window.onerror ("Function setStatus() was called with non-existing ID of html element, \"" + id + "\"");
- }
+ }
}
</script>
+ <!-- ------------------------------------------------------ -->
</head>
<!-- body.onload is called once the page is loaded (call the 'init' function) -->
<body onload="init();">
<form name="checkboxes" action="">
<table border="1" width="100%"><tr>
<td align="center" id="GPSStatus" bgcolor="lightyellow">
<input type="checkbox" name="GPSCheck" value="1" checked="checked" onchange="requestPos();">
<span id="GPSStatusText" onclick="requestPos();">GPS</span>
</td>
<td align="center" id="MapStatus" bgcolor="yellow">
<span id="MapStatusText">Map</span>
</td>
<td align="center" id="SliceStatus" bgcolor="lightyellow">
<input type="checkbox" name="SliceCheck" value="1" checked="checked" onchange="loadWaysDefault();">
<span id="SliceStatusText" onclick="loadWaysDefault();">Ways</span>
</td>
<td align="center" id="SendStatus">
<input type="checkbox" name="SendCheck" value="1" checked="checked" onchange="sendDataNow();">
<span id="SendStatusText" onclick="sendDataNow();">Sending</span>
</td>
</tr>
</table>
</form>
<!-- define a DIV into which the map will appear. Make it take up 400 pixels -->
<div id="map"></div>
<span name="GeneralError"></span>
</body>
</html>
<!-- Local Variables: -->
<!-- mode: javascript -->
<!-- indent-tabs-mode:nil -->
<!-- c-basic-offset:4 -->
<!-- tab-width:8 -->
<!-- End: -->
|
cstim/carcomm
|
f715dbdd6cddd5383f2693416d0b04d6df739359
|
Do the double-buffering switch already in the loadend callback.
|
diff --git a/webapp/public/map.html b/webapp/public/map.html
index dc22c2a..d60a863 100644
--- a/webapp/public/map.html
+++ b/webapp/public/map.html
@@ -1,425 +1,423 @@
<html>
<head>
<meta name="viewport" content="width = device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
<title>Car Communication App</title>
<script src="http://code.google.com/apis/gears/gears_init.js"></script>
<!-- bring in the OpenLayers javascript library
(here we bring it from the remote site, but you could
easily serve up this javascript yourself) -->
<script src="OpenLayers.js"></script>
<!--script src="http://www.openlayers.org/api/OpenLayers.js"></script-->
<!-- bring in the OpenStreetMap OpenLayers layers.
Using this hosted file will make sure we are kept up
to date with any necessary changes -->
<script src="OpenStreetMap.js"></script>
<!--script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script-->
<!-- The geo-location-javascript code -->
<script src="geo.js"></script>
<!-- The personal functions from CS -->
<script src="csfuncs.js"></script>
<script type="text/javascript">
function csErrorHandler (msg, file, line) {
var fullMsg = "General Error: " + msg + " in file: " + file + ":" + line;
setStatus("GPSStatus", "General: " + fullMsg, "red");
var span2 = document.getElementById("GeneralError");
if (span2) {
span2.firstChild.nodeValue = fullMsg;
}
return true;
};
OpenLayers.Util.onImageLoadError = function() {
setStatus("MapStatus", "Map: Cannot load images", "red");
};
// Complex object of type OpenLayers.Map
var map;
var layerGpx1;
var layerGpx2;
var useLayerGpx1;
var gpxStyleMap;
var serverUrl;
var initialized;
var lastPos;
var currentPos;
var sendInterval;
// Global error handler
window.onerror = csErrorHandler;
function setLatLon(lat, lon) {
var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
var currentZoom = map.getZoom();
map.setCenter (lonLat, currentZoom);
}
function zoomTo(lat, lon, zoom) {
var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.setCenter (lonLat, zoom);
}
function zoomToHamburg() {
// Start position for the map (hardcoded here for simplicity)
zoomTo(53.5514, 9.99, 12);
}
function on_geo_error(p) {
setStatus("GPSStatus", "GPS Error: " + p.message, "red");
}
function on_geo_success(p) {
setStatus("GPSStatus", "GPS ok", "lightgreen");
setLatLon(p.coords.latitude, p.coords.longitude);
currentPos = p;
sendDataMaybe();
loadWaysDefault();
}
function requestPos() {
if (!document.forms.checkboxes.elements.GPSCheck.checked) {
setStatus("GPSStatus", "GPS disabled", "yellow");
} else {
setStatus("GPSStatus", "Request GPS...", "lightgreen");
geo_position_js.getCurrentPosition(on_geo_success, on_geo_error,
{enableHighAccuracy : true,
timeout : 10000,
maximumAge : 20000});
//{enableHighAccuracy : true});
// timeout : 1000, // milliseconds
// maximumAge : 10000 // milliseconds
// });
//setStatus("MapStatus", "Map: 3b", "yellow");
}
}
function on_interval() {
if (!document.forms.checkboxes.elements.GPSCheck.checked) {
//setStatus("GPSStatus", "GPS disabled", "yellow");
return;
}
if (currentPos) {
var now = new Date();
var diffmsec = now.getTime() - currentPos.timestamp;
var diffsec = diffmsec / 1000;
var diffstr = diffsec.toFixed(1);
setStatus("GPSStatus",
"GPS ok; " + diffstr + "s old",
"lightgreen");
if (diffsec > 7)
requestPos();
if (diffsec >= sendInterval) {
// Uh, we need to create a new object here
currentPos = { timestamp: now.getTime(),
coords : {
latitude : currentPos.coords.latitude,
longitude : currentPos.coords.longitude
}};
sendDataMaybe();
}
} else {
setStatus("SendStatus",
"Waiting for GPS",
"yellow");
requestPos();
}
}
function sendDataMaybe() {
if (currentPos) {
if (!lastPos)
lastPos = currentPos;
var diffmsec = currentPos.timestamp - lastPos.timestamp;
var diffsec = diffmsec / 1000;
if (diffsec >= sendInterval) {
sendDataNow();
}
}
}
function sendDataNow() {
if (!document.forms.checkboxes.elements.SendCheck.checked) {
setStatus("SendStatus", "Sending disabled", "yellow");
return;
}
if (!currentPos) {
setStatus("SendStatus", "No Valid Positions to send", "red");
return;
}
if (!lastPos) {
lastPos = currentPos;
}
setStatus("SendStatus", "Sending...", "lightgreen");
var endTimestamp = currentPos.timestamp;
var diffsec = (endTimestamp - lastPos.timestamp) / 1000;
if (diffsec == 0) {
endTimestamp = (new Date()).getTime();
diffsec = (endTimestamp - lastPos.timestamp) / 1000;
}
var endLat = currentPos.coords.latitude.toFixed(6);
var endLon = currentPos.coords.longitude.toFixed(6);
var startLat = lastPos.coords.latitude.toFixed(6);
var startLon = lastPos.coords.longitude.toFixed(6);
var time = dateToString(new Date(endTimestamp));
if (diffsec == 0) {
setStatus("SendStatus", "Oops, diffsec = 0", "red");
alert("currentPos.timestamp=" + currentPos.timestamp + " lastPos.timestamp=" + lastPos.timestamp + " date=" + (new Date()).getTime());
return;
}
var dur = diffsec.toFixed(2);
var url = serverUrl + "slices";
var params = "slice[lat]=" + endLat
+ "&slice[lon]=" + endLon
+ "&slice[time]=" + time
+ "&slice[duration]=" + dur
+ "&slice[startlat]=" + startLat
+ "&slice[startlon]=" + startLon;
var http = new XMLHttpRequest();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() { //Call a function when the state changes.
if (http.readyState) {
if (http.status >= 200 && http.status <= 210) {
setStatus("SendStatus", "Sent", "lightgreen");
//alert(http.responseText);
} else {
setStatus("SendStatus", "Position not sent (" + http.status + ")", "yellow");
//alert(http.responseText);
}
}
}
http.send(params);
//alert("Will send: " + url + "?" + params);
lastPos = currentPos;
}
//Initialise the 'map' object
function init() {
sendInterval = 60;
serverUrl = "";
useLayerGpx1 = true;
// Did we get our auxiliary files? Then switch General to green
if (OpenLayers && csCreateMap) {
//setStatus("GeneralStatus", null, "lightgreen");
}
if (typeof(window.google) != "undefined" && typeof(window.google.gears) != "undefined"){
setStatus("GPSStatus", "GPS: Google Gears", "lightyellow");
} else if (typeof(navigator.geolocation) != "undefined") {
setStatus("GPSStatus", "GPS: Mozilla Navigator available", "lightyellow");
} else {
setStatus("GPSStatus", "GPS: Please install Google Gears, http://gears.google.com", "yellow");
}
//setStatus("MapStatus", "Map: 1", "yellow");
// Define the map layer
map = csCreateMap();
//setStatus("MapStatus", "Map: 2", "yellow");
// Define the styles for the way slices
gpxStyleMap = csCreateGpxStyleMap();
//setStatus("MapStatus", "Map: 3", "yellow");
//determine if the handset has client side geo location capabilities
if (geo_position_js.init()) {
//setStatus("MapStatus", "Map: 3a", "yellow");
requestPos();
//setStatus("MapStatus", "Map: 3b", "yellow");
}
else{
//setStatus("MapStatus", "Map: 3c", "yellow");
on_geo_error({message: "No GPS available"});
}
//setStatus("MapStatus", "Map: 4", "yellow");
// Choose Hamburg as center
zoomToHamburg();
initialized = 1;
loadWaysDefault();
setInterval(on_interval, 2500); // milliseconds
if (geo_position_js.init()) {
requestPos();
} else {
on_geo_error({message: "No GPS available"});
}
}
function setServerUrl(value) {
serverUrl = value;
}
function loadWaysDefault() {
if (!document.forms.checkboxes.elements.SliceCheck.checked) {
setStatus("SliceStatus", "Ways disabled", "yellow");
return;
}
var num_minutes = 20220; // 2 weeks + 1 hour
var max_time = new Date();
var min_time = new Date(max_time.getDate() - num_minutes * 60 * 1000);
loadWays(dateToString(min_time), dateToString(max_time));
}
function loadWays(min_time, max_time) {
- if (useLayerGpx1) {
- if (layerGpx2) {
- layerGpx2.visibility = true;
- }
- if (layerGpx1) {
- map.removeLayer(layerGpx1);
- layerGpx1.destroy();
- }
- layerGpx1 = loadWaysLayer(min_time, max_time);
- map.addLayer(layerGpx1);
- layerGpx1.visibility = false;
-
- useLayerGpx1 = false;
- } else {
- if (layerGpx1) {
- layerGpx1.visibility = true;
- }
- if (layerGpx2) {
- map.removeLayer(layerGpx2);
- layerGpx2.destroy();
- }
- layerGpx2 = loadWaysLayer(min_time, max_time);
- map.addLayer(layerGpx2);
- layerGpx2.visibility = false;
-
- useLayerGpx1 = true;
- }
+ if (useLayerGpx1) {
+ useLayerGpx1 = false;
+ if (layerGpx1) {
+ layerGpx1.destroy();
+ }
+ layerGpx1 = loadWaysLayer(min_time, max_time);
+ map.addLayer(layerGpx1);
+ } else {
+ useLayerGpx1 = true;
+ if (layerGpx2) {
+ layerGpx2.destroy();
+ }
+ layerGpx2 = loadWaysLayer(min_time, max_time);
+ map.addLayer(layerGpx2);
+ }
}
function on_gpx_loadstart() {
var numWays = this.features.length;
setStatus("SliceStatus", "Loading... " + numWays, "lightyellow");
}
function on_gpx_loadend() {
var numWays = this.features.length;
if (numWays > 0)
setStatus("SliceStatus", "Ways ok: " + numWays + " lines", "lightgreen");
else
setStatus("SliceStatus", "No Ways received", "yellow");
+
+ if (useLayerGpx1) {
+ if (layerGpx1) {
+ layerGpx1.destroy();
+ }
+ } else {
+ if (layerGpx2) {
+ layerGpx2.destroy();
+ }
+ }
}
function on_osm_loadstart() {
setStatus("MapStatus", "Loading...", "yellow");
setStatus("SendStatus", "", "lightyellow");
}
function on_osm_tileloaded() {
var numRemainingTiles = this.numLoadingTiles;
if (numRemainingTiles > 0)
setStatus("MapStatus", "Loading; " + this.numLoadingTiles + " images remaining", "lightgreen");
else
setStatus("MapStatus", "Loaded", "lightgreen");
}
function loadWaysLayer(min_time, max_time) {
var lonLatUR = map.getLonLatFromPixel(new OpenLayers.Pixel(0,0))
.transform(map.getProjectionObject(),
new OpenLayers.Projection("EPSG:4326"));
var mapSize = map.getSize();
var lonLatLL = map.getLonLatFromPixel(new OpenLayers.Pixel(mapSize.w, mapSize.h))
.transform(map.getProjectionObject(),
new OpenLayers.Projection("EPSG:4326"));
var min_lat = lonLatLL.lat;
var max_lon = lonLatLL.lon;
var max_lat = lonLatUR.lat;
var min_lon = lonLatUR.lon;
// Add the Layer with GPX Track
var layerGpx = csCreateLayerGpx(serverUrl,
min_lat, max_lat,
min_lon, max_lon,
min_time, max_time);
layerGpx.events.register("loadend", layerGpx, on_gpx_loadend);
layerGpx.events.register("loadstart", layerGpx, on_gpx_loadstart);
return layerGpx;
}
function setStatus(id, text, bgcolor) {
var td = document.getElementById(id);
var div = document.getElementById(id + "Text");
if (td && div) {
if (text)
div.firstChild.nodeValue = text;
if (bgcolor)
td.setAttribute("bgcolor", bgcolor);
} else {
window.onerror ("Function setStatus() was called with non-existing ID of html element, \"" + id + "\"");
}
}
</script>
</head>
<!-- body.onload is called once the page is loaded (call the 'init' function) -->
<body onload="init();">
<form name="checkboxes" action="">
<table border="1" width="100%"><tr>
<td align="center" id="GPSStatus" bgcolor="lightyellow">
<input type="checkbox" name="GPSCheck" value="1" checked="checked" onchange="requestPos();">
<span id="GPSStatusText" onclick="requestPos();">GPS</span>
</td>
<td align="center" id="MapStatus" bgcolor="yellow">
<span id="MapStatusText">Map</span>
</td>
<td align="center" id="SliceStatus" bgcolor="lightyellow">
<input type="checkbox" name="SliceCheck" value="1" checked="checked" onchange="loadWaysDefault();">
<span id="SliceStatusText" onclick="loadWaysDefault();">Ways</span>
</td>
<td align="center" id="SendStatus">
<input type="checkbox" name="SendCheck" value="1" checked="checked" onchange="sendDataNow();">
<span id="SendStatusText" onclick="sendDataNow();">Sending</span>
</td>
</tr>
</table>
</form>
<!-- define a DIV into which the map will appear. Make it take up 400 pixels -->
<div id="map"></div>
<span name="GeneralError"></span>
</body>
</html>
<!-- Local Variables: -->
<!-- mode: javascript -->
<!-- indent-tabs-mode:nil -->
<!-- c-basic-offset:4 -->
<!-- tab-width:8 -->
<!-- End: -->
|
paulgirard/pygexf
|
410f06219e1c193df965e0ce28ebe8a651b3af56
|
more python3 fixes
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index c11d6b8..eef0a84 100755
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,850 +1,850 @@
# -*- coding: utf-8 -*-
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
from lxml import etree
from datetime import date
import itertools
import traceback
# missing features :
# data validation regarding attribute types
# phylogeny
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
def msg_unexpected_tag(expected, got):
print("Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got))
def ns_clean(token):
i = token.find('}')
return token[i + 1:]
class Gexf:
def __init__(self, creator, description):
self.creator = creator
self.description = description
self.graphs = []
self.xmlns = "http://www.gephi.org/gexf/1.2draft"
self.xsi = "http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation = "http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.2draft.xsd"
self.viz = "http://www.gexf.net/1.2draft/viz"
self.version = "1.2"
def addGraph(self, type, mode, label, timeformat=""):
g = Graph(type, mode, label, timeformat)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{" + self.xmlns + "}gexf", version=self.version, nsmap={None: self.xmlns, 'viz': self.viz, 'xsi': self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation", self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified", date.today().isoformat())
etree.SubElement(meta, "creator").text = self.creator
etree.SubElement(meta, "description").text = self.description
for graph in self.graphs:
gexfXML.append(graph.getXML())
return gexfXML
def write(self, file, print_stat=True):
file.write(etree.tostring(self.getXML(), pretty_print=True, encoding='utf-8', xml_declaration=True))
if print_stat is True:
self.print_stat()
def print_stat(self):
for graph in self.graphs:
graph.print_stat()
@staticmethod
def importXML(gexf_file):
""" import gexf xml meta tags to create a Gexf Object and delegate Graph extraction to Graph class"""
# parse the gexf file
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse((gexf_file), parser)
# start create Gexf Object
gexf_xml = tree.getroot()
tag = ns_clean(gexf_xml.tag).lower()
if tag != "gexf":
msg_unexpected_tag("gexf", tag)
return
gexf_obj = None
for child in gexf_xml:
tag = ns_clean(child.tag).lower()
# create a gexf object by importing meta tag
if tag == "meta":
meta_xml = child
for child in meta_xml:
tag = ns_clean(child.tag).lower()
if tag == "creator":
creator = child.text
if tag == "description":
description = child.text
gexf_obj = Gexf(creator=creator, description=description)
# export graph xml through Graph Class
if tag == "graph":
graph_xml = child
if gexf_obj is None:
msg_unexpected_tag("meta", tag)
return
Graph.importXML(graph_xml, gexf_obj)
return gexf_obj
class Graph:
def __init__(self, type, mode, label, time_format="double", start="", end=""):
# control variable
self.authorizedType = ("directed", "undirected")
self.authorizedMode = ("dynamic", "static")
# time format
# Discrete: integer or double
# Continuous : date (yyyy-mm-dd) or dateTime
# default : double
self.authorizedTimeFormat = ("integer", "double", "date", "dateTime")
self.defaultTimeFormat = "double"
self.defaultType = "directed"
self.defaultMode = "static"
self.label = label
if type in self.authorizedType:
self.type = type
else:
self.type = self.defaultType
if mode in self.authorizedMode:
self.mode = mode
else:
self.mode = self.defaultMode
if time_format in self.authorizedTimeFormat:
self.time_format = time_format
else:
self.time_format = self.defaultTimeFormat
self.start = start
self.end = end
self._attributes = Attributes()
self.attributes = self._attributes
self._nodes = {}
self.nodes = self._nodes
self._edges = {}
self.edges = self._edges
def addNode(self, id, label, start="", end="", startopen=False, endopen=False, pid="", r="", g="", b="", spells=[]):
self._nodes[str(id)] = Node(self, id, label, start, end, pid, r, g, b, spells, startopen, endopen)
return self._nodes[str(id)]
def nodeExists(self, id):
if id in self._nodes.keys():
return 1
else:
return 0
def addEdge(self, id, source, target, weight="", start="", end="", label="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self._edges[str(id)] = Edge(self, id, source, target, weight, start, end, label, r, g, b, spells, startopen, endopen)
return self._edges[str(id)]
def addNodeAttribute(self, title, defaultValue=None, type="integer", mode="static", force_id=""):
# add to NodeAttributes
return self._attributes.declareAttribute("node", type, defaultValue, title, mode, force_id)
def addDefaultAttributesToNode(self, node):
""" deprecated """
pass
def checkNodeAttribute(self, id, value, start, end):
"""deprecated"""
pass
# check conformity with type is missing
# if id in self._nodesAttributes.keys() :
# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self, title, defaultValue, type="integer", mode="static", force_id=""):
return self._attributes.declareAttribute("edge", type, defaultValue, title, mode, force_id)
def addDefaultAttributesToEdge(self, edge):
""" deprecated """
pass
def checkEdgeAttribute(self, id, value, start, end):
"""deprecated """
pass
# # check conformity with type is missing
# if id in self._edgesAttributes.keys() :
# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self):
# return lxml etree element
graphXML = etree.Element("graph", defaultedgetype=self.type, mode=self.mode, label=self.label, timeformat=self.time_format)
for attributesElement in self.attributes.getAttributesDeclarationXML():
graphXML.append(attributesElement)
nodesXML = etree.SubElement(graphXML, "nodes")
- node_ids = self._nodes.keys()
+ node_ids = list(self._nodes.keys())
node_ids.sort()
for id in node_ids:
nodesXML.append(self._nodes[id].getXML())
edgesXML = etree.SubElement(graphXML, "edges")
- edge_ids = self._edges.keys()
+ edge_ids = list(self._edges.keys())
edge_ids.sort()
for id in edge_ids:
edgesXML.append(self._edges[id].getXML())
return graphXML
@staticmethod
def importXML(graph_xml, gexf_obj):
""" import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""
# get Graph attributes
type = ""
mode = ""
label = ""
timeformat = "double"
for attr in graph_xml.attrib:
attr = attr.lower()
if attr == "defaultedgetype":
type = graph_xml.attrib[attr]
if attr == "mode":
mode = graph_xml.attrib[attr]
if attr == "label":
label = graph_xml.attrib[attr]
if attr == "timeformat":
timeformat = graph_xml.attrib[attr]
# create and attache the graph object to the Gexf object
graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label, timeformat=timeformat)
for child in graph_xml:
tag = ns_clean(child.tag).lower()
if tag == "attributes":
attributes_xml = child
# Delegate Attributes declaration to the attribute object
graph_obj.attributes.importAttributesXML(attributes_xml)
if tag == "nodes":
nodes_xml = child
# Delegate nodes creation to the Node class
Node.importXML(nodes_xml, graph_obj)
if tag == "edges":
edges_xml = child
# Delegate edges creation to the Edge class
Edge.importXML(edges_xml, graph_obj)
def print_stat(self):
print(self.label + " " + self.type + " " + self.mode + " " + self.start + " " + self.end)
print("number of nodes : " + str(len(self._nodes)))
print("number of edges : " + str(len(self._edges)))
class Attributes(dict):
"""
attributes=
{
"node" :
{ "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },
"edge" :
{ "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },
}
"""
def __init__(self):
self.type_choices = ["integer", "string", "float", "double", "boolean", "date", "URI"]
self.attClass_choices = ["node", "edge"]
self.mode_choices = ["static", "dynamic"]
for attClass in self.attClass_choices:
self[attClass] = {}
def declareAttribute(self, attClass, type, defaultValue, title="", mode="static", id=None):
"""
add a new attribute declaration to the graph
"""
if attClass in self.attClass_choices:
# should add quality control here on type and defaultValue
# if no id given generating a numerical one based on dict length
if not id:
id = str(len(self[attClass]))
self[attClass][id] = {"id": id, "type": type, "defaultValue": defaultValue, "mode": mode, "title": title}
return id
else:
raise Exception("wrong attClass : " + str(attClass) + " Should be in " + str(type_choices))
def makeAttributeInstance(self, attClass, id=None, value=None, start=None, end=None, startopen=False, endopen=False):
"""
generate an attribute to be include to a node or edge.
copied from the declared attributes, thus any attribute has to be declared first
"""
if attClass in self.attClass_choices:
if id in self[attClass].keys():
att = {"id": id}
att["value"] = value if value else self[attClass][id]["defaultValue"]
if self[attClass][id]["mode"] == "dynamic" and start or end:
# start & end will be discarded if the mode is set to static
if start:
att["start"] = start
if startopen:
att["startopen"] = startopen
if end:
att["end"] = end
if endopen:
att["endopen"] = endopen
return att
else:
raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute" % (id, ))
else:
raise Exception("wrong attClass : " + str(attClass) + " Should be in " + str(self.type_choices))
def getAttributesDeclarationXML(self):
""" generate attributes declaration XML """
# return lxml etree element
allAttributesXML = []
if len(self) > 0:
# iter on node and then edge atts
for attClass, atts in self.items():
# group by mode
key_mode = lambda att: att["mode"]
- atts_sorted_by_mode = sorted(atts.values(), key=key_mode, reverse=True)
+ atts_sorted_by_mode = sorted(list(atts.values()), key=key_mode, reverse=True)
for mode, atts in itertools.groupby(atts_sorted_by_mode, key_mode):
# generate on attributes by mode
attributesXML = etree.Element("attributes")
attributesXML.set("class", attClass)
attributesXML.set("mode", mode)
# generate attribute by id order
for att in sorted(atts, key=lambda att: att["id"]):
attributeXML = etree.SubElement(attributesXML, "attribute")
attributeXML.set("id", str(att["id"]))
attributeXML.set("title", att["title"])
attributeXML.set("type", att["type"])
if att["defaultValue"]:
etree.SubElement(attributeXML, "default").text = att["defaultValue"]
allAttributesXML.append(attributesXML)
return allAttributesXML
@staticmethod
def getAttributesXML(atts):
""" get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""
if len(atts) > 0:
attValuesXML = etree.Element("attvalues")
for att in atts:
attValueXML = etree.SubElement(attValuesXML, "attvalue")
attValueXML.set("for", str(att["id"]))
attValueXML.set("value", att["value"])
if "start" in att.keys() and not att["start"] == "":
attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen", att["start"])
if "end" in att.keys() and not att["end"] == "":
attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen", att["end"])
return attValuesXML
else:
return None
def importAttributesXML(self, attributes_xml):
""" get XML attributes declaration of a graph gexf"""
attr_class = None
mode = ""
for attr in attributes_xml.attrib:
attr = attr.lower()
if attr == "class":
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode":
mode = attributes_xml.attrib[attr]
for child in attributes_xml:
tag = ns_clean(child.tag).lower()
if tag == "attribute":
attribute_xml = child
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib:
attr = attr.lower()
if attr == "id":
id = attribute_xml.attrib[attr]
if attr == "title":
title = attribute_xml.attrib[attr]
if attr == "type":
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml:
tag = ns_clean(child.tag).lower()
if tag == "default":
default = child.text
self.declareAttribute(attr_class, type, default, title, mode, id)
def importAttributesValuesXML(self, attClass, attvalues_xml):
""" import attributes values from attvalues gexf xml tag attached to nodes or edges"""
atts = []
for attvalues in attvalues_xml:
for child in attvalues:
tag = ns_clean(child.tag).lower()
if tag == "attvalue":
attvalue_xml = child
id = ""
value = ""
start = ""
startopen = False
end = ""
endopen = False
for attr in attvalue_xml.attrib:
if attr == "for":
id = attvalue_xml.attrib[attr]
if attr == "value":
value = attvalue_xml.attrib[attr]
if attr == "start":
start = attvalue_xml.attrib[attr]
if attr == "end":
end = attvalue_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
atts.append(self.makeAttributeInstance(attClass, id, value, start, end, startopen, endopen))
return atts
class Spells(list):
'''
spells are time periods
spells is a list of dictionaries
a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}
'''
def getXML(self):
spellsXML = etree.Element("spells")
for spell in self:
spellXML = etree.SubElement(spellsXML, "spell")
if "start" in spell.keys():
spellXML.set("start", spell["start"])
if "end" in spell.keys():
spellXML.set("end", spell["end"])
return spellsXML
@staticmethod
def importXML(spellsxmltree):
return Spells([spell.attrib for spell in spellsxmltree])
class Node:
def __init__(self, graph, id, label, start="", end="", pid="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self.id = id
self.label = label
self.start = start
self.startopen = startopen
self.end = end
self.endopen = endopen
self.pid = pid
self._graph = graph
self.setColor(r, g, b)
#spells expecting format = [{start:"",end:""},...]
self.spells = spells
if not self.pid == "":
if not self._graph.nodeExists(self.pid):
raise Exception("pid " + self.pid + " node unknown, add nodes to graph first")
self._attributes = []
self.attributes = self._attributes
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self, id, value, start="", end="", startopen=False, endopen=False):
self._attributes.append(self._graph.attributes.makeAttributeInstance("node", id, value, start, end, startopen, endopen))
def getXML(self):
# return lxml etree element
try:
nodeXML = etree.Element("node", id=str(self.id), label=self.label)
if not self.start == "":
nodeXML.set("start" if not self.startopen else "startopen", self.start)
if not self.end == "":
nodeXML.set("end" if not self.endopen else "endopen", self.end)
if not self.pid == "":
nodeXML.set("pid", self.pid)
# attributes
if self._attributes:
nodeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells:
print("found spells in node " + self.id)
nodeXML.append(self.spells.getXML())
if not self.r == "" and not self.g == "" and not self.b == "":
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r", self.r)
colorXML.set("g", self.g)
colorXML.set("b", self.b)
return nodeXML
except Exception as e:
print(self.label)
print(self._attributes)
print(e)
traceback.print_exc()
exit()
def getAttributes(self):
attsFull = []
for att in self._attributes:
attFull = self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(nodes_xml, graph_obj):
for child in nodes_xml:
tag = ns_clean(child.tag).lower()
if tag == "node":
node_xml = child
id = ""
label = ""
start = ""
startopen = False
end = ""
endopen = False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib:
attr = attr.lower()
if attr == "id":
id = node_xml.attrib[attr]
if attr == "label":
label = node_xml.attrib[attr]
if attr == "start":
start = node_xml.attrib[attr]
if attr == "end":
start = node_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
if attr == "pid":
pid = node_xml.attrib[attr]
attvalues_xml = []
spells = []
for child in node_xml:
tag = ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml.append(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag == "spells":
spells = Spells.importXML(child)
node_obj = graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b, spells=spells)
node_obj._attributes = graph_obj.attributes.importAttributesValuesXML("node", attvalues_xml)
def setColor(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __str__(self):
return self.label
class Edge:
def __init__(self, graph, id, source, target, weight="", start="", end="", label="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self.id = id
self._graph = graph
if self._graph.nodeExists(source):
self._source = source
self.source = self._source
else:
raise Exception("source " + source + " node unknown, add nodes to graph first")
if self._graph.nodeExists(target):
self._target = target
self.target = self._target
else:
raise Exception("target " + target + " node unknown, add nodes to graph first")
self.start = start
self.startopen = startopen
self.end = end
self.endopen = endopen
self.weight = weight
self.label = label
self._attributes = []
self.attributes = self._attributes
# COLOR on edges now supported in GEXF 1.2
self.setColor(r, g, b)
#spells expecting format = [{start:"",end:""},...]
self.spells = Spells(spells)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self, id, value, start="", end="", startopen=False, endopen=False):
self._attributes.append(self._graph.attributes.makeAttributeInstance("edge", id, value, start, end, startopen, endopen))
def getXML(self):
# return lxml etree element
try:
edgeXML = etree.Element("edge", id=str(self.id), source=str(self._source), target=str(self._target))
if not self.start == "":
edgeXML.set("start" if not self.startopen else "startopen", self.start)
if not self.end == "":
edgeXML.set("end" if not self.endopen else "endopen", self.end)
if not self.weight == "":
edgeXML.set("weight", str(self.weight))
if not self.label == "":
edgeXML.set("label", self.label)
# attributes
if self._attributes:
edgeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells:
#spellsXML = etree.SubElement(edgeXML, "spells")
#spellsXML.append(self.spells.getXML())
edgeXML.append(self.spells.getXML())
# COLOR on edges is supported in GEXF since 1.2
if not self.r == "" and not self.g == "" and not self.b == "":
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.2draft/viz}color")
colorXML.set("r", self.r)
colorXML.set("g", self.g)
colorXML.set("b", self.b)
return edgeXML
except Exception as e:
print(self._source + " " + self._target)
print(e)
exit()
def getAttributes(self):
attsFull = []
for att in self._attributes:
attFull = self._graph.attributes["edge"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(edges_xml, graph_obj):
for child in edges_xml:
tag = ns_clean(child.tag).lower()
if tag == "edge":
edge_xml = child
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen = False
end = ""
endopen = False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib:
attr = attr.lower()
if attr == "id":
id = edge_xml.attrib[attr]
if attr == "source":
source = edge_xml.attrib[attr]
if attr == "target":
target = edge_xml.attrib[attr]
if attr == "weight":
weight = edge_xml.attrib[attr]
if attr == "start":
start = edge_xml.attrib[attr]
if attr == "end":
end = edge_xml.attrib[attr]
if attr == "startopen":
start = edge_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = edge_xml.attrib[attr]
endopen = True
if attr == "label":
label = edge_xml.attrib[attr]
spells = []
attvalues_xml = []
for child in edge_xml:
tag = ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml.append(child)
if tag == "spells":
spells = Spells.importXML(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
edge_obj = graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end, startopen=startopen, endopen=endopen, label=label, r=r, g=g, b=b, spells=spells)
edge_obj._attributes = graph_obj.attributes.importAttributesValuesXML("edge", attvalues_xml)
# COLOR on edges is supported in GEXF since 1.2
def setColor(self, r, g, b):
self.r = r
self.g = g
self.b = b
class GexfImport:
# class coded by elie Rotenberg, médialab 20/07/2010
# deprecated : import XML codes are now included to the Gexf, Graph, Attribute, Node, Edge classes
def __init__(self, file_like):
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(file_like, parser)
gexf_xml = tree.getroot()
tag = self.ns_clean(gexf_xml.tag).lower()
if tag != "gexf":
self.msg_unexpected_tag("gexf", tag)
return
self.gexf_obj = None
for child in gexf_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "meta":
meta_xml = child
self.gexf_obj = self.extract_gexf_obj(meta_xml)
if tag == "graph":
graph_xml = child
if self.gexf_obj == None:
self.msg_unexpected_tag("meta", tag)
return
self.graph_obj = self.extract_graph_obj(graph_xml)
def ns_clean(self, token):
i = token.find('}')
return token[i + 1:]
def msg_unexpected_tag(self, expected, got):
print("Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got))
def extract_gexf_obj(self, meta_xml):
for child in meta_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "creator":
creator = child.text
if tag == "description":
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml):
type = ""
mode = ""
label = ""
timeformat = "double"
for attr in graph_xml.attrib:
attr = attr.lower()
if attr == "defaultedgetype":
type = graph_xml.attrib[attr]
if attr == "mode":
mode = graph_xml.attrib[attr]
if attr == "label":
label = graph_xml.attrib[attr]
if attr == "timeformat":
timeformat = graph_xml.attrib[attr]
self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label, timeformat=timeformat)
for child in graph_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attributes":
attributes_xml = child
self.extract_attributes(attributes_xml)
if tag == "nodes":
nodes_xml = child
self.extract_nodes(nodes_xml)
if tag == "edges":
edges_xml = child
self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml):
attr_class = None
mode = ""
for attr in attributes_xml.attrib:
attr = attr.lower()
if attr == "class":
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode":
mode = attributes_xml.attrib[attr]
for child in attributes_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attribute":
attribute_xml = child
self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode):
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib:
attr = attr.lower()
if attr == "id":
id = attribute_xml.attrib[attr]
if attr == "title":
title = attribute_xml.attrib[attr]
if attr == "type":
|
paulgirard/pygexf
|
1608b528573e778729c83830483794b9ceea7694
|
python3 fix
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index dbcd676..c11d6b8 100755
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,847 +1,847 @@
# -*- coding: utf-8 -*-
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
from lxml import etree
from datetime import date
import itertools
import traceback
# missing features :
# data validation regarding attribute types
# phylogeny
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
def msg_unexpected_tag(expected, got):
print("Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got))
def ns_clean(token):
i = token.find('}')
return token[i + 1:]
class Gexf:
def __init__(self, creator, description):
self.creator = creator
self.description = description
self.graphs = []
self.xmlns = "http://www.gephi.org/gexf/1.2draft"
self.xsi = "http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation = "http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.2draft.xsd"
self.viz = "http://www.gexf.net/1.2draft/viz"
self.version = "1.2"
def addGraph(self, type, mode, label, timeformat=""):
g = Graph(type, mode, label, timeformat)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{" + self.xmlns + "}gexf", version=self.version, nsmap={None: self.xmlns, 'viz': self.viz, 'xsi': self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation", self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified", date.today().isoformat())
etree.SubElement(meta, "creator").text = self.creator
etree.SubElement(meta, "description").text = self.description
for graph in self.graphs:
gexfXML.append(graph.getXML())
return gexfXML
def write(self, file, print_stat=True):
file.write(etree.tostring(self.getXML(), pretty_print=True, encoding='utf-8', xml_declaration=True))
if print_stat is True:
self.print_stat()
def print_stat(self):
for graph in self.graphs:
graph.print_stat()
@staticmethod
def importXML(gexf_file):
""" import gexf xml meta tags to create a Gexf Object and delegate Graph extraction to Graph class"""
# parse the gexf file
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse((gexf_file), parser)
# start create Gexf Object
gexf_xml = tree.getroot()
tag = ns_clean(gexf_xml.tag).lower()
if tag != "gexf":
msg_unexpected_tag("gexf", tag)
return
gexf_obj = None
for child in gexf_xml:
tag = ns_clean(child.tag).lower()
# create a gexf object by importing meta tag
if tag == "meta":
meta_xml = child
for child in meta_xml:
tag = ns_clean(child.tag).lower()
if tag == "creator":
creator = child.text
if tag == "description":
description = child.text
gexf_obj = Gexf(creator=creator, description=description)
# export graph xml through Graph Class
if tag == "graph":
graph_xml = child
if gexf_obj is None:
msg_unexpected_tag("meta", tag)
return
Graph.importXML(graph_xml, gexf_obj)
return gexf_obj
class Graph:
def __init__(self, type, mode, label, time_format="double", start="", end=""):
# control variable
self.authorizedType = ("directed", "undirected")
self.authorizedMode = ("dynamic", "static")
# time format
# Discrete: integer or double
# Continuous : date (yyyy-mm-dd) or dateTime
# default : double
self.authorizedTimeFormat = ("integer", "double", "date", "dateTime")
self.defaultTimeFormat = "double"
self.defaultType = "directed"
self.defaultMode = "static"
self.label = label
if type in self.authorizedType:
self.type = type
else:
self.type = self.defaultType
if mode in self.authorizedMode:
self.mode = mode
else:
self.mode = self.defaultMode
if time_format in self.authorizedTimeFormat:
self.time_format = time_format
else:
self.time_format = self.defaultTimeFormat
self.start = start
self.end = end
self._attributes = Attributes()
self.attributes = self._attributes
self._nodes = {}
self.nodes = self._nodes
self._edges = {}
self.edges = self._edges
def addNode(self, id, label, start="", end="", startopen=False, endopen=False, pid="", r="", g="", b="", spells=[]):
self._nodes[str(id)] = Node(self, id, label, start, end, pid, r, g, b, spells, startopen, endopen)
return self._nodes[str(id)]
def nodeExists(self, id):
if id in self._nodes.keys():
return 1
else:
return 0
def addEdge(self, id, source, target, weight="", start="", end="", label="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self._edges[str(id)] = Edge(self, id, source, target, weight, start, end, label, r, g, b, spells, startopen, endopen)
return self._edges[str(id)]
def addNodeAttribute(self, title, defaultValue=None, type="integer", mode="static", force_id=""):
# add to NodeAttributes
return self._attributes.declareAttribute("node", type, defaultValue, title, mode, force_id)
def addDefaultAttributesToNode(self, node):
""" deprecated """
pass
def checkNodeAttribute(self, id, value, start, end):
"""deprecated"""
pass
# check conformity with type is missing
# if id in self._nodesAttributes.keys() :
# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self, title, defaultValue, type="integer", mode="static", force_id=""):
return self._attributes.declareAttribute("edge", type, defaultValue, title, mode, force_id)
def addDefaultAttributesToEdge(self, edge):
""" deprecated """
pass
def checkEdgeAttribute(self, id, value, start, end):
"""deprecated """
pass
# # check conformity with type is missing
# if id in self._edgesAttributes.keys() :
# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self):
# return lxml etree element
graphXML = etree.Element("graph", defaultedgetype=self.type, mode=self.mode, label=self.label, timeformat=self.time_format)
for attributesElement in self.attributes.getAttributesDeclarationXML():
graphXML.append(attributesElement)
nodesXML = etree.SubElement(graphXML, "nodes")
node_ids = self._nodes.keys()
node_ids.sort()
for id in node_ids:
nodesXML.append(self._nodes[id].getXML())
edgesXML = etree.SubElement(graphXML, "edges")
edge_ids = self._edges.keys()
edge_ids.sort()
for id in edge_ids:
edgesXML.append(self._edges[id].getXML())
return graphXML
@staticmethod
def importXML(graph_xml, gexf_obj):
""" import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""
# get Graph attributes
type = ""
mode = ""
label = ""
timeformat = "double"
for attr in graph_xml.attrib:
attr = attr.lower()
if attr == "defaultedgetype":
type = graph_xml.attrib[attr]
if attr == "mode":
mode = graph_xml.attrib[attr]
if attr == "label":
label = graph_xml.attrib[attr]
if attr == "timeformat":
timeformat = graph_xml.attrib[attr]
# create and attache the graph object to the Gexf object
graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label, timeformat=timeformat)
for child in graph_xml:
tag = ns_clean(child.tag).lower()
if tag == "attributes":
attributes_xml = child
# Delegate Attributes declaration to the attribute object
graph_obj.attributes.importAttributesXML(attributes_xml)
if tag == "nodes":
nodes_xml = child
# Delegate nodes creation to the Node class
Node.importXML(nodes_xml, graph_obj)
if tag == "edges":
edges_xml = child
# Delegate edges creation to the Edge class
Edge.importXML(edges_xml, graph_obj)
def print_stat(self):
print(self.label + " " + self.type + " " + self.mode + " " + self.start + " " + self.end)
print("number of nodes : " + str(len(self._nodes)))
print("number of edges : " + str(len(self._edges)))
class Attributes(dict):
"""
attributes=
{
"node" :
{ "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },
"edge" :
{ "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },
}
"""
def __init__(self):
self.type_choices = ["integer", "string", "float", "double", "boolean", "date", "URI"]
self.attClass_choices = ["node", "edge"]
self.mode_choices = ["static", "dynamic"]
for attClass in self.attClass_choices:
self[attClass] = {}
def declareAttribute(self, attClass, type, defaultValue, title="", mode="static", id=None):
"""
add a new attribute declaration to the graph
"""
if attClass in self.attClass_choices:
# should add quality control here on type and defaultValue
# if no id given generating a numerical one based on dict length
if not id:
id = str(len(self[attClass]))
self[attClass][id] = {"id": id, "type": type, "defaultValue": defaultValue, "mode": mode, "title": title}
return id
else:
raise Exception("wrong attClass : " + str(attClass) + " Should be in " + str(type_choices))
def makeAttributeInstance(self, attClass, id=None, value=None, start=None, end=None, startopen=False, endopen=False):
"""
generate an attribute to be include to a node or edge.
copied from the declared attributes, thus any attribute has to be declared first
"""
if attClass in self.attClass_choices:
if id in self[attClass].keys():
att = {"id": id}
att["value"] = value if value else self[attClass][id]["defaultValue"]
if self[attClass][id]["mode"] == "dynamic" and start or end:
# start & end will be discarded if the mode is set to static
if start:
att["start"] = start
if startopen:
att["startopen"] = startopen
if end:
att["end"] = end
if endopen:
att["endopen"] = endopen
return att
else:
raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute" % (id, ))
else:
raise Exception("wrong attClass : " + str(attClass) + " Should be in " + str(self.type_choices))
def getAttributesDeclarationXML(self):
""" generate attributes declaration XML """
# return lxml etree element
allAttributesXML = []
if len(self) > 0:
# iter on node and then edge atts
- for attClass, atts in self.iteritems():
+ for attClass, atts in self.items():
# group by mode
key_mode = lambda att: att["mode"]
atts_sorted_by_mode = sorted(atts.values(), key=key_mode, reverse=True)
for mode, atts in itertools.groupby(atts_sorted_by_mode, key_mode):
# generate on attributes by mode
attributesXML = etree.Element("attributes")
attributesXML.set("class", attClass)
attributesXML.set("mode", mode)
# generate attribute by id order
for att in sorted(atts, key=lambda att: att["id"]):
attributeXML = etree.SubElement(attributesXML, "attribute")
attributeXML.set("id", str(att["id"]))
attributeXML.set("title", att["title"])
attributeXML.set("type", att["type"])
if att["defaultValue"]:
etree.SubElement(attributeXML, "default").text = att["defaultValue"]
allAttributesXML.append(attributesXML)
return allAttributesXML
@staticmethod
def getAttributesXML(atts):
""" get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""
if len(atts) > 0:
attValuesXML = etree.Element("attvalues")
for att in atts:
attValueXML = etree.SubElement(attValuesXML, "attvalue")
attValueXML.set("for", str(att["id"]))
attValueXML.set("value", att["value"])
if "start" in att.keys() and not att["start"] == "":
attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen", att["start"])
if "end" in att.keys() and not att["end"] == "":
attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen", att["end"])
return attValuesXML
else:
return None
def importAttributesXML(self, attributes_xml):
""" get XML attributes declaration of a graph gexf"""
attr_class = None
mode = ""
for attr in attributes_xml.attrib:
attr = attr.lower()
if attr == "class":
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode":
mode = attributes_xml.attrib[attr]
for child in attributes_xml:
tag = ns_clean(child.tag).lower()
if tag == "attribute":
attribute_xml = child
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib:
attr = attr.lower()
if attr == "id":
id = attribute_xml.attrib[attr]
if attr == "title":
title = attribute_xml.attrib[attr]
if attr == "type":
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml:
tag = ns_clean(child.tag).lower()
if tag == "default":
default = child.text
self.declareAttribute(attr_class, type, default, title, mode, id)
def importAttributesValuesXML(self, attClass, attvalues_xml):
""" import attributes values from attvalues gexf xml tag attached to nodes or edges"""
atts = []
for attvalues in attvalues_xml:
for child in attvalues:
tag = ns_clean(child.tag).lower()
if tag == "attvalue":
attvalue_xml = child
id = ""
value = ""
start = ""
startopen = False
end = ""
endopen = False
for attr in attvalue_xml.attrib:
if attr == "for":
id = attvalue_xml.attrib[attr]
if attr == "value":
value = attvalue_xml.attrib[attr]
if attr == "start":
start = attvalue_xml.attrib[attr]
if attr == "end":
end = attvalue_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
atts.append(self.makeAttributeInstance(attClass, id, value, start, end, startopen, endopen))
return atts
class Spells(list):
'''
spells are time periods
spells is a list of dictionaries
a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}
'''
def getXML(self):
spellsXML = etree.Element("spells")
for spell in self:
spellXML = etree.SubElement(spellsXML, "spell")
if "start" in spell.keys():
spellXML.set("start", spell["start"])
if "end" in spell.keys():
spellXML.set("end", spell["end"])
return spellsXML
@staticmethod
def importXML(spellsxmltree):
return Spells([spell.attrib for spell in spellsxmltree])
class Node:
def __init__(self, graph, id, label, start="", end="", pid="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self.id = id
self.label = label
self.start = start
self.startopen = startopen
self.end = end
self.endopen = endopen
self.pid = pid
self._graph = graph
self.setColor(r, g, b)
#spells expecting format = [{start:"",end:""},...]
self.spells = spells
if not self.pid == "":
if not self._graph.nodeExists(self.pid):
raise Exception("pid " + self.pid + " node unknown, add nodes to graph first")
self._attributes = []
self.attributes = self._attributes
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self, id, value, start="", end="", startopen=False, endopen=False):
self._attributes.append(self._graph.attributes.makeAttributeInstance("node", id, value, start, end, startopen, endopen))
def getXML(self):
# return lxml etree element
try:
nodeXML = etree.Element("node", id=str(self.id), label=self.label)
if not self.start == "":
nodeXML.set("start" if not self.startopen else "startopen", self.start)
if not self.end == "":
nodeXML.set("end" if not self.endopen else "endopen", self.end)
if not self.pid == "":
nodeXML.set("pid", self.pid)
# attributes
if self._attributes:
nodeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells:
print("found spells in node " + self.id)
nodeXML.append(self.spells.getXML())
if not self.r == "" and not self.g == "" and not self.b == "":
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r", self.r)
colorXML.set("g", self.g)
colorXML.set("b", self.b)
return nodeXML
except Exception as e:
print(self.label)
print(self._attributes)
print(e)
traceback.print_exc()
exit()
def getAttributes(self):
attsFull = []
for att in self._attributes:
attFull = self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(nodes_xml, graph_obj):
for child in nodes_xml:
tag = ns_clean(child.tag).lower()
if tag == "node":
node_xml = child
id = ""
label = ""
start = ""
startopen = False
end = ""
endopen = False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib:
attr = attr.lower()
if attr == "id":
id = node_xml.attrib[attr]
if attr == "label":
label = node_xml.attrib[attr]
if attr == "start":
start = node_xml.attrib[attr]
if attr == "end":
start = node_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
if attr == "pid":
pid = node_xml.attrib[attr]
attvalues_xml = []
spells = []
for child in node_xml:
tag = ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml.append(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag == "spells":
spells = Spells.importXML(child)
node_obj = graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b, spells=spells)
node_obj._attributes = graph_obj.attributes.importAttributesValuesXML("node", attvalues_xml)
def setColor(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __str__(self):
return self.label
class Edge:
def __init__(self, graph, id, source, target, weight="", start="", end="", label="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self.id = id
self._graph = graph
if self._graph.nodeExists(source):
self._source = source
self.source = self._source
else:
raise Exception("source " + source + " node unknown, add nodes to graph first")
if self._graph.nodeExists(target):
self._target = target
self.target = self._target
else:
raise Exception("target " + target + " node unknown, add nodes to graph first")
self.start = start
self.startopen = startopen
self.end = end
self.endopen = endopen
self.weight = weight
self.label = label
self._attributes = []
self.attributes = self._attributes
# COLOR on edges now supported in GEXF 1.2
self.setColor(r, g, b)
#spells expecting format = [{start:"",end:""},...]
self.spells = Spells(spells)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self, id, value, start="", end="", startopen=False, endopen=False):
self._attributes.append(self._graph.attributes.makeAttributeInstance("edge", id, value, start, end, startopen, endopen))
def getXML(self):
# return lxml etree element
try:
edgeXML = etree.Element("edge", id=str(self.id), source=str(self._source), target=str(self._target))
if not self.start == "":
edgeXML.set("start" if not self.startopen else "startopen", self.start)
if not self.end == "":
edgeXML.set("end" if not self.endopen else "endopen", self.end)
if not self.weight == "":
edgeXML.set("weight", str(self.weight))
if not self.label == "":
edgeXML.set("label", self.label)
# attributes
if self._attributes:
edgeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells:
#spellsXML = etree.SubElement(edgeXML, "spells")
#spellsXML.append(self.spells.getXML())
edgeXML.append(self.spells.getXML())
# COLOR on edges is supported in GEXF since 1.2
if not self.r == "" and not self.g == "" and not self.b == "":
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.2draft/viz}color")
colorXML.set("r", self.r)
colorXML.set("g", self.g)
colorXML.set("b", self.b)
return edgeXML
except Exception as e:
print(self._source + " " + self._target)
print(e)
exit()
def getAttributes(self):
attsFull = []
for att in self._attributes:
attFull = self._graph.attributes["edge"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(edges_xml, graph_obj):
for child in edges_xml:
tag = ns_clean(child.tag).lower()
if tag == "edge":
edge_xml = child
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen = False
end = ""
endopen = False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib:
attr = attr.lower()
if attr == "id":
id = edge_xml.attrib[attr]
if attr == "source":
source = edge_xml.attrib[attr]
if attr == "target":
target = edge_xml.attrib[attr]
if attr == "weight":
weight = edge_xml.attrib[attr]
if attr == "start":
start = edge_xml.attrib[attr]
if attr == "end":
end = edge_xml.attrib[attr]
if attr == "startopen":
start = edge_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = edge_xml.attrib[attr]
endopen = True
if attr == "label":
label = edge_xml.attrib[attr]
spells = []
attvalues_xml = []
for child in edge_xml:
tag = ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml.append(child)
if tag == "spells":
spells = Spells.importXML(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
edge_obj = graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end, startopen=startopen, endopen=endopen, label=label, r=r, g=g, b=b, spells=spells)
edge_obj._attributes = graph_obj.attributes.importAttributesValuesXML("edge", attvalues_xml)
# COLOR on edges is supported in GEXF since 1.2
def setColor(self, r, g, b):
self.r = r
self.g = g
self.b = b
class GexfImport:
# class coded by elie Rotenberg, médialab 20/07/2010
# deprecated : import XML codes are now included to the Gexf, Graph, Attribute, Node, Edge classes
def __init__(self, file_like):
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(file_like, parser)
gexf_xml = tree.getroot()
tag = self.ns_clean(gexf_xml.tag).lower()
if tag != "gexf":
self.msg_unexpected_tag("gexf", tag)
return
self.gexf_obj = None
for child in gexf_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "meta":
meta_xml = child
self.gexf_obj = self.extract_gexf_obj(meta_xml)
if tag == "graph":
graph_xml = child
if self.gexf_obj == None:
self.msg_unexpected_tag("meta", tag)
return
self.graph_obj = self.extract_graph_obj(graph_xml)
def ns_clean(self, token):
i = token.find('}')
return token[i + 1:]
def msg_unexpected_tag(self, expected, got):
print("Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got))
def extract_gexf_obj(self, meta_xml):
for child in meta_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "creator":
creator = child.text
if tag == "description":
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml):
type = ""
mode = ""
label = ""
timeformat = "double"
for attr in graph_xml.attrib:
attr = attr.lower()
if attr == "defaultedgetype":
type = graph_xml.attrib[attr]
if attr == "mode":
mode = graph_xml.attrib[attr]
if attr == "label":
label = graph_xml.attrib[attr]
if attr == "timeformat":
timeformat = graph_xml.attrib[attr]
self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label, timeformat=timeformat)
for child in graph_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attributes":
attributes_xml = child
self.extract_attributes(attributes_xml)
if tag == "nodes":
nodes_xml = child
self.extract_nodes(nodes_xml)
if tag == "edges":
edges_xml = child
self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml):
attr_class = None
mode = ""
for attr in attributes_xml.attrib:
attr = attr.lower()
if attr == "class":
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode":
mode = attributes_xml.attrib[attr]
for child in attributes_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attribute":
attribute_xml = child
self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode):
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib:
attr = attr.lower()
if attr == "id":
id = attribute_xml.attrib[attr]
|
paulgirard/pygexf
|
0ae0862ff6b2600ccb85a391c8bdc2e3e3f40891
|
more pep8/python3 fixes
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index 6eab911..dbcd676 100755
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,1049 +1,1047 @@
# -*- coding: utf-8 -*-
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
-from lxml import etree
-from datetime import date
+from lxml import etree
+from datetime import date
import itertools
import traceback
# missing features :
# data validation regarding attribute types
# phylogeny
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
def msg_unexpected_tag(expected, got):
print("Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got))
def ns_clean(token):
i = token.find('}')
return token[i + 1:]
class Gexf:
def __init__(self, creator, description):
self.creator = creator
self.description = description
self.graphs = []
self.xmlns = "http://www.gephi.org/gexf/1.2draft"
self.xsi = "http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation = "http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.2draft.xsd"
self.viz = "http://www.gexf.net/1.2draft/viz"
self.version = "1.2"
def addGraph(self, type, mode, label, timeformat=""):
g = Graph(type, mode, label, timeformat)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{" + self.xmlns + "}gexf", version=self.version, nsmap={None: self.xmlns, 'viz': self.viz, 'xsi': self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation", self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified", date.today().isoformat())
etree.SubElement(meta, "creator").text = self.creator
etree.SubElement(meta, "description").text = self.description
for graph in self.graphs:
gexfXML.append(graph.getXML())
return gexfXML
def write(self, file, print_stat=True):
file.write(etree.tostring(self.getXML(), pretty_print=True, encoding='utf-8', xml_declaration=True))
- if print_stat == True:
+ if print_stat is True:
self.print_stat()
def print_stat(self):
for graph in self.graphs:
graph.print_stat()
@staticmethod
def importXML(gexf_file):
""" import gexf xml meta tags to create a Gexf Object and delegate Graph extraction to Graph class"""
# parse the gexf file
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse((gexf_file), parser)
# start create Gexf Object
gexf_xml = tree.getroot()
tag = ns_clean(gexf_xml.tag).lower()
- if tag <> "gexf":
+ if tag != "gexf":
msg_unexpected_tag("gexf", tag)
return
gexf_obj = None
for child in gexf_xml:
tag = ns_clean(child.tag).lower()
# create a gexf object by importing meta tag
if tag == "meta":
meta_xml = child
for child in meta_xml:
tag = ns_clean(child.tag).lower()
if tag == "creator":
creator = child.text
if tag == "description":
description = child.text
gexf_obj = Gexf(creator=creator, description=description)
# export graph xml through Graph Class
if tag == "graph":
graph_xml = child
- if gexf_obj == None:
+ if gexf_obj is None:
msg_unexpected_tag("meta", tag)
return
Graph.importXML(graph_xml, gexf_obj)
return gexf_obj
class Graph:
def __init__(self, type, mode, label, time_format="double", start="", end=""):
# control variable
self.authorizedType = ("directed", "undirected")
self.authorizedMode = ("dynamic", "static")
# time format
# Discrete: integer or double
# Continuous : date (yyyy-mm-dd) or dateTime
# default : double
self.authorizedTimeFormat = ("integer", "double", "date", "dateTime")
self.defaultTimeFormat = "double"
self.defaultType = "directed"
self.defaultMode = "static"
self.label = label
if type in self.authorizedType:
self.type = type
else:
self.type = self.defaultType
if mode in self.authorizedMode:
self.mode = mode
else:
self.mode = self.defaultMode
if time_format in self.authorizedTimeFormat:
self.time_format = time_format
else:
self.time_format = self.defaultTimeFormat
self.start = start
self.end = end
self._attributes = Attributes()
self.attributes = self._attributes
self._nodes = {}
self.nodes = self._nodes
self._edges = {}
self.edges = self._edges
def addNode(self, id, label, start="", end="", startopen=False, endopen=False, pid="", r="", g="", b="", spells=[]):
self._nodes[str(id)] = Node(self, id, label, start, end, pid, r, g, b, spells, startopen, endopen)
return self._nodes[str(id)]
def nodeExists(self, id):
if id in self._nodes.keys():
return 1
else:
return 0
def addEdge(self, id, source, target, weight="", start="", end="", label="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self._edges[str(id)] = Edge(self, id, source, target, weight, start, end, label, r, g, b, spells, startopen, endopen)
return self._edges[str(id)]
def addNodeAttribute(self, title, defaultValue=None, type="integer", mode="static", force_id=""):
# add to NodeAttributes
return self._attributes.declareAttribute("node", type, defaultValue, title, mode, force_id)
def addDefaultAttributesToNode(self, node):
""" deprecated """
pass
def checkNodeAttribute(self, id, value, start, end):
"""deprecated"""
pass
# check conformity with type is missing
# if id in self._nodesAttributes.keys() :
# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self, title, defaultValue, type="integer", mode="static", force_id=""):
return self._attributes.declareAttribute("edge", type, defaultValue, title, mode, force_id)
def addDefaultAttributesToEdge(self, edge):
""" deprecated """
pass
def checkEdgeAttribute(self, id, value, start, end):
"""deprecated """
pass
# # check conformity with type is missing
# if id in self._edgesAttributes.keys() :
# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self):
# return lxml etree element
graphXML = etree.Element("graph", defaultedgetype=self.type, mode=self.mode, label=self.label, timeformat=self.time_format)
for attributesElement in self.attributes.getAttributesDeclarationXML():
graphXML.append(attributesElement)
nodesXML = etree.SubElement(graphXML, "nodes")
node_ids = self._nodes.keys()
node_ids.sort()
for id in node_ids:
nodesXML.append(self._nodes[id].getXML())
edgesXML = etree.SubElement(graphXML, "edges")
edge_ids = self._edges.keys()
edge_ids.sort()
for id in edge_ids:
edgesXML.append(self._edges[id].getXML())
return graphXML
@staticmethod
def importXML(graph_xml, gexf_obj):
""" import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""
# get Graph attributes
type = ""
mode = ""
label = ""
timeformat = "double"
for attr in graph_xml.attrib:
attr = attr.lower()
if attr == "defaultedgetype":
type = graph_xml.attrib[attr]
if attr == "mode":
mode = graph_xml.attrib[attr]
if attr == "label":
label = graph_xml.attrib[attr]
if attr == "timeformat":
timeformat = graph_xml.attrib[attr]
# create and attache the graph object to the Gexf object
graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label, timeformat=timeformat)
for child in graph_xml:
tag = ns_clean(child.tag).lower()
if tag == "attributes":
attributes_xml = child
# Delegate Attributes declaration to the attribute object
graph_obj.attributes.importAttributesXML(attributes_xml)
if tag == "nodes":
nodes_xml = child
# Delegate nodes creation to the Node class
Node.importXML(nodes_xml, graph_obj)
if tag == "edges":
edges_xml = child
# Delegate edges creation to the Edge class
Edge.importXML(edges_xml, graph_obj)
def print_stat(self):
print(self.label + " " + self.type + " " + self.mode + " " + self.start + " " + self.end)
print("number of nodes : " + str(len(self._nodes)))
print("number of edges : " + str(len(self._edges)))
class Attributes(dict):
- """
+ """
attributes=
{
"node" :
{ "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },
"edge" :
{ "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },
- }
-
-
+ }
+
+
"""
def __init__(self):
self.type_choices = ["integer", "string", "float", "double", "boolean", "date", "URI"]
self.attClass_choices = ["node", "edge"]
self.mode_choices = ["static", "dynamic"]
for attClass in self.attClass_choices:
self[attClass] = {}
def declareAttribute(self, attClass, type, defaultValue, title="", mode="static", id=None):
"""
add a new attribute declaration to the graph
"""
if attClass in self.attClass_choices:
# should add quality control here on type and defaultValue
# if no id given generating a numerical one based on dict length
if not id:
id = str(len(self[attClass]))
self[attClass][id] = {"id": id, "type": type, "defaultValue": defaultValue, "mode": mode, "title": title}
return id
else:
raise Exception("wrong attClass : " + str(attClass) + " Should be in " + str(type_choices))
def makeAttributeInstance(self, attClass, id=None, value=None, start=None, end=None, startopen=False, endopen=False):
"""
generate an attribute to be include to a node or edge.
copied from the declared attributes, thus any attribute has to be declared first
"""
if attClass in self.attClass_choices:
if id in self[attClass].keys():
att = {"id": id}
att["value"] = value if value else self[attClass][id]["defaultValue"]
if self[attClass][id]["mode"] == "dynamic" and start or end:
# start & end will be discarded if the mode is set to static
if start:
att["start"] = start
if startopen:
att["startopen"] = startopen
if end:
att["end"] = end
if endopen:
att["endopen"] = endopen
return att
else:
raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute" % (id, ))
else:
raise Exception("wrong attClass : " + str(attClass) + " Should be in " + str(self.type_choices))
def getAttributesDeclarationXML(self):
""" generate attributes declaration XML """
# return lxml etree element
allAttributesXML = []
if len(self) > 0:
# iter on node and then edge atts
for attClass, atts in self.iteritems():
# group by mode
key_mode = lambda att: att["mode"]
atts_sorted_by_mode = sorted(atts.values(), key=key_mode, reverse=True)
for mode, atts in itertools.groupby(atts_sorted_by_mode, key_mode):
# generate on attributes by mode
attributesXML = etree.Element("attributes")
attributesXML.set("class", attClass)
attributesXML.set("mode", mode)
# generate attribute by id order
for att in sorted(atts, key=lambda att: att["id"]):
attributeXML = etree.SubElement(attributesXML, "attribute")
attributeXML.set("id", str(att["id"]))
attributeXML.set("title", att["title"])
attributeXML.set("type", att["type"])
if att["defaultValue"]:
etree.SubElement(attributeXML, "default").text = att["defaultValue"]
allAttributesXML.append(attributesXML)
return allAttributesXML
@staticmethod
def getAttributesXML(atts):
""" get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""
if len(atts) > 0:
attValuesXML = etree.Element("attvalues")
for att in atts:
attValueXML = etree.SubElement(attValuesXML, "attvalue")
attValueXML.set("for", str(att["id"]))
attValueXML.set("value", att["value"])
if "start" in att.keys() and not att["start"] == "":
attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen", att["start"])
if "end" in att.keys() and not att["end"] == "":
attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen", att["end"])
return attValuesXML
else:
return None
def importAttributesXML(self, attributes_xml):
""" get XML attributes declaration of a graph gexf"""
attr_class = None
mode = ""
for attr in attributes_xml.attrib:
attr = attr.lower()
if attr == "class":
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode":
mode = attributes_xml.attrib[attr]
for child in attributes_xml:
tag = ns_clean(child.tag).lower()
if tag == "attribute":
attribute_xml = child
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib:
attr = attr.lower()
if attr == "id":
id = attribute_xml.attrib[attr]
if attr == "title":
title = attribute_xml.attrib[attr]
if attr == "type":
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml:
tag = ns_clean(child.tag).lower()
if tag == "default":
default = child.text
self.declareAttribute(attr_class, type, default, title, mode, id)
def importAttributesValuesXML(self, attClass, attvalues_xml):
""" import attributes values from attvalues gexf xml tag attached to nodes or edges"""
atts = []
for attvalues in attvalues_xml:
for child in attvalues:
tag = ns_clean(child.tag).lower()
if tag == "attvalue":
attvalue_xml = child
id = ""
value = ""
start = ""
startopen = False
end = ""
endopen = False
for attr in attvalue_xml.attrib:
if attr == "for":
id = attvalue_xml.attrib[attr]
if attr == "value":
value = attvalue_xml.attrib[attr]
if attr == "start":
start = attvalue_xml.attrib[attr]
if attr == "end":
end = attvalue_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
atts.append(self.makeAttributeInstance(attClass, id, value, start, end, startopen, endopen))
return atts
class Spells(list):
- '''
+ '''
spells are time periods
spells is a list of dictionaries
a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}
'''
def getXML(self):
spellsXML = etree.Element("spells")
for spell in self:
spellXML = etree.SubElement(spellsXML, "spell")
if "start" in spell.keys():
spellXML.set("start", spell["start"])
if "end" in spell.keys():
spellXML.set("end", spell["end"])
return spellsXML
@staticmethod
def importXML(spellsxmltree):
return Spells([spell.attrib for spell in spellsxmltree])
-
+
class Node:
def __init__(self, graph, id, label, start="", end="", pid="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self.id = id
self.label = label
self.start = start
self.startopen = startopen
self.end = end
self.endopen = endopen
self.pid = pid
self._graph = graph
self.setColor(r, g, b)
#spells expecting format = [{start:"",end:""},...]
self.spells = spells
if not self.pid == "":
if not self._graph.nodeExists(self.pid):
raise Exception("pid " + self.pid + " node unknown, add nodes to graph first")
self._attributes = []
self.attributes = self._attributes
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self, id, value, start="", end="", startopen=False, endopen=False):
self._attributes.append(self._graph.attributes.makeAttributeInstance("node", id, value, start, end, startopen, endopen))
def getXML(self):
# return lxml etree element
try:
nodeXML = etree.Element("node", id=str(self.id), label=self.label)
if not self.start == "":
nodeXML.set("start" if not self.startopen else "startopen", self.start)
if not self.end == "":
nodeXML.set("end" if not self.endopen else "endopen", self.end)
if not self.pid == "":
nodeXML.set("pid", self.pid)
# attributes
if self._attributes:
nodeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells:
print("found spells in node " + self.id)
nodeXML.append(self.spells.getXML())
-
+
if not self.r == "" and not self.g == "" and not self.b == "":
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r", self.r)
colorXML.set("g", self.g)
colorXML.set("b", self.b)
return nodeXML
except Exception as e:
print(self.label)
print(self._attributes)
print(e)
traceback.print_exc()
exit()
def getAttributes(self):
attsFull = []
for att in self._attributes:
attFull = self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(nodes_xml, graph_obj):
for child in nodes_xml:
tag = ns_clean(child.tag).lower()
if tag == "node":
node_xml = child
id = ""
label = ""
start = ""
startopen = False
end = ""
endopen = False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib:
attr = attr.lower()
if attr == "id":
id = node_xml.attrib[attr]
if attr == "label":
label = node_xml.attrib[attr]
if attr == "start":
start = node_xml.attrib[attr]
if attr == "end":
start = node_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
if attr == "pid":
pid = node_xml.attrib[attr]
attvalues_xml = []
spells = []
for child in node_xml:
tag = ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml.append(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag == "spells":
spells = Spells.importXML(child)
node_obj = graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b, spells=spells)
node_obj._attributes = graph_obj.attributes.importAttributesValuesXML("node", attvalues_xml)
def setColor(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __str__(self):
return self.label
class Edge:
def __init__(self, graph, id, source, target, weight="", start="", end="", label="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self.id = id
self._graph = graph
-
if self._graph.nodeExists(source):
self._source = source
self.source = self._source
else:
raise Exception("source " + source + " node unknown, add nodes to graph first")
if self._graph.nodeExists(target):
self._target = target
self.target = self._target
else:
raise Exception("target " + target + " node unknown, add nodes to graph first")
self.start = start
self.startopen = startopen
self.end = end
self.endopen = endopen
self.weight = weight
self.label = label
self._attributes = []
self.attributes = self._attributes
# COLOR on edges now supported in GEXF 1.2
self.setColor(r, g, b)
#spells expecting format = [{start:"",end:""},...]
self.spells = Spells(spells)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self, id, value, start="", end="", startopen=False, endopen=False):
self._attributes.append(self._graph.attributes.makeAttributeInstance("edge", id, value, start, end, startopen, endopen))
def getXML(self):
# return lxml etree element
try:
edgeXML = etree.Element("edge", id=str(self.id), source=str(self._source), target=str(self._target))
if not self.start == "":
edgeXML.set("start" if not self.startopen else "startopen", self.start)
if not self.end == "":
edgeXML.set("end" if not self.endopen else "endopen", self.end)
if not self.weight == "":
edgeXML.set("weight", str(self.weight))
if not self.label == "":
edgeXML.set("label", self.label)
# attributes
if self._attributes:
edgeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells:
#spellsXML = etree.SubElement(edgeXML, "spells")
#spellsXML.append(self.spells.getXML())
edgeXML.append(self.spells.getXML())
# COLOR on edges is supported in GEXF since 1.2
if not self.r == "" and not self.g == "" and not self.b == "":
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.2draft/viz}color")
colorXML.set("r", self.r)
colorXML.set("g", self.g)
colorXML.set("b", self.b)
return edgeXML
except Exception as e:
print(self._source + " " + self._target)
print(e)
exit()
def getAttributes(self):
attsFull = []
for att in self._attributes:
attFull = self._graph.attributes["edge"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(edges_xml, graph_obj):
for child in edges_xml:
tag = ns_clean(child.tag).lower()
if tag == "edge":
edge_xml = child
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen = False
end = ""
endopen = False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib:
attr = attr.lower()
if attr == "id":
id = edge_xml.attrib[attr]
if attr == "source":
source = edge_xml.attrib[attr]
if attr == "target":
target = edge_xml.attrib[attr]
if attr == "weight":
weight = edge_xml.attrib[attr]
if attr == "start":
start = edge_xml.attrib[attr]
if attr == "end":
end = edge_xml.attrib[attr]
if attr == "startopen":
start = edge_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = edge_xml.attrib[attr]
endopen = True
if attr == "label":
label = edge_xml.attrib[attr]
spells = []
attvalues_xml = []
for child in edge_xml:
tag = ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml.append(child)
if tag == "spells":
spells = Spells.importXML(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
edge_obj = graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end, startopen=startopen, endopen=endopen, label=label, r=r, g=g, b=b, spells=spells)
edge_obj._attributes = graph_obj.attributes.importAttributesValuesXML("edge", attvalues_xml)
# COLOR on edges is supported in GEXF since 1.2
def setColor(self, r, g, b):
self.r = r
self.g = g
self.b = b
class GexfImport:
# class coded by elie Rotenberg, médialab 20/07/2010
# deprecated : import XML codes are now included to the Gexf, Graph, Attribute, Node, Edge classes
def __init__(self, file_like):
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(file_like, parser)
gexf_xml = tree.getroot()
tag = self.ns_clean(gexf_xml.tag).lower()
- if tag <> "gexf":
+ if tag != "gexf":
self.msg_unexpected_tag("gexf", tag)
return
self.gexf_obj = None
for child in gexf_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "meta":
meta_xml = child
self.gexf_obj = self.extract_gexf_obj(meta_xml)
if tag == "graph":
graph_xml = child
if self.gexf_obj == None:
self.msg_unexpected_tag("meta", tag)
return
self.graph_obj = self.extract_graph_obj(graph_xml)
def ns_clean(self, token):
i = token.find('}')
return token[i + 1:]
def msg_unexpected_tag(self, expected, got):
print("Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got))
def extract_gexf_obj(self, meta_xml):
for child in meta_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "creator":
creator = child.text
if tag == "description":
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml):
type = ""
mode = ""
label = ""
timeformat = "double"
for attr in graph_xml.attrib:
attr = attr.lower()
if attr == "defaultedgetype":
type = graph_xml.attrib[attr]
if attr == "mode":
mode = graph_xml.attrib[attr]
if attr == "label":
label = graph_xml.attrib[attr]
if attr == "timeformat":
timeformat = graph_xml.attrib[attr]
self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label, timeformat=timeformat)
for child in graph_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attributes":
attributes_xml = child
self.extract_attributes(attributes_xml)
if tag == "nodes":
nodes_xml = child
self.extract_nodes(nodes_xml)
if tag == "edges":
edges_xml = child
self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml):
attr_class = None
mode = ""
for attr in attributes_xml.attrib:
attr = attr.lower()
if attr == "class":
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode":
mode = attributes_xml.attrib[attr]
for child in attributes_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attribute":
attribute_xml = child
self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode):
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib:
attr = attr.lower()
if attr == "id":
id = attribute_xml.attrib[attr]
if attr == "title":
title = attribute_xml.attrib[attr]
if attr == "type":
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "default":
default = child.text
-
if attr_class == "node":
self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)
if attr_class == "edge":
self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)
def extract_nodes(self, nodes_xml):
for child in nodes_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "node":
node_xml = child
self.extract_node(node_xml)
def extract_node(self, node_xml):
id = ""
label = ""
start = ""
startopen = False
end = ""
endopen = False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib:
attr = attr.lower()
if attr == "id":
id = node_xml.attrib[attr]
if attr == "label":
label = node_xml.attrib[attr]
if attr == "start":
start = node_xml.attrib[attr]
if attr == "end":
start = node_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
if attr == "pid":
pid = node_xml.attrib[attr]
attvalues_xmls = []
spells = []
for child in node_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xmls.append(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag == "spells":
spells = [spell.attrib for spell in child]
self.node_obj = self.graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b, spells=spells)
for attvalues_xml in attvalues_xmls:
self.extract_node_attvalues(attvalues_xml)
def extract_node_attvalues(self, attvalues_xml):
for child in attvalues_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue":
attvalue_xml = child
self.extract_node_attvalue(attvalue_xml)
def extract_node_attvalue(self, attvalue_xml):
id = ""
value = ""
start = ""
startopen = False
end = ""
endopen = False
for attr in attvalue_xml.attrib:
attr = attr.lower()
if attr == "for":
id = attvalue_xml.attrib[attr]
if attr == "value":
value = attvalue_xml.attrib[attr]
if attr == "start":
start = attvalue_xml.attrib[attr]
if attr == "end":
end = attvalue_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
self.node_obj.addAttribute(id=id, value=value, start=start, end=end, startopen=startopen, endopen=endopen)
def extract_edges(self, edges_xml):
for child in edges_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "edge":
edge_xml = child
self.extract_edge(edge_xml)
def extract_edge(self, edge_xml):
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen = False
end = ""
endopen = False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib:
attr = attr.lower()
if attr == "id":
id = edge_xml.attrib[attr]
if attr == "source":
source = edge_xml.attrib[attr]
if attr == "target":
target = edge_xml.attrib[attr]
if attr == "weight":
weight = edge_xml.attrib[attr]
if attr == "start":
start = edge_xml.attrib[attr]
if attr == "end":
end = edge_xml.attrib[attr]
if attr == "startopen":
start = edge_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = edge_xml.attrib[attr]
endopen = True
if attr == "label":
label = edge_xml.attrib[attr]
spells = []
attvalues_xml = []
for child in edge_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml = child
if tag == "spells":
spells = [spell.attrib for spell in child]
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
self.edge_obj = self.graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end, startopen=startopen, endopen=endopen, label=label, r=r, g=g, b=b, spells=spells)
self.extract_edge_attvalues(attvalues_xml)
def extract_edge_attvalues(self, attvalues_xml):
for child in attvalues_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue":
attvalue_xml = child
self.extract_edge_attvalue(attvalue_xml)
# def addAttribute(self,id,value,start="",end="") :
def extract_edge_attvalue(self, attvalue_xml):
id = ""
value = ""
start = ""
startopen = True
end = ""
endopen = True
for attr in attvalue_xml.attrib:
if attr == "for":
id = attvalue_xml.attrib[attr]
if attr == "value":
value = attvalue_xml.attrib[attr]
if attr == "start":
start = attvalue_xml.attrib[attr]
if attr == "end":
end = attvalue_xml.attrib[attr]
if attr == "startopen":
startopen = attvalue_xml.attrib[attr]
if attr == "endopen":
endopen = attvalue_xml.attrib[attr]
self.edge_obj.addAttribute(id=id, value=value, start=start, end=end, startopen=startopen, endopen=endopen)
def gexf(self):
return self.gexf_obj
|
paulgirard/pygexf
|
77cc1523162c52aef37ea0c81f5d2e30be59ff04
|
more python3 fixes
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index d02d95f..6eab911 100755
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,1049 +1,1049 @@
# -*- coding: utf-8 -*-
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
from lxml import etree
from datetime import date
import itertools
import traceback
# missing features :
# data validation regarding attribute types
# phylogeny
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
def msg_unexpected_tag(expected, got):
- print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
+ print("Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got))
def ns_clean(token):
i = token.find('}')
return token[i + 1:]
class Gexf:
def __init__(self, creator, description):
self.creator = creator
self.description = description
self.graphs = []
self.xmlns = "http://www.gephi.org/gexf/1.2draft"
self.xsi = "http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation = "http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.2draft.xsd"
self.viz = "http://www.gexf.net/1.2draft/viz"
self.version = "1.2"
def addGraph(self, type, mode, label, timeformat=""):
g = Graph(type, mode, label, timeformat)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{" + self.xmlns + "}gexf", version=self.version, nsmap={None: self.xmlns, 'viz': self.viz, 'xsi': self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation", self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified", date.today().isoformat())
etree.SubElement(meta, "creator").text = self.creator
etree.SubElement(meta, "description").text = self.description
for graph in self.graphs:
gexfXML.append(graph.getXML())
return gexfXML
def write(self, file, print_stat=True):
file.write(etree.tostring(self.getXML(), pretty_print=True, encoding='utf-8', xml_declaration=True))
if print_stat == True:
self.print_stat()
def print_stat(self):
for graph in self.graphs:
graph.print_stat()
@staticmethod
def importXML(gexf_file):
""" import gexf xml meta tags to create a Gexf Object and delegate Graph extraction to Graph class"""
# parse the gexf file
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse((gexf_file), parser)
# start create Gexf Object
gexf_xml = tree.getroot()
tag = ns_clean(gexf_xml.tag).lower()
if tag <> "gexf":
msg_unexpected_tag("gexf", tag)
return
gexf_obj = None
for child in gexf_xml:
tag = ns_clean(child.tag).lower()
# create a gexf object by importing meta tag
if tag == "meta":
meta_xml = child
for child in meta_xml:
tag = ns_clean(child.tag).lower()
if tag == "creator":
creator = child.text
if tag == "description":
description = child.text
gexf_obj = Gexf(creator=creator, description=description)
# export graph xml through Graph Class
if tag == "graph":
graph_xml = child
if gexf_obj == None:
msg_unexpected_tag("meta", tag)
return
Graph.importXML(graph_xml, gexf_obj)
return gexf_obj
class Graph:
def __init__(self, type, mode, label, time_format="double", start="", end=""):
# control variable
self.authorizedType = ("directed", "undirected")
self.authorizedMode = ("dynamic", "static")
# time format
# Discrete: integer or double
# Continuous : date (yyyy-mm-dd) or dateTime
# default : double
self.authorizedTimeFormat = ("integer", "double", "date", "dateTime")
self.defaultTimeFormat = "double"
self.defaultType = "directed"
self.defaultMode = "static"
self.label = label
if type in self.authorizedType:
self.type = type
else:
self.type = self.defaultType
if mode in self.authorizedMode:
self.mode = mode
else:
self.mode = self.defaultMode
if time_format in self.authorizedTimeFormat:
self.time_format = time_format
else:
self.time_format = self.defaultTimeFormat
self.start = start
self.end = end
self._attributes = Attributes()
self.attributes = self._attributes
self._nodes = {}
self.nodes = self._nodes
self._edges = {}
self.edges = self._edges
def addNode(self, id, label, start="", end="", startopen=False, endopen=False, pid="", r="", g="", b="", spells=[]):
self._nodes[str(id)] = Node(self, id, label, start, end, pid, r, g, b, spells, startopen, endopen)
return self._nodes[str(id)]
def nodeExists(self, id):
if id in self._nodes.keys():
return 1
else:
return 0
def addEdge(self, id, source, target, weight="", start="", end="", label="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self._edges[str(id)] = Edge(self, id, source, target, weight, start, end, label, r, g, b, spells, startopen, endopen)
return self._edges[str(id)]
def addNodeAttribute(self, title, defaultValue=None, type="integer", mode="static", force_id=""):
# add to NodeAttributes
return self._attributes.declareAttribute("node", type, defaultValue, title, mode, force_id)
def addDefaultAttributesToNode(self, node):
""" deprecated """
pass
def checkNodeAttribute(self, id, value, start, end):
"""deprecated"""
pass
# check conformity with type is missing
# if id in self._nodesAttributes.keys() :
# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self, title, defaultValue, type="integer", mode="static", force_id=""):
return self._attributes.declareAttribute("edge", type, defaultValue, title, mode, force_id)
def addDefaultAttributesToEdge(self, edge):
""" deprecated """
pass
def checkEdgeAttribute(self, id, value, start, end):
"""deprecated """
pass
# # check conformity with type is missing
# if id in self._edgesAttributes.keys() :
# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self):
# return lxml etree element
graphXML = etree.Element("graph", defaultedgetype=self.type, mode=self.mode, label=self.label, timeformat=self.time_format)
for attributesElement in self.attributes.getAttributesDeclarationXML():
graphXML.append(attributesElement)
nodesXML = etree.SubElement(graphXML, "nodes")
node_ids = self._nodes.keys()
node_ids.sort()
for id in node_ids:
nodesXML.append(self._nodes[id].getXML())
edgesXML = etree.SubElement(graphXML, "edges")
edge_ids = self._edges.keys()
edge_ids.sort()
for id in edge_ids:
edgesXML.append(self._edges[id].getXML())
return graphXML
@staticmethod
def importXML(graph_xml, gexf_obj):
""" import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""
# get Graph attributes
type = ""
mode = ""
label = ""
timeformat = "double"
for attr in graph_xml.attrib:
attr = attr.lower()
if attr == "defaultedgetype":
type = graph_xml.attrib[attr]
if attr == "mode":
mode = graph_xml.attrib[attr]
if attr == "label":
label = graph_xml.attrib[attr]
if attr == "timeformat":
timeformat = graph_xml.attrib[attr]
# create and attache the graph object to the Gexf object
graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label, timeformat=timeformat)
for child in graph_xml:
tag = ns_clean(child.tag).lower()
if tag == "attributes":
attributes_xml = child
# Delegate Attributes declaration to the attribute object
graph_obj.attributes.importAttributesXML(attributes_xml)
if tag == "nodes":
nodes_xml = child
# Delegate nodes creation to the Node class
Node.importXML(nodes_xml, graph_obj)
if tag == "edges":
edges_xml = child
# Delegate edges creation to the Edge class
Edge.importXML(edges_xml, graph_obj)
def print_stat(self):
- print self.label + " " + self.type + " " + self.mode + " " + self.start + " " + self.end
- print "number of nodes : " + str(len(self._nodes))
- print "number of edges : " + str(len(self._edges))
+ print(self.label + " " + self.type + " " + self.mode + " " + self.start + " " + self.end)
+ print("number of nodes : " + str(len(self._nodes)))
+ print("number of edges : " + str(len(self._edges)))
class Attributes(dict):
"""
attributes=
{
"node" :
{ "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },
"edge" :
{ "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },
}
"""
def __init__(self):
self.type_choices = ["integer", "string", "float", "double", "boolean", "date", "URI"]
self.attClass_choices = ["node", "edge"]
self.mode_choices = ["static", "dynamic"]
for attClass in self.attClass_choices:
self[attClass] = {}
def declareAttribute(self, attClass, type, defaultValue, title="", mode="static", id=None):
"""
add a new attribute declaration to the graph
"""
if attClass in self.attClass_choices:
# should add quality control here on type and defaultValue
# if no id given generating a numerical one based on dict length
if not id:
id = str(len(self[attClass]))
self[attClass][id] = {"id": id, "type": type, "defaultValue": defaultValue, "mode": mode, "title": title}
return id
else:
raise Exception("wrong attClass : " + str(attClass) + " Should be in " + str(type_choices))
def makeAttributeInstance(self, attClass, id=None, value=None, start=None, end=None, startopen=False, endopen=False):
"""
generate an attribute to be include to a node or edge.
copied from the declared attributes, thus any attribute has to be declared first
"""
if attClass in self.attClass_choices:
if id in self[attClass].keys():
att = {"id": id}
att["value"] = value if value else self[attClass][id]["defaultValue"]
if self[attClass][id]["mode"] == "dynamic" and start or end:
# start & end will be discarded if the mode is set to static
if start:
att["start"] = start
if startopen:
att["startopen"] = startopen
if end:
att["end"] = end
if endopen:
att["endopen"] = endopen
return att
else:
raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute" % (id, ))
else:
raise Exception("wrong attClass : " + str(attClass) + " Should be in " + str(self.type_choices))
def getAttributesDeclarationXML(self):
""" generate attributes declaration XML """
# return lxml etree element
allAttributesXML = []
if len(self) > 0:
# iter on node and then edge atts
for attClass, atts in self.iteritems():
# group by mode
key_mode = lambda att: att["mode"]
atts_sorted_by_mode = sorted(atts.values(), key=key_mode, reverse=True)
for mode, atts in itertools.groupby(atts_sorted_by_mode, key_mode):
# generate on attributes by mode
attributesXML = etree.Element("attributes")
attributesXML.set("class", attClass)
attributesXML.set("mode", mode)
# generate attribute by id order
for att in sorted(atts, key=lambda att: att["id"]):
attributeXML = etree.SubElement(attributesXML, "attribute")
attributeXML.set("id", str(att["id"]))
attributeXML.set("title", att["title"])
attributeXML.set("type", att["type"])
if att["defaultValue"]:
etree.SubElement(attributeXML, "default").text = att["defaultValue"]
allAttributesXML.append(attributesXML)
return allAttributesXML
@staticmethod
def getAttributesXML(atts):
""" get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""
if len(atts) > 0:
attValuesXML = etree.Element("attvalues")
for att in atts:
attValueXML = etree.SubElement(attValuesXML, "attvalue")
attValueXML.set("for", str(att["id"]))
attValueXML.set("value", att["value"])
if "start" in att.keys() and not att["start"] == "":
attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen", att["start"])
if "end" in att.keys() and not att["end"] == "":
attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen", att["end"])
return attValuesXML
else:
return None
def importAttributesXML(self, attributes_xml):
""" get XML attributes declaration of a graph gexf"""
attr_class = None
mode = ""
for attr in attributes_xml.attrib:
attr = attr.lower()
if attr == "class":
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode":
mode = attributes_xml.attrib[attr]
for child in attributes_xml:
tag = ns_clean(child.tag).lower()
if tag == "attribute":
attribute_xml = child
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib:
attr = attr.lower()
if attr == "id":
id = attribute_xml.attrib[attr]
if attr == "title":
title = attribute_xml.attrib[attr]
if attr == "type":
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml:
tag = ns_clean(child.tag).lower()
if tag == "default":
default = child.text
self.declareAttribute(attr_class, type, default, title, mode, id)
def importAttributesValuesXML(self, attClass, attvalues_xml):
""" import attributes values from attvalues gexf xml tag attached to nodes or edges"""
atts = []
for attvalues in attvalues_xml:
for child in attvalues:
tag = ns_clean(child.tag).lower()
if tag == "attvalue":
attvalue_xml = child
id = ""
value = ""
start = ""
startopen = False
end = ""
endopen = False
for attr in attvalue_xml.attrib:
if attr == "for":
id = attvalue_xml.attrib[attr]
if attr == "value":
value = attvalue_xml.attrib[attr]
if attr == "start":
start = attvalue_xml.attrib[attr]
if attr == "end":
end = attvalue_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
atts.append(self.makeAttributeInstance(attClass, id, value, start, end, startopen, endopen))
return atts
class Spells(list):
'''
spells are time periods
spells is a list of dictionaries
a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}
'''
def getXML(self):
spellsXML = etree.Element("spells")
for spell in self:
spellXML = etree.SubElement(spellsXML, "spell")
if "start" in spell.keys():
spellXML.set("start", spell["start"])
if "end" in spell.keys():
spellXML.set("end", spell["end"])
return spellsXML
@staticmethod
def importXML(spellsxmltree):
return Spells([spell.attrib for spell in spellsxmltree])
class Node:
def __init__(self, graph, id, label, start="", end="", pid="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self.id = id
self.label = label
self.start = start
self.startopen = startopen
self.end = end
self.endopen = endopen
self.pid = pid
self._graph = graph
self.setColor(r, g, b)
#spells expecting format = [{start:"",end:""},...]
self.spells = spells
if not self.pid == "":
if not self._graph.nodeExists(self.pid):
raise Exception("pid " + self.pid + " node unknown, add nodes to graph first")
self._attributes = []
self.attributes = self._attributes
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self, id, value, start="", end="", startopen=False, endopen=False):
self._attributes.append(self._graph.attributes.makeAttributeInstance("node", id, value, start, end, startopen, endopen))
def getXML(self):
# return lxml etree element
try:
nodeXML = etree.Element("node", id=str(self.id), label=self.label)
if not self.start == "":
nodeXML.set("start" if not self.startopen else "startopen", self.start)
if not self.end == "":
nodeXML.set("end" if not self.endopen else "endopen", self.end)
if not self.pid == "":
nodeXML.set("pid", self.pid)
# attributes
if self._attributes:
nodeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells:
- print "found spells in node " + self.id
+ print("found spells in node " + self.id)
nodeXML.append(self.spells.getXML())
if not self.r == "" and not self.g == "" and not self.b == "":
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r", self.r)
colorXML.set("g", self.g)
colorXML.set("b", self.b)
return nodeXML
- except Exception, e:
- print self.label
- print self._attributes
- print e
+ except Exception as e:
+ print(self.label)
+ print(self._attributes)
+ print(e)
traceback.print_exc()
exit()
def getAttributes(self):
attsFull = []
for att in self._attributes:
attFull = self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(nodes_xml, graph_obj):
for child in nodes_xml:
tag = ns_clean(child.tag).lower()
if tag == "node":
node_xml = child
id = ""
label = ""
start = ""
startopen = False
end = ""
endopen = False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib:
attr = attr.lower()
if attr == "id":
id = node_xml.attrib[attr]
if attr == "label":
label = node_xml.attrib[attr]
if attr == "start":
start = node_xml.attrib[attr]
if attr == "end":
start = node_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
if attr == "pid":
pid = node_xml.attrib[attr]
attvalues_xml = []
spells = []
for child in node_xml:
tag = ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml.append(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag == "spells":
spells = Spells.importXML(child)
node_obj = graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b, spells=spells)
node_obj._attributes = graph_obj.attributes.importAttributesValuesXML("node", attvalues_xml)
def setColor(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __str__(self):
return self.label
class Edge:
def __init__(self, graph, id, source, target, weight="", start="", end="", label="", r="", g="", b="", spells=[], startopen=False, endopen=False):
self.id = id
self._graph = graph
if self._graph.nodeExists(source):
self._source = source
self.source = self._source
else:
raise Exception("source " + source + " node unknown, add nodes to graph first")
if self._graph.nodeExists(target):
self._target = target
self.target = self._target
else:
raise Exception("target " + target + " node unknown, add nodes to graph first")
self.start = start
self.startopen = startopen
self.end = end
self.endopen = endopen
self.weight = weight
self.label = label
self._attributes = []
self.attributes = self._attributes
# COLOR on edges now supported in GEXF 1.2
self.setColor(r, g, b)
#spells expecting format = [{start:"",end:""},...]
self.spells = Spells(spells)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self, id, value, start="", end="", startopen=False, endopen=False):
self._attributes.append(self._graph.attributes.makeAttributeInstance("edge", id, value, start, end, startopen, endopen))
def getXML(self):
# return lxml etree element
try:
edgeXML = etree.Element("edge", id=str(self.id), source=str(self._source), target=str(self._target))
if not self.start == "":
edgeXML.set("start" if not self.startopen else "startopen", self.start)
if not self.end == "":
edgeXML.set("end" if not self.endopen else "endopen", self.end)
if not self.weight == "":
edgeXML.set("weight", str(self.weight))
if not self.label == "":
edgeXML.set("label", self.label)
# attributes
if self._attributes:
edgeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells:
#spellsXML = etree.SubElement(edgeXML, "spells")
#spellsXML.append(self.spells.getXML())
edgeXML.append(self.spells.getXML())
# COLOR on edges is supported in GEXF since 1.2
if not self.r == "" and not self.g == "" and not self.b == "":
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.2draft/viz}color")
colorXML.set("r", self.r)
colorXML.set("g", self.g)
colorXML.set("b", self.b)
return edgeXML
- except Exception, e:
- print self._source + " " + self._target
- print e
+ except Exception as e:
+ print(self._source + " " + self._target)
+ print(e)
exit()
def getAttributes(self):
attsFull = []
for att in self._attributes:
attFull = self._graph.attributes["edge"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(edges_xml, graph_obj):
for child in edges_xml:
tag = ns_clean(child.tag).lower()
if tag == "edge":
edge_xml = child
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen = False
end = ""
endopen = False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib:
attr = attr.lower()
if attr == "id":
id = edge_xml.attrib[attr]
if attr == "source":
source = edge_xml.attrib[attr]
if attr == "target":
target = edge_xml.attrib[attr]
if attr == "weight":
weight = edge_xml.attrib[attr]
if attr == "start":
start = edge_xml.attrib[attr]
if attr == "end":
end = edge_xml.attrib[attr]
if attr == "startopen":
start = edge_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = edge_xml.attrib[attr]
endopen = True
if attr == "label":
label = edge_xml.attrib[attr]
spells = []
attvalues_xml = []
for child in edge_xml:
tag = ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml.append(child)
if tag == "spells":
spells = Spells.importXML(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
edge_obj = graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end, startopen=startopen, endopen=endopen, label=label, r=r, g=g, b=b, spells=spells)
edge_obj._attributes = graph_obj.attributes.importAttributesValuesXML("edge", attvalues_xml)
# COLOR on edges is supported in GEXF since 1.2
def setColor(self, r, g, b):
self.r = r
self.g = g
self.b = b
class GexfImport:
# class coded by elie Rotenberg, médialab 20/07/2010
# deprecated : import XML codes are now included to the Gexf, Graph, Attribute, Node, Edge classes
def __init__(self, file_like):
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(file_like, parser)
gexf_xml = tree.getroot()
tag = self.ns_clean(gexf_xml.tag).lower()
if tag <> "gexf":
self.msg_unexpected_tag("gexf", tag)
return
self.gexf_obj = None
for child in gexf_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "meta":
meta_xml = child
self.gexf_obj = self.extract_gexf_obj(meta_xml)
if tag == "graph":
graph_xml = child
if self.gexf_obj == None:
self.msg_unexpected_tag("meta", tag)
return
self.graph_obj = self.extract_graph_obj(graph_xml)
def ns_clean(self, token):
i = token.find('}')
return token[i + 1:]
def msg_unexpected_tag(self, expected, got):
- print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
+ print("Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got))
def extract_gexf_obj(self, meta_xml):
for child in meta_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "creator":
creator = child.text
if tag == "description":
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml):
type = ""
mode = ""
label = ""
timeformat = "double"
for attr in graph_xml.attrib:
attr = attr.lower()
if attr == "defaultedgetype":
type = graph_xml.attrib[attr]
if attr == "mode":
mode = graph_xml.attrib[attr]
if attr == "label":
label = graph_xml.attrib[attr]
if attr == "timeformat":
timeformat = graph_xml.attrib[attr]
self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label, timeformat=timeformat)
for child in graph_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attributes":
attributes_xml = child
self.extract_attributes(attributes_xml)
if tag == "nodes":
nodes_xml = child
self.extract_nodes(nodes_xml)
if tag == "edges":
edges_xml = child
self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml):
attr_class = None
mode = ""
for attr in attributes_xml.attrib:
attr = attr.lower()
if attr == "class":
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode":
mode = attributes_xml.attrib[attr]
for child in attributes_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attribute":
attribute_xml = child
self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode):
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib:
attr = attr.lower()
if attr == "id":
id = attribute_xml.attrib[attr]
if attr == "title":
title = attribute_xml.attrib[attr]
if attr == "type":
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "default":
default = child.text
if attr_class == "node":
self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)
if attr_class == "edge":
self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)
def extract_nodes(self, nodes_xml):
for child in nodes_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "node":
node_xml = child
self.extract_node(node_xml)
def extract_node(self, node_xml):
id = ""
label = ""
start = ""
startopen = False
end = ""
endopen = False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib:
attr = attr.lower()
if attr == "id":
id = node_xml.attrib[attr]
if attr == "label":
label = node_xml.attrib[attr]
if attr == "start":
start = node_xml.attrib[attr]
if attr == "end":
start = node_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
if attr == "pid":
pid = node_xml.attrib[attr]
attvalues_xmls = []
spells = []
for child in node_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xmls.append(child)
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag == "spells":
spells = [spell.attrib for spell in child]
self.node_obj = self.graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b, spells=spells)
for attvalues_xml in attvalues_xmls:
self.extract_node_attvalues(attvalues_xml)
def extract_node_attvalues(self, attvalues_xml):
for child in attvalues_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue":
attvalue_xml = child
self.extract_node_attvalue(attvalue_xml)
def extract_node_attvalue(self, attvalue_xml):
id = ""
value = ""
start = ""
startopen = False
end = ""
endopen = False
for attr in attvalue_xml.attrib:
attr = attr.lower()
if attr == "for":
id = attvalue_xml.attrib[attr]
if attr == "value":
value = attvalue_xml.attrib[attr]
if attr == "start":
start = attvalue_xml.attrib[attr]
if attr == "end":
end = attvalue_xml.attrib[attr]
if attr == "startopen":
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = attvalue_xml.attrib[attr]
endopen = True
self.node_obj.addAttribute(id=id, value=value, start=start, end=end, startopen=startopen, endopen=endopen)
def extract_edges(self, edges_xml):
for child in edges_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "edge":
edge_xml = child
self.extract_edge(edge_xml)
def extract_edge(self, edge_xml):
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen = False
end = ""
endopen = False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib:
attr = attr.lower()
if attr == "id":
id = edge_xml.attrib[attr]
if attr == "source":
source = edge_xml.attrib[attr]
if attr == "target":
target = edge_xml.attrib[attr]
if attr == "weight":
weight = edge_xml.attrib[attr]
if attr == "start":
start = edge_xml.attrib[attr]
if attr == "end":
end = edge_xml.attrib[attr]
if attr == "startopen":
start = edge_xml.attrib[attr]
startopen = True
if attr == "endopen":
end = edge_xml.attrib[attr]
endopen = True
if attr == "label":
label = edge_xml.attrib[attr]
spells = []
attvalues_xml = []
for child in edge_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues":
attvalues_xml = child
if tag == "spells":
spells = [spell.attrib for spell in child]
if tag == "viz:color":
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
self.edge_obj = self.graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end, startopen=startopen, endopen=endopen, label=label, r=r, g=g, b=b, spells=spells)
self.extract_edge_attvalues(attvalues_xml)
def extract_edge_attvalues(self, attvalues_xml):
for child in attvalues_xml:
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue":
attvalue_xml = child
self.extract_edge_attvalue(attvalue_xml)
# def addAttribute(self,id,value,start="",end="") :
def extract_edge_attvalue(self, attvalue_xml):
id = ""
value = ""
start = ""
startopen = True
end = ""
endopen = True
for attr in attvalue_xml.attrib:
if attr == "for":
id = attvalue_xml.attrib[attr]
if attr == "value":
value = attvalue_xml.attrib[attr]
if attr == "start":
start = attvalue_xml.attrib[attr]
if attr == "end":
end = attvalue_xml.attrib[attr]
if attr == "startopen":
startopen = attvalue_xml.attrib[attr]
if attr == "endopen":
endopen = attvalue_xml.attrib[attr]
self.edge_obj.addAttribute(id=id, value=value, start=start, end=end, startopen=startopen, endopen=endopen)
def gexf(self):
return self.gexf_obj
|
paulgirard/pygexf
|
3595ad68753dc59ed8c763aa5c388ace90b50725
|
make it working with python3
|
diff --git a/gexf/__init__.py b/gexf/__init__.py
index 99603ef..14e4841 100644
--- a/gexf/__init__.py
+++ b/gexf/__init__.py
@@ -1,5 +1,5 @@
-from _gexf import Gexf
-from _gexf import Node
-from _gexf import Edge
-from _gexf import Graph
-from _gexf import GexfImport
\ No newline at end of file
+from ._gexf import Gexf
+from ._gexf import Node
+from ._gexf import Edge
+from ._gexf import Graph
+from ._gexf import GexfImport
|
paulgirard/pygexf
|
ac0f51afdc4e304fdd949c7c63ad5d1f96cba326
|
licences
|
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..315e7dd
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,21 @@
+Copyright médialab SciencesPo (2013)
+<[email protected]>
+
+This program is free software distributed under the terms of two licenses, the
+CeCILL-C license that fits European law, and the GNU Lesser General Public
+License. You can use, modify and/ or redistribute the software under the terms
+of the CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
+URL <http://www.cecill.info> or under the terms of the GNU LGPL as published by
+the Free Software Foundation, either version 3 of the License, or (at your
+option) any later version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+The fact that you are presently reading this means that you have had
+knowledge of the CeCILL-C and LGPL licenses and that you accept their terms.
+
diff --git a/LICENSE.CECILL-C b/LICENSE.CECILL-C
new file mode 100644
index 0000000..3d2a819
--- /dev/null
+++ b/LICENSE.CECILL-C
@@ -0,0 +1,517 @@
+
+CeCILL-C FREE SOFTWARE LICENSE AGREEMENT
+
+
+ Notice
+
+This Agreement is a Free Software license agreement that is the result
+of discussions between its authors in order to ensure compliance with
+the two main principles guiding its drafting:
+
+ * firstly, compliance with the principles governing the distribution
+ of Free Software: access to source code, broad rights granted to
+ users,
+ * secondly, the election of a governing law, French law, with which
+ it is conformant, both as regards the law of torts and
+ intellectual property law, and the protection that it offers to
+ both authors and holders of the economic rights over software.
+
+The authors of the CeCILL-C (for Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre])
+license are:
+
+Commissariat à l'Energie Atomique - CEA, a public scientific, technical
+and industrial research establishment, having its principal place of
+business at 25 rue Leblanc, immeuble Le Ponant D, 75015 Paris, France.
+
+Centre National de la Recherche Scientifique - CNRS, a public scientific
+and technological establishment, having its principal place of business
+at 3 rue Michel-Ange, 75794 Paris cedex 16, France.
+
+Institut National de Recherche en Informatique et en Automatique -
+INRIA, a public scientific and technological establishment, having its
+principal place of business at Domaine de Voluceau, Rocquencourt, BP
+105, 78153 Le Chesnay cedex, France.
+
+
+ Preamble
+
+The purpose of this Free Software license agreement is to grant users
+the right to modify and re-use the software governed by this license.
+
+The exercising of this right is conditional upon the obligation to make
+available to the community the modifications made to the source code of
+the software so as to contribute to its evolution.
+
+In consideration of access to the source code and the rights to copy,
+modify and redistribute granted by the license, users are provided only
+with a limited warranty and the software's author, the holder of the
+economic rights, and the successive licensors only have limited liability.
+
+In this respect, the risks associated with loading, using, modifying
+and/or developing or reproducing the software by the user are brought to
+the user's attention, given its Free Software status, which may make it
+complicated to use, with the result that its use is reserved for
+developers and experienced professionals having in-depth computer
+knowledge. Users are therefore encouraged to load and test the
+suitability of the software as regards their requirements in conditions
+enabling the security of their systems and/or data to be ensured and,
+more generally, to use and operate it in the same conditions of
+security. This Agreement may be freely reproduced and published,
+provided it is not altered, and that no provisions are either added or
+removed herefrom.
+
+This Agreement may apply to any or all software for which the holder of
+the economic rights decides to submit the use thereof to its provisions.
+
+
+ Article 1 - DEFINITIONS
+
+For the purpose of this Agreement, when the following expressions
+commence with a capital letter, they shall have the following meaning:
+
+Agreement: means this license agreement, and its possible subsequent
+versions and annexes.
+
+Software: means the software in its Object Code and/or Source Code form
+and, where applicable, its documentation, "as is" when the Licensee
+accepts the Agreement.
+
+Initial Software: means the Software in its Source Code and possibly its
+Object Code form and, where applicable, its documentation, "as is" when
+it is first distributed under the terms and conditions of the Agreement.
+
+Modified Software: means the Software modified by at least one
+Integrated Contribution.
+
+Source Code: means all the Software's instructions and program lines to
+which access is required so as to modify the Software.
+
+Object Code: means the binary files originating from the compilation of
+the Source Code.
+
+Holder: means the holder(s) of the economic rights over the Initial
+Software.
+
+Licensee: means the Software user(s) having accepted the Agreement.
+
+Contributor: means a Licensee having made at least one Integrated
+Contribution.
+
+Licensor: means the Holder, or any other individual or legal entity, who
+distributes the Software under the Agreement.
+
+Integrated Contribution: means any or all modifications, corrections,
+translations, adaptations and/or new functions integrated into the
+Source Code by any or all Contributors.
+
+Related Module: means a set of sources files including their
+documentation that, without modification to the Source Code, enables
+supplementary functions or services in addition to those offered by the
+Software.
+
+Derivative Software: means any combination of the Software, modified or
+not, and of a Related Module.
+
+Parties: mean both the Licensee and the Licensor.
+
+These expressions may be used both in singular and plural form.
+
+
+ Article 2 - PURPOSE
+
+The purpose of the Agreement is the grant by the Licensor to the
+Licensee of a non-exclusive, transferable and worldwide license for the
+Software as set forth in Article 5 hereinafter for the whole term of the
+protection granted by the rights over said Software.
+
+
+ Article 3 - ACCEPTANCE
+
+3.1 The Licensee shall be deemed as having accepted the terms and
+conditions of this Agreement upon the occurrence of the first of the
+following events:
+
+ * (i) loading the Software by any or all means, notably, by
+ downloading from a remote server, or by loading from a physical
+ medium;
+ * (ii) the first time the Licensee exercises any of the rights
+ granted hereunder.
+
+3.2 One copy of the Agreement, containing a notice relating to the
+characteristics of the Software, to the limited warranty, and to the
+fact that its use is restricted to experienced users has been provided
+to the Licensee prior to its acceptance as set forth in Article 3.1
+hereinabove, and the Licensee hereby acknowledges that it has read and
+understood it.
+
+
+ Article 4 - EFFECTIVE DATE AND TERM
+
+
+ 4.1 EFFECTIVE DATE
+
+The Agreement shall become effective on the date when it is accepted by
+the Licensee as set forth in Article 3.1.
+
+
+ 4.2 TERM
+
+The Agreement shall remain in force for the entire legal term of
+protection of the economic rights over the Software.
+
+
+ Article 5 - SCOPE OF RIGHTS GRANTED
+
+The Licensor hereby grants to the Licensee, who accepts, the following
+rights over the Software for any or all use, and for the term of the
+Agreement, on the basis of the terms and conditions set forth hereinafter.
+
+Besides, if the Licensor owns or comes to own one or more patents
+protecting all or part of the functions of the Software or of its
+components, the Licensor undertakes not to enforce the rights granted by
+these patents against successive Licensees using, exploiting or
+modifying the Software. If these patents are transferred, the Licensor
+undertakes to have the transferees subscribe to the obligations set
+forth in this paragraph.
+
+
+ 5.1 RIGHT OF USE
+
+The Licensee is authorized to use the Software, without any limitation
+as to its fields of application, with it being hereinafter specified
+that this comprises:
+
+ 1. permanent or temporary reproduction of all or part of the Software
+ by any or all means and in any or all form.
+
+ 2. loading, displaying, running, or storing the Software on any or
+ all medium.
+
+ 3. entitlement to observe, study or test its operation so as to
+ determine the ideas and principles behind any or all constituent
+ elements of said Software. This shall apply when the Licensee
+ carries out any or all loading, displaying, running, transmission
+ or storage operation as regards the Software, that it is entitled
+ to carry out hereunder.
+
+
+ 5.2 RIGHT OF MODIFICATION
+
+The right of modification includes the right to translate, adapt,
+arrange, or make any or all modifications to the Software, and the right
+to reproduce the resulting software. It includes, in particular, the
+right to create a Derivative Software.
+
+The Licensee is authorized to make any or all modification to the
+Software provided that it includes an explicit notice that it is the
+author of said modification and indicates the date of the creation thereof.
+
+
+ 5.3 RIGHT OF DISTRIBUTION
+
+In particular, the right of distribution includes the right to publish,
+transmit and communicate the Software to the general public on any or
+all medium, and by any or all means, and the right to market, either in
+consideration of a fee, or free of charge, one or more copies of the
+Software by any means.
+
+The Licensee is further authorized to distribute copies of the modified
+or unmodified Software to third parties according to the terms and
+conditions set forth hereinafter.
+
+
+ 5.3.1 DISTRIBUTION OF SOFTWARE WITHOUT MODIFICATION
+
+The Licensee is authorized to distribute true copies of the Software in
+Source Code or Object Code form, provided that said distribution
+complies with all the provisions of the Agreement and is accompanied by:
+
+ 1. a copy of the Agreement,
+
+ 2. a notice relating to the limitation of both the Licensor's
+ warranty and liability as set forth in Articles 8 and 9,
+
+and that, in the event that only the Object Code of the Software is
+redistributed, the Licensee allows effective access to the full Source
+Code of the Software at a minimum during the entire period of its
+distribution of the Software, it being understood that the additional
+cost of acquiring the Source Code shall not exceed the cost of
+transferring the data.
+
+
+ 5.3.2 DISTRIBUTION OF MODIFIED SOFTWARE
+
+When the Licensee makes an Integrated Contribution to the Software, the
+terms and conditions for the distribution of the resulting Modified
+Software become subject to all the provisions of this Agreement.
+
+The Licensee is authorized to distribute the Modified Software, in
+source code or object code form, provided that said distribution
+complies with all the provisions of the Agreement and is accompanied by:
+
+ 1. a copy of the Agreement,
+
+ 2. a notice relating to the limitation of both the Licensor's
+ warranty and liability as set forth in Articles 8 and 9,
+
+and that, in the event that only the object code of the Modified
+Software is redistributed, the Licensee allows effective access to the
+full source code of the Modified Software at a minimum during the entire
+period of its distribution of the Modified Software, it being understood
+that the additional cost of acquiring the source code shall not exceed
+the cost of transferring the data.
+
+
+ 5.3.3 DISTRIBUTION OF DERIVATIVE SOFTWARE
+
+When the Licensee creates Derivative Software, this Derivative Software
+may be distributed under a license agreement other than this Agreement,
+subject to compliance with the requirement to include a notice
+concerning the rights over the Software as defined in Article 6.4.
+In the event the creation of the Derivative Software required modification
+of the Source Code, the Licensee undertakes that:
+
+ 1. the resulting Modified Software will be governed by this Agreement,
+ 2. the Integrated Contributions in the resulting Modified Software
+ will be clearly identified and documented,
+ 3. the Licensee will allow effective access to the source code of the
+ Modified Software, at a minimum during the entire period of
+ distribution of the Derivative Software, such that such
+ modifications may be carried over in a subsequent version of the
+ Software; it being understood that the additional cost of
+ purchasing the source code of the Modified Software shall not
+ exceed the cost of transferring the data.
+
+
+ 5.3.4 COMPATIBILITY WITH THE CeCILL LICENSE
+
+When a Modified Software contains an Integrated Contribution subject to
+the CeCILL license agreement, or when a Derivative Software contains a
+Related Module subject to the CeCILL license agreement, the provisions
+set forth in the third item of Article 6.4 are optional.
+
+
+ Article 6 - INTELLECTUAL PROPERTY
+
+
+ 6.1 OVER THE INITIAL SOFTWARE
+
+The Holder owns the economic rights over the Initial Software. Any or
+all use of the Initial Software is subject to compliance with the terms
+and conditions under which the Holder has elected to distribute its work
+and no one shall be entitled to modify the terms and conditions for the
+distribution of said Initial Software.
+
+The Holder undertakes that the Initial Software will remain ruled at
+least by this Agreement, for the duration set forth in Article 4.2.
+
+
+ 6.2 OVER THE INTEGRATED CONTRIBUTIONS
+
+The Licensee who develops an Integrated Contribution is the owner of the
+intellectual property rights over this Contribution as defined by
+applicable law.
+
+
+ 6.3 OVER THE RELATED MODULES
+
+The Licensee who develops a Related Module is the owner of the
+intellectual property rights over this Related Module as defined by
+applicable law and is free to choose the type of agreement that shall
+govern its distribution under the conditions defined in Article 5.3.3.
+
+
+ 6.4 NOTICE OF RIGHTS
+
+The Licensee expressly undertakes:
+
+ 1. not to remove, or modify, in any manner, the intellectual property
+ notices attached to the Software;
+
+ 2. to reproduce said notices, in an identical manner, in the copies
+ of the Software modified or not;
+
+ 3. to ensure that use of the Software, its intellectual property
+ notices and the fact that it is governed by the Agreement is
+ indicated in a text that is easily accessible, specifically from
+ the interface of any Derivative Software.
+
+The Licensee undertakes not to directly or indirectly infringe the
+intellectual property rights of the Holder and/or Contributors on the
+Software and to take, where applicable, vis-à-vis its staff, any and all
+measures required to ensure respect of said intellectual property rights
+of the Holder and/or Contributors.
+
+
+ Article 7 - RELATED SERVICES
+
+7.1 Under no circumstances shall the Agreement oblige the Licensor to
+provide technical assistance or maintenance services for the Software.
+
+However, the Licensor is entitled to offer this type of services. The
+terms and conditions of such technical assistance, and/or such
+maintenance, shall be set forth in a separate instrument. Only the
+Licensor offering said maintenance and/or technical assistance services
+shall incur liability therefor.
+
+7.2 Similarly, any Licensor is entitled to offer to its licensees, under
+its sole responsibility, a warranty, that shall only be binding upon
+itself, for the redistribution of the Software and/or the Modified
+Software, under terms and conditions that it is free to decide. Said
+warranty, and the financial terms and conditions of its application,
+shall be subject of a separate instrument executed between the Licensor
+and the Licensee.
+
+
+ Article 8 - LIABILITY
+
+8.1 Subject to the provisions of Article 8.2, the Licensee shall be
+entitled to claim compensation for any direct loss it may have suffered
+from the Software as a result of a fault on the part of the relevant
+Licensor, subject to providing evidence thereof.
+
+8.2 The Licensor's liability is limited to the commitments made under
+this Agreement and shall not be incurred as a result of in particular:
+(i) loss due the Licensee's total or partial failure to fulfill its
+obligations, (ii) direct or consequential loss that is suffered by the
+Licensee due to the use or performance of the Software, and (iii) more
+generally, any consequential loss. In particular the Parties expressly
+agree that any or all pecuniary or business loss (i.e. loss of data,
+loss of profits, operating loss, loss of customers or orders,
+opportunity cost, any disturbance to business activities) or any or all
+legal proceedings instituted against the Licensee by a third party,
+shall constitute consequential loss and shall not provide entitlement to
+any or all compensation from the Licensor.
+
+
+ Article 9 - WARRANTY
+
+9.1 The Licensee acknowledges that the scientific and technical
+state-of-the-art when the Software was distributed did not enable all
+possible uses to be tested and verified, nor for the presence of
+possible defects to be detected. In this respect, the Licensee's
+attention has been drawn to the risks associated with loading, using,
+modifying and/or developing and reproducing the Software which are
+reserved for experienced users.
+
+The Licensee shall be responsible for verifying, by any or all means,
+the suitability of the product for its requirements, its good working
+order, and for ensuring that it shall not cause damage to either persons
+or properties.
+
+9.2 The Licensor hereby represents, in good faith, that it is entitled
+to grant all the rights over the Software (including in particular the
+rights set forth in Article 5).
+
+9.3 The Licensee acknowledges that the Software is supplied "as is" by
+the Licensor without any other express or tacit warranty, other than
+that provided for in Article 9.2 and, in particular, without any warranty
+as to its commercial value, its secured, safe, innovative or relevant
+nature.
+
+Specifically, the Licensor does not warrant that the Software is free
+from any error, that it will operate without interruption, that it will
+be compatible with the Licensee's own equipment and software
+configuration, nor that it will meet the Licensee's requirements.
+
+9.4 The Licensor does not either expressly or tacitly warrant that the
+Software does not infringe any third party intellectual property right
+relating to a patent, software or any other property right. Therefore,
+the Licensor disclaims any and all liability towards the Licensee
+arising out of any or all proceedings for infringement that may be
+instituted in respect of the use, modification and redistribution of the
+Software. Nevertheless, should such proceedings be instituted against
+the Licensee, the Licensor shall provide it with technical and legal
+assistance for its defense. Such technical and legal assistance shall be
+decided on a case-by-case basis between the relevant Licensor and the
+Licensee pursuant to a memorandum of understanding. The Licensor
+disclaims any and all liability as regards the Licensee's use of the
+name of the Software. No warranty is given as regards the existence of
+prior rights over the name of the Software or as regards the existence
+of a trademark.
+
+
+ Article 10 - TERMINATION
+
+10.1 In the event of a breach by the Licensee of its obligations
+hereunder, the Licensor may automatically terminate this Agreement
+thirty (30) days after notice has been sent to the Licensee and has
+remained ineffective.
+
+10.2 A Licensee whose Agreement is terminated shall no longer be
+authorized to use, modify or distribute the Software. However, any
+licenses that it may have granted prior to termination of the Agreement
+shall remain valid subject to their having been granted in compliance
+with the terms and conditions hereof.
+
+
+ Article 11 - MISCELLANEOUS
+
+
+ 11.1 EXCUSABLE EVENTS
+
+Neither Party shall be liable for any or all delay, or failure to
+perform the Agreement, that may be attributable to an event of force
+majeure, an act of God or an outside cause, such as defective
+functioning or interruptions of the electricity or telecommunications
+networks, network paralysis following a virus attack, intervention by
+government authorities, natural disasters, water damage, earthquakes,
+fire, explosions, strikes and labor unrest, war, etc.
+
+11.2 Any failure by either Party, on one or more occasions, to invoke
+one or more of the provisions hereof, shall under no circumstances be
+interpreted as being a waiver by the interested Party of its right to
+invoke said provision(s) subsequently.
+
+11.3 The Agreement cancels and replaces any or all previous agreements,
+whether written or oral, between the Parties and having the same
+purpose, and constitutes the entirety of the agreement between said
+Parties concerning said purpose. No supplement or modification to the
+terms and conditions hereof shall be effective as between the Parties
+unless it is made in writing and signed by their duly authorized
+representatives.
+
+11.4 In the event that one or more of the provisions hereof were to
+conflict with a current or future applicable act or legislative text,
+said act or legislative text shall prevail, and the Parties shall make
+the necessary amendments so as to comply with said act or legislative
+text. All other provisions shall remain effective. Similarly, invalidity
+of a provision of the Agreement, for any reason whatsoever, shall not
+cause the Agreement as a whole to be invalid.
+
+
+ 11.5 LANGUAGE
+
+The Agreement is drafted in both French and English and both versions
+are deemed authentic.
+
+
+ Article 12 - NEW VERSIONS OF THE AGREEMENT
+
+12.1 Any person is authorized to duplicate and distribute copies of this
+Agreement.
+
+12.2 So as to ensure coherence, the wording of this Agreement is
+protected and may only be modified by the authors of the License, who
+reserve the right to periodically publish updates or new versions of the
+Agreement, each with a separate number. These subsequent versions may
+address new issues encountered by Free Software.
+
+12.3 Any Software distributed under a given version of the Agreement may
+only be subsequently distributed under the same version of the Agreement
+or a subsequent version.
+
+
+ Article 13 - GOVERNING LAW AND JURISDICTION
+
+13.1 The Agreement is governed by French law. The Parties agree to
+endeavor to seek an amicable solution to any disagreements or disputes
+that may arise during the performance of the Agreement.
+
+13.2 Failing an amicable solution within two (2) months as from their
+occurrence, and unless emergency proceedings are necessary, the
+disagreements or disputes shall be referred to the Paris Courts having
+jurisdiction, by the more diligent Party.
+
+
+Version 1.0 dated 2006-09-05.
diff --git a/LICENSE.LGPL b/LICENSE.LGPL
new file mode 100644
index 0000000..65c5ca8
--- /dev/null
+++ b/LICENSE.LGPL
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
|
paulgirard/pygexf
|
3ea7da17f1b93501c076fcdbce6a50bf47eefcf7
|
Get edge attributes, not node attributes
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index d071212..75ada26 100644
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -178,888 +178,888 @@ class Graph :
# check conformity with type is missing
# if id in self._nodesAttributes.keys() :
# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static", force_id=""):
return self._attributes.declareAttribute("edge",type,defaultValue,title,mode,force_id)
def addDefaultAttributesToEdge(self,edge) :
""" deprecated """
pass
def checkEdgeAttribute(self,id,value,start,end):
"""deprecated """
pass
# # check conformity with type is missing
# if id in self._edgesAttributes.keys() :
# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label,timeformat=self.time_format)
for attributesElement in self.attributes.getAttributesDeclarationXML() :
graphXML.append(attributesElement)
nodesXML = etree.SubElement(graphXML, "nodes")
node_ids=self._nodes.keys()
node_ids.sort()
for id in node_ids :
nodesXML.append(self._nodes[id].getXML())
edgesXML = etree.SubElement(graphXML, "edges")
edge_ids=self._edges.keys()
edge_ids.sort()
for id in edge_ids :
edgesXML.append(self._edges[id].getXML())
return graphXML
@staticmethod
def importXML(graph_xml,gexf_obj) :
""" import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""
# get Graph attributes
type = ""
mode = ""
label = ""
timeformat="double"
for attr in graph_xml.attrib :
attr = attr.lower()
if attr == "defaultedgetype" :
type = graph_xml.attrib[attr]
if attr == "mode" :
mode = graph_xml.attrib[attr]
if attr == "label" :
label = graph_xml.attrib[attr]
if attr == "timeformat" :
timeformat = graph_xml.attrib[attr]
# create and attache the graph object to the Gexf object
graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)
for child in graph_xml :
tag = ns_clean(child.tag).lower()
if tag == "attributes" :
attributes_xml = child
# Delegate Attributes declaration to the attribute object
graph_obj.attributes.importAttributesXML(attributes_xml)
if tag == "nodes" :
nodes_xml = child
# Delegate nodes creation to the Node class
Node.importXML(nodes_xml,graph_obj)
if tag == "edges" :
edges_xml = child
# Delegate edges creation to the Edge class
Edge.importXML(edges_xml,graph_obj)
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Attributes(dict):
"""
attributes=
{
"node" :
{ "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },
"edge" :
{ "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },
}
"""
def __init__(self):
self.type_choices=["integer","string","float","double","boolean","date","URI"]
self.attClass_choices=["node","edge"]
self.mode_choices=["static","dynamic"]
for attClass in self.attClass_choices :
self[attClass]={}
def declareAttribute(self,attClass,type,defaultValue,title="",mode="static",id=None) :
"""
add a new attribute declaration to the graph
"""
if attClass in self.attClass_choices :
# should add quality control here on type and defaultValue
# if no id given generating a numerical one based on dict length
if not id :
id = str(len(self[attClass]))
self[attClass][id]={"id":id,"type":type,"defaultValue":defaultValue,"mode":mode,"title":title}
return id
else :
raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(type_choices))
def makeAttributeInstance(self,attClass,id=None,value=None,start=None,end=None,startopen=False,endopen=False) :
"""
generate an attribute to be include to a node or edge.
copied from the declared attributes, thus any attribute has to be declared first
"""
if attClass in self.attClass_choices :
if id in self[attClass].keys() :
att={"id":id}
att["value"]=value if value else self[attClass][id].defaultValue
if self[attClass][id]["mode"]=="dynamic" and start or end :
# start & end will be discarded if the mode is set to static
if start :
att["start"]=start
if startopen :
att["startopen"]=startopen
if end :
att["end"]=end
if endopen :
att["endopen"]=endopen
return att
else :
raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute"%(id,))
else :
raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(self.type_choices))
def getAttributesDeclarationXML(self) :
""" generate attributes declaration XML """
# return lxml etree element
allAttributesXML=[]
if len(self)>0 :
# iter on node and then edge atts
for attClass,atts in self.iteritems() :
# group by mode
key_mode=lambda att : att["mode"]
atts_sorted_by_mode=sorted(atts.values(),key=key_mode,reverse=True)
for mode,atts in itertools.groupby(atts_sorted_by_mode,key_mode) :
# generate on attributes by mode
attributesXML = etree.Element("attributes")
attributesXML.set("class",attClass)
attributesXML.set("mode",mode)
# generate attribute by id order
for att in sorted(atts,key=lambda att: att["id"]) :
attributeXML=etree.SubElement(attributesXML, "attribute")
attributeXML.set("id",str(att["id"]))
attributeXML.set("title",att["title"])
attributeXML.set("type",att["type"])
if att["defaultValue"] :
etree.SubElement(attributeXML, "default").text=att["defaultValue"]
allAttributesXML.append(attributesXML)
return allAttributesXML
@staticmethod
def getAttributesXML(atts) :
""" get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""
if len(atts)>0:
attValuesXML = etree.Element("attvalues")
for att in atts :
attValueXML=etree.SubElement(attValuesXML, "attvalue")
attValueXML.set("for",str(att["id"]))
attValueXML.set("value",att["value"])
if "start" in att.keys() and not att["start"]=="" :
attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen",att["start"])
if "end" in att.keys() and not att["end"]=="" :
attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen",att["end"])
return attValuesXML
else :
return None
def importAttributesXML(self,attributes_xml):
""" get XML attributes declaration of a graph gexf"""
attr_class = None
mode = ""
for attr in attributes_xml.attrib :
attr = attr.lower()
if attr == "class" :
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode" :
mode = attributes_xml.attrib[attr]
for child in attributes_xml :
tag = ns_clean(child.tag).lower()
if tag == "attribute" :
attribute_xml = child
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = attribute_xml.attrib[attr]
if attr == "title" :
title = attribute_xml.attrib[attr]
if attr == "type" :
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml :
tag = ns_clean(child.tag).lower()
if tag == "default" :
default = child.text
self.declareAttribute(attr_class,type,default,title,mode,id)
def importAttributesValuesXML(self,attClass,attvalues_xml):
""" import attributes values from attvalues gexf xml tag attached to nodes or edges"""
atts=[]
for attvalues in attvalues_xml :
for child in attvalues :
tag = ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
id = ""
value = ""
start = ""
startopen=False
end = ""
endopen=False
for attr in attvalue_xml.attrib :
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen = True
atts.append(self.makeAttributeInstance(attClass,id,value,start,end,startopen,endopen))
return atts
class Spells(list):
'''
spells are time periods
spells is a list of dictionaries
a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}
'''
def getXML(self):
spellsXML=etree.Element("spells")
for spell in self :
spellXML=etree.SubElement(spellsXML, "spell")
if "start" in spell.keys() :
spellXML.set("start",spell["start"])
if "end" in spell.keys() :
spellXML.set("end",spell["end"])
return spellsXML
@staticmethod
def importXML(spellsxmltree):
return Spells([ spell.attrib for spell in spellsxmltree])
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self.id =id
self.label=label
self.start=start
self.startopen=startopen
self.end=end
self.endopen=endopen
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
#spells expecting format = [{start:"",end:""},...]
self.spells= spells
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
self.attributes=self._attributes
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :
self._attributes.append(self._graph.attributes.makeAttributeInstance("node",id,value,start,end,startopen,endopen))
def getXML(self) :
# return lxml etree element
try :
nodeXML = etree.Element("node",id=str(self.id),label=self.label)
if not self.start == "":
nodeXML.set("start" if not self.startopen else "startopen",self.start)
if not self.end == "":
nodeXML.set("end" if not self.endopen else "endopen" ,self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
# attributes
if self._attributes :
nodeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells :
print "found spells in node "+self.id
nodeXML.append(self.spells.getXML())
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception, e:
print self.label
print self._attributes
print e
traceback.print_exc()
exit()
def getAttributes(self):
attsFull=[]
for att in self._attributes :
attFull=self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(nodes_xml,graph_obj) :
for child in nodes_xml :
tag = ns_clean(child.tag).lower()
if tag == "node" :
node_xml = child
id = ""
label = ""
start = ""
startopen=False
end = ""
endopen=False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = node_xml.attrib[attr]
if attr == "label" :
label = node_xml.attrib[attr]
if attr == "start" :
start = node_xml.attrib[attr]
if attr == "end" :
start = node_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
if attr == "pid" :
pid = node_xml.attrib[attr]
attvalues_xml = []
spells=[]
for child in node_xml :
tag = ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml.append(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag =="spells" :
spells=Spells.importXML(child)
node_obj = graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)
node_obj._attributes =graph_obj.attributes.importAttributesValuesXML("node",attvalues_xml)
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
def __str__(self):
return self.label
class Edge :
def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self.id =id
self._graph=graph
if self._graph.nodeExists(source) :
self._source=source
self.source=self._source
else :
raise Exception("source "+source+" node unknown, add nodes to graph first")
if self._graph.nodeExists(target) :
self._target=target
self.target=self._target
else:
raise Exception("target "+target+" node unknown, add nodes to graph first")
self.start=start
self.startopen=startopen
self.end=end
self.endopen=endopen
self.weight=weight
self.label=label
self._attributes=[]
self.attributes=self._attributes
# COLOR on edges now supported in GEXF 1.2
self.setColor(r,g,b)
#spells expecting format = [{start:"",end:""},...]
self.spells= Spells()
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :
self._attributes.append(self._graph.attributes.makeAttributeInstance("edge",id,value,start,end,startopen,endopen))
def getXML(self) :
# return lxml etree element
try :
edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
if not self.start == "":
edgeXML.set("start" if not self.startopen else "startopen",self.start)
if not self.end == "":
edgeXML.set("end" if not self.endopen else "endopen" ,self.end)
if not self.weight == "":
edgeXML.set("weight",str(self.weight))
if not self.label == "":
edgeXML.set("label",self.label)
# attributes
if self._attributes :
edgeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells :
spellsXML.append(self.spells.getXML())
# COLOR on edges is supported in GEXF since 1.2
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.2draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return edgeXML
except Exception, e:
print self._source+" "+self._target
print e
exit()
def getAttributes(self):
attsFull=[]
for att in self._attributes :
- attFull=self._graph.attributes["node"][att["id"]].copy()
+ attFull=self._graph.attributes["edge"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(edges_xml,graph_obj) :
for child in edges_xml :
tag = ns_clean(child.tag).lower()
if tag == "edge" :
edge_xml = child
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen=False
end = ""
endopen=False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = edge_xml.attrib[attr]
if attr == "source" :
source = edge_xml.attrib[attr]
if attr == "target" :
target = edge_xml.attrib[attr]
if attr == "weight" :
weight = edge_xml.attrib[attr]
if attr == "start" :
start = edge_xml.attrib[attr]
if attr == "end" :
end = edge_xml.attrib[attr]
if attr == "startopen" :
start = edge_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = edge_xml.attrib[attr]
endopen=True
if attr == "label" :
label = edge_xml.attrib[attr]
spells=[]
attvalues_xml=[]
for child in edge_xml :
tag = ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml.append(child)
if tag =="spells" :
spells=Spells.importXML(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
edge_obj = graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)
edge_obj._attributes=graph_obj.attributes.importAttributesValuesXML("edge",attvalues_xml)
# COLOR on edges is supported in GEXF since 1.2
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class GexfImport :
# class coded by elie Rotenberg, médialab 20/07/2010
# deprecated : import XML codes are now included to the Gexf, Graph, Attribute, Node, Edge classes
def __init__(self, file_like) :
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(file_like, parser)
gexf_xml = tree.getroot()
tag = self.ns_clean(gexf_xml.tag).lower()
if tag <> "gexf" :
self.msg_unexpected_tag("gexf", tag)
return
self.gexf_obj = None
for child in gexf_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "meta" :
meta_xml = child
self.gexf_obj = self.extract_gexf_obj(meta_xml)
if tag == "graph" :
graph_xml = child
if self.gexf_obj == None :
self.msg_unexpected_tag("meta", tag)
return
self.graph_obj = self.extract_graph_obj(graph_xml)
def ns_clean(self, token) :
i = token.find('}')
return token[i+1:]
def msg_unexpected_tag(self, expected, got) :
print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
def extract_gexf_obj(self, meta_xml) :
for child in meta_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "creator" :
creator = child.text
if tag == "description" :
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml) :
type = ""
mode = ""
label = ""
timeformat="double"
for attr in graph_xml.attrib :
attr = attr.lower()
if attr == "defaultedgetype" :
type = graph_xml.attrib[attr]
if attr == "mode" :
mode = graph_xml.attrib[attr]
if attr == "label" :
label = graph_xml.attrib[attr]
if attr == "timeformat" :
timeformat = graph_xml.attrib[attr]
self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)
for child in graph_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attributes" :
attributes_xml = child
self.extract_attributes(attributes_xml)
if tag == "nodes" :
nodes_xml = child
self.extract_nodes(nodes_xml)
if tag == "edges" :
edges_xml = child
self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml) :
attr_class = None
mode = ""
for attr in attributes_xml.attrib :
attr = attr.lower()
if attr == "class" :
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode" :
mode = attributes_xml.attrib[attr]
for child in attributes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attribute" :
attribute_xml = child
self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode) :
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = attribute_xml.attrib[attr]
if attr == "title" :
title = attribute_xml.attrib[attr]
if attr == "type" :
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "default" :
default = child.text
if attr_class == "node" :
self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)
if attr_class == "edge" :
self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)
def extract_nodes(self, nodes_xml) :
for child in nodes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "node" :
node_xml = child
self.extract_node(node_xml)
def extract_node(self, node_xml) :
id = ""
label = ""
start = ""
startopen=False
end = ""
endopen=False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = node_xml.attrib[attr]
if attr == "label" :
label = node_xml.attrib[attr]
if attr == "start" :
start = node_xml.attrib[attr]
if attr == "end" :
start = node_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
if attr == "pid" :
pid = node_xml.attrib[attr]
attvalues_xmls = []
spells=[]
for child in node_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xmls.append(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag =="spells" :
spells=[ spell.attrib for spell in child ]
self.node_obj = self.graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)
for attvalues_xml in attvalues_xmls :
self.extract_node_attvalues(attvalues_xml)
def extract_node_attvalues(self, attvalues_xml) :
for child in attvalues_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
self.extract_node_attvalue(attvalue_xml)
def extract_node_attvalue(self, attvalue_xml) :
id = ""
value = ""
start = ""
startopen=False
end = ""
endopen=False
for attr in attvalue_xml.attrib :
attr = attr.lower()
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
self.node_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)
def extract_edges(self, edges_xml) :
for child in edges_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "edge" :
edge_xml = child
self.extract_edge(edge_xml)
def extract_edge(self, edge_xml) :
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen=False
end = ""
endopen=False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = edge_xml.attrib[attr]
if attr == "source" :
source = edge_xml.attrib[attr]
if attr == "target" :
target = edge_xml.attrib[attr]
if attr == "weight" :
weight = edge_xml.attrib[attr]
if attr == "start" :
start = edge_xml.attrib[attr]
if attr == "end" :
end = edge_xml.attrib[attr]
if attr == "startopen" :
start = edge_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = edge_xml.attrib[attr]
endopen=True
if attr == "label" :
label = edge_xml.attrib[attr]
spells=[]
attvalues_xml=[]
for child in edge_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml = child
if tag =="spells" :
spells=[ spell.attrib for spell in child]
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
self.edge_obj = self.graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)
self.extract_edge_attvalues(attvalues_xml)
def extract_edge_attvalues(self, attvalues_xml) :
for child in attvalues_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
self.extract_edge_attvalue(attvalue_xml)
# def addAttribute(self,id,value,start="",end="") :
def extract_edge_attvalue(self, attvalue_xml) :
id = ""
value = ""
start = ""
startopen=True
end = ""
endopen=True
for attr in attvalue_xml.attrib :
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
startopen = attvalue_xml.attrib[attr]
if attr == "endopen" :
endopen = attvalue_xml.attrib[attr]
self.edge_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)
def gexf(self) :
return self.gexf_obj
|
paulgirard/pygexf
|
641b43a77019ee241dce5aae7c603d1241ba6a42
|
Bugfixes for spells
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
old mode 100644
new mode 100755
index d071212..5526624
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,1065 +1,1067 @@
# -*- coding: utf-8 -*-
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
from lxml import etree
from datetime import date
import itertools
import traceback
# missing features :
# data validation regarding attribute types
# phylogeny
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
def msg_unexpected_tag(expected, got) :
print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
def ns_clean(token) :
i = token.find('}')
return token[i+1:]
class Gexf :
def __init__(self,creator,description):
self.creator=creator
self.description=description
self.graphs=[]
self.xmlns="http://www.gephi.org/gexf/1.2draft"
self.xsi="http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.2draft.xsd"
self.viz="http://www.gexf.net/1.2draft/viz"
self.version="1.2"
def addGraph(self,type,mode,label,timeformat=""):
g = Graph(type,mode,label,timeformat)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified",date.today().isoformat())
etree.SubElement(meta, "creator").text=self.creator
etree.SubElement(meta, "description").text=self.description
for graph in self.graphs :
gexfXML.append(graph.getXML())
return gexfXML
def write(self,file, print_stat=True):
file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8',xml_declaration=True))
if print_stat == True:
self.print_stat()
def print_stat(self) :
for graph in self.graphs :
graph.print_stat()
@staticmethod
def importXML(gexf_file) :
""" import gexf xml meta tags to create a Gexf Object and delegate Graph extraction to Graph class"""
# parse the gexf file
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse((gexf_file), parser)
# start create Gexf Object
gexf_xml = tree.getroot()
tag = ns_clean(gexf_xml.tag).lower()
if tag <> "gexf" :
msg_unexpected_tag("gexf", tag)
return
gexf_obj = None
for child in gexf_xml :
tag = ns_clean(child.tag).lower()
# create a gexf object by importing meta tag
if tag == "meta" :
meta_xml = child
for child in meta_xml :
tag = ns_clean(child.tag).lower()
if tag == "creator" :
creator = child.text
if tag == "description" :
description = child.text
gexf_obj=Gexf(creator=creator, description=description)
# export graph xml through Graph Class
if tag == "graph" :
graph_xml = child
if gexf_obj == None :
msg_unexpected_tag("meta", tag)
return
Graph.importXML(graph_xml,gexf_obj)
return gexf_obj
class Graph :
def __init__(self,type,mode,label,time_format="double",start="",end="") :
# control variable
self.authorizedType=("directed","undirected")
self.authorizedMode=("dynamic","static")
# time format
# Discrete: integer or double
# Continuous : date (yyyy-mm-dd) or dateTime
# default : double
self.authorizedTimeFormat=("integer","double","date","dateTime")
self.defaultTimeFormat="double"
self.defaultType="directed"
self.defaultMode="static"
self.label=label
if type in self.authorizedType :
self.type=type
else :
self.type=self.defaultType
if mode in self.authorizedMode :
self.mode=mode
else :
self.mode=self.defaultMode
if time_format in self.authorizedTimeFormat :
self.time_format=time_format
else :
self.time_format=self.defaultTimeFormat
self.start=start
self.end = end
self._attributes= Attributes()
self.attributes = self._attributes
self._nodes={}
self.nodes=self._nodes
self._edges={}
self.edges=self._edges
def addNode(self,id,label,start="",end="",startopen=False,endopen=False,pid="",r="",g="",b="",spells=[]) :
self._nodes[str(id)]=Node(self,id,label,start,end,pid,r,g,b,spells,startopen,endopen)
return self._nodes[str(id)]
def nodeExists(self,id) :
if id in self._nodes.keys():
return 1
else :
return 0
def addEdge(self,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self._edges[str(id)]=Edge(self,id,source,target,weight,start,end,label,r,g,b,spells,startopen,endopen)
return self._edges[str(id)]
def addNodeAttribute(self,title,defaultValue=None,type="integer",mode="static", force_id="") :
# add to NodeAttributes
return self._attributes.declareAttribute("node",type,defaultValue,title,mode,force_id)
def addDefaultAttributesToNode(self,node) :
""" deprecated """
pass
def checkNodeAttribute(self,id,value,start,end):
"""deprecated"""
pass
# check conformity with type is missing
# if id in self._nodesAttributes.keys() :
# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static", force_id=""):
return self._attributes.declareAttribute("edge",type,defaultValue,title,mode,force_id)
def addDefaultAttributesToEdge(self,edge) :
""" deprecated """
pass
def checkEdgeAttribute(self,id,value,start,end):
"""deprecated """
pass
# # check conformity with type is missing
# if id in self._edgesAttributes.keys() :
# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label,timeformat=self.time_format)
for attributesElement in self.attributes.getAttributesDeclarationXML() :
graphXML.append(attributesElement)
nodesXML = etree.SubElement(graphXML, "nodes")
node_ids=self._nodes.keys()
node_ids.sort()
for id in node_ids :
nodesXML.append(self._nodes[id].getXML())
edgesXML = etree.SubElement(graphXML, "edges")
edge_ids=self._edges.keys()
edge_ids.sort()
for id in edge_ids :
edgesXML.append(self._edges[id].getXML())
return graphXML
@staticmethod
def importXML(graph_xml,gexf_obj) :
""" import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""
# get Graph attributes
type = ""
mode = ""
label = ""
timeformat="double"
for attr in graph_xml.attrib :
attr = attr.lower()
if attr == "defaultedgetype" :
type = graph_xml.attrib[attr]
if attr == "mode" :
mode = graph_xml.attrib[attr]
if attr == "label" :
label = graph_xml.attrib[attr]
if attr == "timeformat" :
timeformat = graph_xml.attrib[attr]
# create and attache the graph object to the Gexf object
graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)
for child in graph_xml :
tag = ns_clean(child.tag).lower()
if tag == "attributes" :
attributes_xml = child
# Delegate Attributes declaration to the attribute object
graph_obj.attributes.importAttributesXML(attributes_xml)
if tag == "nodes" :
nodes_xml = child
# Delegate nodes creation to the Node class
Node.importXML(nodes_xml,graph_obj)
if tag == "edges" :
edges_xml = child
# Delegate edges creation to the Edge class
Edge.importXML(edges_xml,graph_obj)
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Attributes(dict):
"""
attributes=
{
"node" :
{ "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },
"edge" :
{ "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },
}
"""
def __init__(self):
self.type_choices=["integer","string","float","double","boolean","date","URI"]
self.attClass_choices=["node","edge"]
self.mode_choices=["static","dynamic"]
for attClass in self.attClass_choices :
self[attClass]={}
def declareAttribute(self,attClass,type,defaultValue,title="",mode="static",id=None) :
"""
add a new attribute declaration to the graph
"""
if attClass in self.attClass_choices :
# should add quality control here on type and defaultValue
# if no id given generating a numerical one based on dict length
if not id :
id = str(len(self[attClass]))
self[attClass][id]={"id":id,"type":type,"defaultValue":defaultValue,"mode":mode,"title":title}
return id
else :
raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(type_choices))
def makeAttributeInstance(self,attClass,id=None,value=None,start=None,end=None,startopen=False,endopen=False) :
"""
generate an attribute to be include to a node or edge.
copied from the declared attributes, thus any attribute has to be declared first
"""
if attClass in self.attClass_choices :
if id in self[attClass].keys() :
att={"id":id}
- att["value"]=value if value else self[attClass][id].defaultValue
+ att["value"]=value if value else self[attClass][id]["defaultValue"]
if self[attClass][id]["mode"]=="dynamic" and start or end :
# start & end will be discarded if the mode is set to static
if start :
att["start"]=start
if startopen :
att["startopen"]=startopen
if end :
att["end"]=end
if endopen :
att["endopen"]=endopen
return att
else :
raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute"%(id,))
else :
raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(self.type_choices))
def getAttributesDeclarationXML(self) :
""" generate attributes declaration XML """
# return lxml etree element
allAttributesXML=[]
if len(self)>0 :
# iter on node and then edge atts
for attClass,atts in self.iteritems() :
# group by mode
key_mode=lambda att : att["mode"]
atts_sorted_by_mode=sorted(atts.values(),key=key_mode,reverse=True)
for mode,atts in itertools.groupby(atts_sorted_by_mode,key_mode) :
# generate on attributes by mode
attributesXML = etree.Element("attributes")
attributesXML.set("class",attClass)
attributesXML.set("mode",mode)
# generate attribute by id order
for att in sorted(atts,key=lambda att: att["id"]) :
attributeXML=etree.SubElement(attributesXML, "attribute")
attributeXML.set("id",str(att["id"]))
attributeXML.set("title",att["title"])
attributeXML.set("type",att["type"])
if att["defaultValue"] :
etree.SubElement(attributeXML, "default").text=att["defaultValue"]
allAttributesXML.append(attributesXML)
return allAttributesXML
@staticmethod
def getAttributesXML(atts) :
""" get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""
if len(atts)>0:
attValuesXML = etree.Element("attvalues")
for att in atts :
attValueXML=etree.SubElement(attValuesXML, "attvalue")
attValueXML.set("for",str(att["id"]))
attValueXML.set("value",att["value"])
if "start" in att.keys() and not att["start"]=="" :
attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen",att["start"])
if "end" in att.keys() and not att["end"]=="" :
attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen",att["end"])
return attValuesXML
else :
return None
def importAttributesXML(self,attributes_xml):
""" get XML attributes declaration of a graph gexf"""
attr_class = None
mode = ""
for attr in attributes_xml.attrib :
attr = attr.lower()
if attr == "class" :
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode" :
mode = attributes_xml.attrib[attr]
for child in attributes_xml :
tag = ns_clean(child.tag).lower()
if tag == "attribute" :
attribute_xml = child
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = attribute_xml.attrib[attr]
if attr == "title" :
title = attribute_xml.attrib[attr]
if attr == "type" :
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml :
tag = ns_clean(child.tag).lower()
if tag == "default" :
default = child.text
self.declareAttribute(attr_class,type,default,title,mode,id)
def importAttributesValuesXML(self,attClass,attvalues_xml):
""" import attributes values from attvalues gexf xml tag attached to nodes or edges"""
atts=[]
for attvalues in attvalues_xml :
for child in attvalues :
tag = ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
id = ""
value = ""
start = ""
startopen=False
end = ""
endopen=False
for attr in attvalue_xml.attrib :
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen = True
atts.append(self.makeAttributeInstance(attClass,id,value,start,end,startopen,endopen))
return atts
class Spells(list):
'''
spells are time periods
spells is a list of dictionaries
a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}
'''
def getXML(self):
spellsXML=etree.Element("spells")
for spell in self :
spellXML=etree.SubElement(spellsXML, "spell")
if "start" in spell.keys() :
spellXML.set("start",spell["start"])
if "end" in spell.keys() :
spellXML.set("end",spell["end"])
return spellsXML
@staticmethod
def importXML(spellsxmltree):
return Spells([ spell.attrib for spell in spellsxmltree])
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self.id =id
self.label=label
self.start=start
self.startopen=startopen
self.end=end
self.endopen=endopen
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
#spells expecting format = [{start:"",end:""},...]
self.spells= spells
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
self.attributes=self._attributes
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :
self._attributes.append(self._graph.attributes.makeAttributeInstance("node",id,value,start,end,startopen,endopen))
def getXML(self) :
# return lxml etree element
try :
nodeXML = etree.Element("node",id=str(self.id),label=self.label)
if not self.start == "":
nodeXML.set("start" if not self.startopen else "startopen",self.start)
if not self.end == "":
nodeXML.set("end" if not self.endopen else "endopen" ,self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
# attributes
if self._attributes :
nodeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells :
print "found spells in node "+self.id
nodeXML.append(self.spells.getXML())
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception, e:
print self.label
print self._attributes
print e
traceback.print_exc()
exit()
def getAttributes(self):
attsFull=[]
for att in self._attributes :
attFull=self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(nodes_xml,graph_obj) :
for child in nodes_xml :
tag = ns_clean(child.tag).lower()
if tag == "node" :
node_xml = child
id = ""
label = ""
start = ""
startopen=False
end = ""
endopen=False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = node_xml.attrib[attr]
if attr == "label" :
label = node_xml.attrib[attr]
if attr == "start" :
start = node_xml.attrib[attr]
if attr == "end" :
start = node_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
if attr == "pid" :
pid = node_xml.attrib[attr]
attvalues_xml = []
spells=[]
for child in node_xml :
tag = ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml.append(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag =="spells" :
spells=Spells.importXML(child)
node_obj = graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)
node_obj._attributes =graph_obj.attributes.importAttributesValuesXML("node",attvalues_xml)
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
def __str__(self):
return self.label
class Edge :
def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self.id =id
self._graph=graph
if self._graph.nodeExists(source) :
self._source=source
self.source=self._source
else :
raise Exception("source "+source+" node unknown, add nodes to graph first")
if self._graph.nodeExists(target) :
self._target=target
self.target=self._target
else:
raise Exception("target "+target+" node unknown, add nodes to graph first")
self.start=start
self.startopen=startopen
self.end=end
self.endopen=endopen
self.weight=weight
self.label=label
self._attributes=[]
self.attributes=self._attributes
# COLOR on edges now supported in GEXF 1.2
self.setColor(r,g,b)
#spells expecting format = [{start:"",end:""},...]
- self.spells= Spells()
+ self.spells= Spells(spells)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :
self._attributes.append(self._graph.attributes.makeAttributeInstance("edge",id,value,start,end,startopen,endopen))
def getXML(self) :
# return lxml etree element
try :
edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
if not self.start == "":
edgeXML.set("start" if not self.startopen else "startopen",self.start)
if not self.end == "":
edgeXML.set("end" if not self.endopen else "endopen" ,self.end)
if not self.weight == "":
edgeXML.set("weight",str(self.weight))
if not self.label == "":
edgeXML.set("label",self.label)
# attributes
if self._attributes :
edgeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells :
- spellsXML.append(self.spells.getXML())
+ #spellsXML = etree.SubElement(edgeXML, "spells")
+ #spellsXML.append(self.spells.getXML())
+ edgeXML.append(self.spells.getXML())
# COLOR on edges is supported in GEXF since 1.2
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.2draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return edgeXML
except Exception, e:
print self._source+" "+self._target
print e
exit()
def getAttributes(self):
attsFull=[]
for att in self._attributes :
attFull=self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(edges_xml,graph_obj) :
for child in edges_xml :
tag = ns_clean(child.tag).lower()
if tag == "edge" :
edge_xml = child
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen=False
end = ""
endopen=False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = edge_xml.attrib[attr]
if attr == "source" :
source = edge_xml.attrib[attr]
if attr == "target" :
target = edge_xml.attrib[attr]
if attr == "weight" :
weight = edge_xml.attrib[attr]
if attr == "start" :
start = edge_xml.attrib[attr]
if attr == "end" :
end = edge_xml.attrib[attr]
if attr == "startopen" :
start = edge_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = edge_xml.attrib[attr]
endopen=True
if attr == "label" :
label = edge_xml.attrib[attr]
spells=[]
attvalues_xml=[]
for child in edge_xml :
tag = ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml.append(child)
if tag =="spells" :
spells=Spells.importXML(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
edge_obj = graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)
edge_obj._attributes=graph_obj.attributes.importAttributesValuesXML("edge",attvalues_xml)
# COLOR on edges is supported in GEXF since 1.2
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class GexfImport :
# class coded by elie Rotenberg, médialab 20/07/2010
# deprecated : import XML codes are now included to the Gexf, Graph, Attribute, Node, Edge classes
def __init__(self, file_like) :
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(file_like, parser)
gexf_xml = tree.getroot()
tag = self.ns_clean(gexf_xml.tag).lower()
if tag <> "gexf" :
self.msg_unexpected_tag("gexf", tag)
return
self.gexf_obj = None
for child in gexf_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "meta" :
meta_xml = child
self.gexf_obj = self.extract_gexf_obj(meta_xml)
if tag == "graph" :
graph_xml = child
if self.gexf_obj == None :
self.msg_unexpected_tag("meta", tag)
return
self.graph_obj = self.extract_graph_obj(graph_xml)
def ns_clean(self, token) :
i = token.find('}')
return token[i+1:]
def msg_unexpected_tag(self, expected, got) :
print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
def extract_gexf_obj(self, meta_xml) :
for child in meta_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "creator" :
creator = child.text
if tag == "description" :
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml) :
type = ""
mode = ""
label = ""
timeformat="double"
for attr in graph_xml.attrib :
attr = attr.lower()
if attr == "defaultedgetype" :
type = graph_xml.attrib[attr]
if attr == "mode" :
mode = graph_xml.attrib[attr]
if attr == "label" :
label = graph_xml.attrib[attr]
if attr == "timeformat" :
timeformat = graph_xml.attrib[attr]
self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)
for child in graph_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attributes" :
attributes_xml = child
self.extract_attributes(attributes_xml)
if tag == "nodes" :
nodes_xml = child
self.extract_nodes(nodes_xml)
if tag == "edges" :
edges_xml = child
self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml) :
attr_class = None
mode = ""
for attr in attributes_xml.attrib :
attr = attr.lower()
if attr == "class" :
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode" :
mode = attributes_xml.attrib[attr]
for child in attributes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attribute" :
attribute_xml = child
self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode) :
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = attribute_xml.attrib[attr]
if attr == "title" :
title = attribute_xml.attrib[attr]
if attr == "type" :
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "default" :
default = child.text
if attr_class == "node" :
self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)
if attr_class == "edge" :
self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)
def extract_nodes(self, nodes_xml) :
for child in nodes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "node" :
node_xml = child
self.extract_node(node_xml)
def extract_node(self, node_xml) :
id = ""
label = ""
start = ""
startopen=False
end = ""
endopen=False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = node_xml.attrib[attr]
if attr == "label" :
label = node_xml.attrib[attr]
if attr == "start" :
start = node_xml.attrib[attr]
if attr == "end" :
start = node_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
if attr == "pid" :
pid = node_xml.attrib[attr]
attvalues_xmls = []
spells=[]
for child in node_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xmls.append(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag =="spells" :
spells=[ spell.attrib for spell in child ]
self.node_obj = self.graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)
for attvalues_xml in attvalues_xmls :
self.extract_node_attvalues(attvalues_xml)
def extract_node_attvalues(self, attvalues_xml) :
for child in attvalues_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
self.extract_node_attvalue(attvalue_xml)
def extract_node_attvalue(self, attvalue_xml) :
id = ""
value = ""
start = ""
startopen=False
end = ""
endopen=False
for attr in attvalue_xml.attrib :
attr = attr.lower()
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
self.node_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)
def extract_edges(self, edges_xml) :
for child in edges_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "edge" :
edge_xml = child
self.extract_edge(edge_xml)
def extract_edge(self, edge_xml) :
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen=False
end = ""
endopen=False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = edge_xml.attrib[attr]
if attr == "source" :
source = edge_xml.attrib[attr]
if attr == "target" :
target = edge_xml.attrib[attr]
if attr == "weight" :
weight = edge_xml.attrib[attr]
if attr == "start" :
start = edge_xml.attrib[attr]
if attr == "end" :
end = edge_xml.attrib[attr]
if attr == "startopen" :
start = edge_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = edge_xml.attrib[attr]
endopen=True
if attr == "label" :
label = edge_xml.attrib[attr]
spells=[]
attvalues_xml=[]
for child in edge_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml = child
if tag =="spells" :
spells=[ spell.attrib for spell in child]
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
self.edge_obj = self.graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)
self.extract_edge_attvalues(attvalues_xml)
def extract_edge_attvalues(self, attvalues_xml) :
for child in attvalues_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
self.extract_edge_attvalue(attvalue_xml)
# def addAttribute(self,id,value,start="",end="") :
def extract_edge_attvalue(self, attvalue_xml) :
id = ""
value = ""
start = ""
startopen=True
end = ""
endopen=True
for attr in attvalue_xml.attrib :
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
startopen = attvalue_xml.attrib[attr]
if attr == "endopen" :
endopen = attvalue_xml.attrib[attr]
self.edge_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)
def gexf(self) :
return self.gexf_obj
|
paulgirard/pygexf
|
12afdc521973f359b23a0c742d69a92a07250a40
|
fix #4
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index 358473b..d071212 100644
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,1065 +1,1065 @@
# -*- coding: utf-8 -*-
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
from lxml import etree
from datetime import date
import itertools
import traceback
# missing features :
# data validation regarding attribute types
# phylogeny
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
def msg_unexpected_tag(expected, got) :
print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
def ns_clean(token) :
i = token.find('}')
return token[i+1:]
class Gexf :
def __init__(self,creator,description):
self.creator=creator
self.description=description
self.graphs=[]
self.xmlns="http://www.gephi.org/gexf/1.2draft"
self.xsi="http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.2draft.xsd"
self.viz="http://www.gexf.net/1.2draft/viz"
self.version="1.2"
def addGraph(self,type,mode,label,timeformat=""):
g = Graph(type,mode,label,timeformat)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified",date.today().isoformat())
etree.SubElement(meta, "creator").text=self.creator
etree.SubElement(meta, "description").text=self.description
for graph in self.graphs :
gexfXML.append(graph.getXML())
return gexfXML
def write(self,file, print_stat=True):
file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8',xml_declaration=True))
if print_stat == True:
self.print_stat()
def print_stat(self) :
for graph in self.graphs :
graph.print_stat()
@staticmethod
def importXML(gexf_file) :
""" import gexf xml meta tags to create a Gexf Object and delegate Graph extraction to Graph class"""
# parse the gexf file
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse((gexf_file), parser)
# start create Gexf Object
gexf_xml = tree.getroot()
tag = ns_clean(gexf_xml.tag).lower()
if tag <> "gexf" :
msg_unexpected_tag("gexf", tag)
return
gexf_obj = None
for child in gexf_xml :
tag = ns_clean(child.tag).lower()
# create a gexf object by importing meta tag
if tag == "meta" :
meta_xml = child
for child in meta_xml :
tag = ns_clean(child.tag).lower()
if tag == "creator" :
creator = child.text
if tag == "description" :
description = child.text
gexf_obj=Gexf(creator=creator, description=description)
# export graph xml through Graph Class
if tag == "graph" :
graph_xml = child
if gexf_obj == None :
msg_unexpected_tag("meta", tag)
return
Graph.importXML(graph_xml,gexf_obj)
return gexf_obj
class Graph :
def __init__(self,type,mode,label,time_format="double",start="",end="") :
# control variable
self.authorizedType=("directed","undirected")
self.authorizedMode=("dynamic","static")
# time format
# Discrete: integer or double
# Continuous : date (yyyy-mm-dd) or dateTime
# default : double
self.authorizedTimeFormat=("integer","double","date","dateTime")
self.defaultTimeFormat="double"
self.defaultType="directed"
self.defaultMode="static"
self.label=label
if type in self.authorizedType :
self.type=type
else :
self.type=self.defaultType
if mode in self.authorizedMode :
self.mode=mode
else :
self.mode=self.defaultMode
if time_format in self.authorizedTimeFormat :
self.time_format=time_format
else :
self.time_format=self.defaultTimeFormat
self.start=start
self.end = end
self._attributes= Attributes()
self.attributes = self._attributes
self._nodes={}
self.nodes=self._nodes
self._edges={}
self.edges=self._edges
def addNode(self,id,label,start="",end="",startopen=False,endopen=False,pid="",r="",g="",b="",spells=[]) :
self._nodes[str(id)]=Node(self,id,label,start,end,pid,r,g,b,spells,startopen,endopen)
return self._nodes[str(id)]
def nodeExists(self,id) :
if id in self._nodes.keys():
return 1
else :
return 0
def addEdge(self,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self._edges[str(id)]=Edge(self,id,source,target,weight,start,end,label,r,g,b,spells,startopen,endopen)
return self._edges[str(id)]
def addNodeAttribute(self,title,defaultValue=None,type="integer",mode="static", force_id="") :
# add to NodeAttributes
return self._attributes.declareAttribute("node",type,defaultValue,title,mode,force_id)
def addDefaultAttributesToNode(self,node) :
""" deprecated """
pass
def checkNodeAttribute(self,id,value,start,end):
"""deprecated"""
pass
# check conformity with type is missing
# if id in self._nodesAttributes.keys() :
# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static", force_id=""):
return self._attributes.declareAttribute("edge",type,defaultValue,title,mode,force_id)
def addDefaultAttributesToEdge(self,edge) :
""" deprecated """
pass
def checkEdgeAttribute(self,id,value,start,end):
"""deprecated """
pass
# # check conformity with type is missing
# if id in self._edgesAttributes.keys() :
# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label,timeformat=self.time_format)
for attributesElement in self.attributes.getAttributesDeclarationXML() :
graphXML.append(attributesElement)
nodesXML = etree.SubElement(graphXML, "nodes")
node_ids=self._nodes.keys()
node_ids.sort()
for id in node_ids :
nodesXML.append(self._nodes[id].getXML())
edgesXML = etree.SubElement(graphXML, "edges")
edge_ids=self._edges.keys()
edge_ids.sort()
for id in edge_ids :
edgesXML.append(self._edges[id].getXML())
return graphXML
@staticmethod
def importXML(graph_xml,gexf_obj) :
""" import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""
# get Graph attributes
type = ""
mode = ""
label = ""
timeformat="double"
for attr in graph_xml.attrib :
attr = attr.lower()
if attr == "defaultedgetype" :
type = graph_xml.attrib[attr]
if attr == "mode" :
mode = graph_xml.attrib[attr]
if attr == "label" :
label = graph_xml.attrib[attr]
if attr == "timeformat" :
timeformat = graph_xml.attrib[attr]
# create and attache the graph object to the Gexf object
graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)
for child in graph_xml :
tag = ns_clean(child.tag).lower()
if tag == "attributes" :
attributes_xml = child
# Delegate Attributes declaration to the attribute object
graph_obj.attributes.importAttributesXML(attributes_xml)
if tag == "nodes" :
nodes_xml = child
# Delegate nodes creation to the Node class
Node.importXML(nodes_xml,graph_obj)
if tag == "edges" :
edges_xml = child
# Delegate edges creation to the Edge class
Edge.importXML(edges_xml,graph_obj)
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Attributes(dict):
"""
attributes=
{
"node" :
{ "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },
"edge" :
{ "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },
}
"""
def __init__(self):
self.type_choices=["integer","string","float","double","boolean","date","URI"]
self.attClass_choices=["node","edge"]
self.mode_choices=["static","dynamic"]
for attClass in self.attClass_choices :
self[attClass]={}
def declareAttribute(self,attClass,type,defaultValue,title="",mode="static",id=None) :
"""
add a new attribute declaration to the graph
"""
if attClass in self.attClass_choices :
# should add quality control here on type and defaultValue
# if no id given generating a numerical one based on dict length
if not id :
id = str(len(self[attClass]))
self[attClass][id]={"id":id,"type":type,"defaultValue":defaultValue,"mode":mode,"title":title}
return id
else :
raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(type_choices))
def makeAttributeInstance(self,attClass,id=None,value=None,start=None,end=None,startopen=False,endopen=False) :
"""
generate an attribute to be include to a node or edge.
copied from the declared attributes, thus any attribute has to be declared first
"""
if attClass in self.attClass_choices :
if id in self[attClass].keys() :
att={"id":id}
att["value"]=value if value else self[attClass][id].defaultValue
if self[attClass][id]["mode"]=="dynamic" and start or end :
# start & end will be discarded if the mode is set to static
if start :
att["start"]=start
if startopen :
att["startopen"]=startopen
if end :
att["end"]=end
if endopen :
att["endopen"]=endopen
return att
else :
raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute"%(id,))
else :
raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(self.type_choices))
def getAttributesDeclarationXML(self) :
""" generate attributes declaration XML """
# return lxml etree element
allAttributesXML=[]
if len(self)>0 :
# iter on node and then edge atts
for attClass,atts in self.iteritems() :
# group by mode
key_mode=lambda att : att["mode"]
atts_sorted_by_mode=sorted(atts.values(),key=key_mode,reverse=True)
for mode,atts in itertools.groupby(atts_sorted_by_mode,key_mode) :
# generate on attributes by mode
attributesXML = etree.Element("attributes")
attributesXML.set("class",attClass)
attributesXML.set("mode",mode)
# generate attribute by id order
for att in sorted(atts,key=lambda att: att["id"]) :
attributeXML=etree.SubElement(attributesXML, "attribute")
attributeXML.set("id",str(att["id"]))
attributeXML.set("title",att["title"])
attributeXML.set("type",att["type"])
if att["defaultValue"] :
etree.SubElement(attributeXML, "default").text=att["defaultValue"]
allAttributesXML.append(attributesXML)
return allAttributesXML
@staticmethod
def getAttributesXML(atts) :
""" get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""
if len(atts)>0:
attValuesXML = etree.Element("attvalues")
for att in atts :
attValueXML=etree.SubElement(attValuesXML, "attvalue")
attValueXML.set("for",str(att["id"]))
attValueXML.set("value",att["value"])
if "start" in att.keys() and not att["start"]=="" :
attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen",att["start"])
if "end" in att.keys() and not att["end"]=="" :
attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen",att["end"])
return attValuesXML
else :
return None
def importAttributesXML(self,attributes_xml):
""" get XML attributes declaration of a graph gexf"""
attr_class = None
mode = ""
for attr in attributes_xml.attrib :
attr = attr.lower()
if attr == "class" :
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode" :
mode = attributes_xml.attrib[attr]
for child in attributes_xml :
tag = ns_clean(child.tag).lower()
if tag == "attribute" :
attribute_xml = child
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = attribute_xml.attrib[attr]
if attr == "title" :
title = attribute_xml.attrib[attr]
if attr == "type" :
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml :
tag = ns_clean(child.tag).lower()
if tag == "default" :
default = child.text
self.declareAttribute(attr_class,type,default,title,mode,id)
def importAttributesValuesXML(self,attClass,attvalues_xml):
""" import attributes values from attvalues gexf xml tag attached to nodes or edges"""
atts=[]
for attvalues in attvalues_xml :
for child in attvalues :
tag = ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
id = ""
value = ""
start = ""
startopen=False
end = ""
endopen=False
for attr in attvalue_xml.attrib :
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen = True
atts.append(self.makeAttributeInstance(attClass,id,value,start,end,startopen,endopen))
return atts
class Spells(list):
'''
spells are time periods
spells is a list of dictionaries
a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}
'''
def getXML(self):
spellsXML=etree.Element("spells")
for spell in self :
spellXML=etree.SubElement(spellsXML, "spell")
if "start" in spell.keys() :
spellXML.set("start",spell["start"])
if "end" in spell.keys() :
spellXML.set("end",spell["end"])
return spellsXML
@staticmethod
def importXML(spellsxmltree):
return Spells([ spell.attrib for spell in spellsxmltree])
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self.id =id
self.label=label
self.start=start
self.startopen=startopen
self.end=end
self.endopen=endopen
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
#spells expecting format = [{start:"",end:""},...]
self.spells= spells
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
self.attributes=self._attributes
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :
- self._attributes.append(makeAttributeInstance(self,"node",id,value,start,end,startopen,endopen))
+ self._attributes.append(self._graph.attributes.makeAttributeInstance("node",id,value,start,end,startopen,endopen))
def getXML(self) :
# return lxml etree element
try :
nodeXML = etree.Element("node",id=str(self.id),label=self.label)
if not self.start == "":
nodeXML.set("start" if not self.startopen else "startopen",self.start)
if not self.end == "":
nodeXML.set("end" if not self.endopen else "endopen" ,self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
# attributes
if self._attributes :
nodeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells :
print "found spells in node "+self.id
nodeXML.append(self.spells.getXML())
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception, e:
print self.label
print self._attributes
print e
traceback.print_exc()
exit()
def getAttributes(self):
attsFull=[]
for att in self._attributes :
attFull=self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(nodes_xml,graph_obj) :
for child in nodes_xml :
tag = ns_clean(child.tag).lower()
if tag == "node" :
node_xml = child
id = ""
label = ""
start = ""
startopen=False
end = ""
endopen=False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = node_xml.attrib[attr]
if attr == "label" :
label = node_xml.attrib[attr]
if attr == "start" :
start = node_xml.attrib[attr]
if attr == "end" :
start = node_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
if attr == "pid" :
pid = node_xml.attrib[attr]
attvalues_xml = []
spells=[]
for child in node_xml :
tag = ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml.append(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag =="spells" :
spells=Spells.importXML(child)
node_obj = graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)
node_obj._attributes =graph_obj.attributes.importAttributesValuesXML("node",attvalues_xml)
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
def __str__(self):
return self.label
class Edge :
def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self.id =id
self._graph=graph
if self._graph.nodeExists(source) :
self._source=source
self.source=self._source
else :
raise Exception("source "+source+" node unknown, add nodes to graph first")
if self._graph.nodeExists(target) :
self._target=target
self.target=self._target
else:
raise Exception("target "+target+" node unknown, add nodes to graph first")
self.start=start
self.startopen=startopen
self.end=end
self.endopen=endopen
self.weight=weight
self.label=label
self._attributes=[]
self.attributes=self._attributes
# COLOR on edges now supported in GEXF 1.2
self.setColor(r,g,b)
#spells expecting format = [{start:"",end:""},...]
self.spells= Spells()
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :
- self._attributes.append(makeAttributeInstance(self,"node",id,value,start,end,startopen,endopen))
+ self._attributes.append(self._graph.attributes.makeAttributeInstance("edge",id,value,start,end,startopen,endopen))
def getXML(self) :
# return lxml etree element
try :
edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
if not self.start == "":
edgeXML.set("start" if not self.startopen else "startopen",self.start)
if not self.end == "":
edgeXML.set("end" if not self.endopen else "endopen" ,self.end)
if not self.weight == "":
edgeXML.set("weight",str(self.weight))
if not self.label == "":
edgeXML.set("label",self.label)
# attributes
if self._attributes :
edgeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells :
spellsXML.append(self.spells.getXML())
# COLOR on edges is supported in GEXF since 1.2
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.2draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return edgeXML
except Exception, e:
print self._source+" "+self._target
print e
exit()
def getAttributes(self):
attsFull=[]
for att in self._attributes :
attFull=self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(edges_xml,graph_obj) :
for child in edges_xml :
tag = ns_clean(child.tag).lower()
if tag == "edge" :
edge_xml = child
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen=False
end = ""
endopen=False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = edge_xml.attrib[attr]
if attr == "source" :
source = edge_xml.attrib[attr]
if attr == "target" :
target = edge_xml.attrib[attr]
if attr == "weight" :
weight = edge_xml.attrib[attr]
if attr == "start" :
start = edge_xml.attrib[attr]
if attr == "end" :
end = edge_xml.attrib[attr]
if attr == "startopen" :
start = edge_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = edge_xml.attrib[attr]
endopen=True
if attr == "label" :
label = edge_xml.attrib[attr]
spells=[]
attvalues_xml=[]
for child in edge_xml :
tag = ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml.append(child)
if tag =="spells" :
spells=Spells.importXML(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
edge_obj = graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)
edge_obj._attributes=graph_obj.attributes.importAttributesValuesXML("edge",attvalues_xml)
# COLOR on edges is supported in GEXF since 1.2
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class GexfImport :
# class coded by elie Rotenberg, médialab 20/07/2010
# deprecated : import XML codes are now included to the Gexf, Graph, Attribute, Node, Edge classes
def __init__(self, file_like) :
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(file_like, parser)
gexf_xml = tree.getroot()
tag = self.ns_clean(gexf_xml.tag).lower()
if tag <> "gexf" :
self.msg_unexpected_tag("gexf", tag)
return
self.gexf_obj = None
for child in gexf_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "meta" :
meta_xml = child
self.gexf_obj = self.extract_gexf_obj(meta_xml)
if tag == "graph" :
graph_xml = child
if self.gexf_obj == None :
self.msg_unexpected_tag("meta", tag)
return
self.graph_obj = self.extract_graph_obj(graph_xml)
def ns_clean(self, token) :
i = token.find('}')
return token[i+1:]
def msg_unexpected_tag(self, expected, got) :
print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
def extract_gexf_obj(self, meta_xml) :
for child in meta_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "creator" :
creator = child.text
if tag == "description" :
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml) :
type = ""
mode = ""
label = ""
timeformat="double"
for attr in graph_xml.attrib :
attr = attr.lower()
if attr == "defaultedgetype" :
type = graph_xml.attrib[attr]
if attr == "mode" :
mode = graph_xml.attrib[attr]
if attr == "label" :
label = graph_xml.attrib[attr]
if attr == "timeformat" :
timeformat = graph_xml.attrib[attr]
self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)
for child in graph_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attributes" :
attributes_xml = child
self.extract_attributes(attributes_xml)
if tag == "nodes" :
nodes_xml = child
self.extract_nodes(nodes_xml)
if tag == "edges" :
edges_xml = child
self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml) :
attr_class = None
mode = ""
for attr in attributes_xml.attrib :
attr = attr.lower()
if attr == "class" :
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode" :
mode = attributes_xml.attrib[attr]
for child in attributes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attribute" :
attribute_xml = child
self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode) :
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = attribute_xml.attrib[attr]
if attr == "title" :
title = attribute_xml.attrib[attr]
if attr == "type" :
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "default" :
default = child.text
if attr_class == "node" :
self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)
if attr_class == "edge" :
self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)
def extract_nodes(self, nodes_xml) :
for child in nodes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "node" :
node_xml = child
self.extract_node(node_xml)
def extract_node(self, node_xml) :
id = ""
label = ""
start = ""
startopen=False
end = ""
endopen=False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = node_xml.attrib[attr]
if attr == "label" :
label = node_xml.attrib[attr]
if attr == "start" :
start = node_xml.attrib[attr]
if attr == "end" :
start = node_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
if attr == "pid" :
pid = node_xml.attrib[attr]
attvalues_xmls = []
spells=[]
for child in node_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xmls.append(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
if tag =="spells" :
spells=[ spell.attrib for spell in child ]
self.node_obj = self.graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)
for attvalues_xml in attvalues_xmls :
self.extract_node_attvalues(attvalues_xml)
def extract_node_attvalues(self, attvalues_xml) :
for child in attvalues_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
self.extract_node_attvalue(attvalue_xml)
def extract_node_attvalue(self, attvalue_xml) :
id = ""
value = ""
start = ""
startopen=False
end = ""
endopen=False
for attr in attvalue_xml.attrib :
attr = attr.lower()
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
self.node_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)
def extract_edges(self, edges_xml) :
for child in edges_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "edge" :
edge_xml = child
self.extract_edge(edge_xml)
def extract_edge(self, edge_xml) :
id = ""
source = ""
target = ""
weight = ""
start = ""
startopen=False
end = ""
endopen=False
label = ""
r = ""
g = ""
b = ""
for attr in edge_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = edge_xml.attrib[attr]
if attr == "source" :
source = edge_xml.attrib[attr]
if attr == "target" :
target = edge_xml.attrib[attr]
if attr == "weight" :
weight = edge_xml.attrib[attr]
if attr == "start" :
start = edge_xml.attrib[attr]
if attr == "end" :
end = edge_xml.attrib[attr]
if attr == "startopen" :
start = edge_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = edge_xml.attrib[attr]
endopen=True
if attr == "label" :
label = edge_xml.attrib[attr]
spells=[]
attvalues_xml=[]
for child in edge_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml = child
if tag =="spells" :
spells=[ spell.attrib for spell in child]
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
self.edge_obj = self.graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)
self.extract_edge_attvalues(attvalues_xml)
def extract_edge_attvalues(self, attvalues_xml) :
for child in attvalues_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
self.extract_edge_attvalue(attvalue_xml)
# def addAttribute(self,id,value,start="",end="") :
def extract_edge_attvalue(self, attvalue_xml) :
id = ""
value = ""
start = ""
startopen=True
end = ""
endopen=True
for attr in attvalue_xml.attrib :
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
startopen = attvalue_xml.attrib[attr]
if attr == "endopen" :
endopen = attvalue_xml.attrib[attr]
self.edge_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)
def gexf(self) :
return self.gexf_obj
|
paulgirard/pygexf
|
71f6433a17552778ebc93e0c3fbc592027698dff
|
Fix for issue #6 https://github.com/paulgirard/pygexf/issues/6 Don't write stats to stdout or make it optional
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index 3105d5b..358473b 100644
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,580 +1,581 @@
# -*- coding: utf-8 -*-
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
from lxml import etree
from datetime import date
import itertools
import traceback
# missing features :
# data validation regarding attribute types
# phylogeny
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
def msg_unexpected_tag(expected, got) :
print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
def ns_clean(token) :
i = token.find('}')
return token[i+1:]
class Gexf :
def __init__(self,creator,description):
self.creator=creator
self.description=description
self.graphs=[]
self.xmlns="http://www.gephi.org/gexf/1.2draft"
self.xsi="http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.2draft.xsd"
self.viz="http://www.gexf.net/1.2draft/viz"
self.version="1.2"
def addGraph(self,type,mode,label,timeformat=""):
g = Graph(type,mode,label,timeformat)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified",date.today().isoformat())
etree.SubElement(meta, "creator").text=self.creator
etree.SubElement(meta, "description").text=self.description
for graph in self.graphs :
gexfXML.append(graph.getXML())
return gexfXML
- def write(self,file):
+ def write(self,file, print_stat=True):
file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8',xml_declaration=True))
- self.print_stat()
+ if print_stat == True:
+ self.print_stat()
def print_stat(self) :
for graph in self.graphs :
graph.print_stat()
@staticmethod
def importXML(gexf_file) :
""" import gexf xml meta tags to create a Gexf Object and delegate Graph extraction to Graph class"""
# parse the gexf file
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse((gexf_file), parser)
# start create Gexf Object
gexf_xml = tree.getroot()
tag = ns_clean(gexf_xml.tag).lower()
if tag <> "gexf" :
msg_unexpected_tag("gexf", tag)
return
gexf_obj = None
for child in gexf_xml :
tag = ns_clean(child.tag).lower()
# create a gexf object by importing meta tag
if tag == "meta" :
meta_xml = child
for child in meta_xml :
tag = ns_clean(child.tag).lower()
if tag == "creator" :
creator = child.text
if tag == "description" :
description = child.text
gexf_obj=Gexf(creator=creator, description=description)
# export graph xml through Graph Class
if tag == "graph" :
graph_xml = child
if gexf_obj == None :
msg_unexpected_tag("meta", tag)
return
Graph.importXML(graph_xml,gexf_obj)
return gexf_obj
class Graph :
def __init__(self,type,mode,label,time_format="double",start="",end="") :
# control variable
self.authorizedType=("directed","undirected")
self.authorizedMode=("dynamic","static")
# time format
# Discrete: integer or double
# Continuous : date (yyyy-mm-dd) or dateTime
# default : double
self.authorizedTimeFormat=("integer","double","date","dateTime")
self.defaultTimeFormat="double"
self.defaultType="directed"
self.defaultMode="static"
self.label=label
if type in self.authorizedType :
self.type=type
else :
self.type=self.defaultType
if mode in self.authorizedMode :
self.mode=mode
else :
self.mode=self.defaultMode
if time_format in self.authorizedTimeFormat :
self.time_format=time_format
else :
self.time_format=self.defaultTimeFormat
self.start=start
self.end = end
self._attributes= Attributes()
self.attributes = self._attributes
self._nodes={}
self.nodes=self._nodes
self._edges={}
self.edges=self._edges
def addNode(self,id,label,start="",end="",startopen=False,endopen=False,pid="",r="",g="",b="",spells=[]) :
self._nodes[str(id)]=Node(self,id,label,start,end,pid,r,g,b,spells,startopen,endopen)
return self._nodes[str(id)]
def nodeExists(self,id) :
if id in self._nodes.keys():
return 1
else :
return 0
def addEdge(self,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self._edges[str(id)]=Edge(self,id,source,target,weight,start,end,label,r,g,b,spells,startopen,endopen)
return self._edges[str(id)]
def addNodeAttribute(self,title,defaultValue=None,type="integer",mode="static", force_id="") :
# add to NodeAttributes
return self._attributes.declareAttribute("node",type,defaultValue,title,mode,force_id)
def addDefaultAttributesToNode(self,node) :
""" deprecated """
pass
def checkNodeAttribute(self,id,value,start,end):
"""deprecated"""
pass
# check conformity with type is missing
# if id in self._nodesAttributes.keys() :
# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static", force_id=""):
return self._attributes.declareAttribute("edge",type,defaultValue,title,mode,force_id)
def addDefaultAttributesToEdge(self,edge) :
""" deprecated """
pass
def checkEdgeAttribute(self,id,value,start,end):
"""deprecated """
pass
# # check conformity with type is missing
# if id in self._edgesAttributes.keys() :
# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
# return 1
# else :
# raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label,timeformat=self.time_format)
for attributesElement in self.attributes.getAttributesDeclarationXML() :
graphXML.append(attributesElement)
nodesXML = etree.SubElement(graphXML, "nodes")
node_ids=self._nodes.keys()
node_ids.sort()
for id in node_ids :
nodesXML.append(self._nodes[id].getXML())
edgesXML = etree.SubElement(graphXML, "edges")
edge_ids=self._edges.keys()
edge_ids.sort()
for id in edge_ids :
edgesXML.append(self._edges[id].getXML())
return graphXML
@staticmethod
def importXML(graph_xml,gexf_obj) :
""" import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""
# get Graph attributes
type = ""
mode = ""
label = ""
timeformat="double"
for attr in graph_xml.attrib :
attr = attr.lower()
if attr == "defaultedgetype" :
type = graph_xml.attrib[attr]
if attr == "mode" :
mode = graph_xml.attrib[attr]
if attr == "label" :
label = graph_xml.attrib[attr]
if attr == "timeformat" :
timeformat = graph_xml.attrib[attr]
# create and attache the graph object to the Gexf object
graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)
for child in graph_xml :
tag = ns_clean(child.tag).lower()
if tag == "attributes" :
attributes_xml = child
# Delegate Attributes declaration to the attribute object
graph_obj.attributes.importAttributesXML(attributes_xml)
if tag == "nodes" :
nodes_xml = child
# Delegate nodes creation to the Node class
Node.importXML(nodes_xml,graph_obj)
if tag == "edges" :
edges_xml = child
# Delegate edges creation to the Edge class
Edge.importXML(edges_xml,graph_obj)
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Attributes(dict):
"""
attributes=
{
"node" :
{ "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },
"edge" :
{ "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },
}
"""
def __init__(self):
self.type_choices=["integer","string","float","double","boolean","date","URI"]
self.attClass_choices=["node","edge"]
self.mode_choices=["static","dynamic"]
for attClass in self.attClass_choices :
self[attClass]={}
def declareAttribute(self,attClass,type,defaultValue,title="",mode="static",id=None) :
"""
add a new attribute declaration to the graph
"""
if attClass in self.attClass_choices :
# should add quality control here on type and defaultValue
# if no id given generating a numerical one based on dict length
if not id :
id = str(len(self[attClass]))
self[attClass][id]={"id":id,"type":type,"defaultValue":defaultValue,"mode":mode,"title":title}
return id
else :
raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(type_choices))
def makeAttributeInstance(self,attClass,id=None,value=None,start=None,end=None,startopen=False,endopen=False) :
"""
generate an attribute to be include to a node or edge.
copied from the declared attributes, thus any attribute has to be declared first
"""
if attClass in self.attClass_choices :
if id in self[attClass].keys() :
att={"id":id}
att["value"]=value if value else self[attClass][id].defaultValue
if self[attClass][id]["mode"]=="dynamic" and start or end :
# start & end will be discarded if the mode is set to static
if start :
att["start"]=start
if startopen :
att["startopen"]=startopen
if end :
att["end"]=end
if endopen :
att["endopen"]=endopen
return att
else :
raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute"%(id,))
else :
raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(self.type_choices))
def getAttributesDeclarationXML(self) :
""" generate attributes declaration XML """
# return lxml etree element
allAttributesXML=[]
if len(self)>0 :
# iter on node and then edge atts
for attClass,atts in self.iteritems() :
# group by mode
key_mode=lambda att : att["mode"]
atts_sorted_by_mode=sorted(atts.values(),key=key_mode,reverse=True)
for mode,atts in itertools.groupby(atts_sorted_by_mode,key_mode) :
# generate on attributes by mode
attributesXML = etree.Element("attributes")
attributesXML.set("class",attClass)
attributesXML.set("mode",mode)
# generate attribute by id order
for att in sorted(atts,key=lambda att: att["id"]) :
attributeXML=etree.SubElement(attributesXML, "attribute")
attributeXML.set("id",str(att["id"]))
attributeXML.set("title",att["title"])
attributeXML.set("type",att["type"])
if att["defaultValue"] :
etree.SubElement(attributeXML, "default").text=att["defaultValue"]
allAttributesXML.append(attributesXML)
return allAttributesXML
@staticmethod
def getAttributesXML(atts) :
""" get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""
if len(atts)>0:
attValuesXML = etree.Element("attvalues")
for att in atts :
attValueXML=etree.SubElement(attValuesXML, "attvalue")
attValueXML.set("for",str(att["id"]))
attValueXML.set("value",att["value"])
if "start" in att.keys() and not att["start"]=="" :
attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen",att["start"])
if "end" in att.keys() and not att["end"]=="" :
attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen",att["end"])
return attValuesXML
else :
return None
def importAttributesXML(self,attributes_xml):
""" get XML attributes declaration of a graph gexf"""
attr_class = None
mode = ""
for attr in attributes_xml.attrib :
attr = attr.lower()
if attr == "class" :
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode" :
mode = attributes_xml.attrib[attr]
for child in attributes_xml :
tag = ns_clean(child.tag).lower()
if tag == "attribute" :
attribute_xml = child
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = attribute_xml.attrib[attr]
if attr == "title" :
title = attribute_xml.attrib[attr]
if attr == "type" :
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml :
tag = ns_clean(child.tag).lower()
if tag == "default" :
default = child.text
self.declareAttribute(attr_class,type,default,title,mode,id)
def importAttributesValuesXML(self,attClass,attvalues_xml):
""" import attributes values from attvalues gexf xml tag attached to nodes or edges"""
atts=[]
for attvalues in attvalues_xml :
for child in attvalues :
tag = ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
id = ""
value = ""
start = ""
startopen=False
end = ""
endopen=False
for attr in attvalue_xml.attrib :
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen = True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen = True
atts.append(self.makeAttributeInstance(attClass,id,value,start,end,startopen,endopen))
return atts
class Spells(list):
'''
spells are time periods
spells is a list of dictionaries
a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}
'''
def getXML(self):
spellsXML=etree.Element("spells")
for spell in self :
spellXML=etree.SubElement(spellsXML, "spell")
if "start" in spell.keys() :
spellXML.set("start",spell["start"])
if "end" in spell.keys() :
spellXML.set("end",spell["end"])
return spellsXML
@staticmethod
def importXML(spellsxmltree):
return Spells([ spell.attrib for spell in spellsxmltree])
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
self.id =id
self.label=label
self.start=start
self.startopen=startopen
self.end=end
self.endopen=endopen
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
#spells expecting format = [{start:"",end:""},...]
self.spells= spells
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
self.attributes=self._attributes
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :
self._attributes.append(makeAttributeInstance(self,"node",id,value,start,end,startopen,endopen))
def getXML(self) :
# return lxml etree element
try :
nodeXML = etree.Element("node",id=str(self.id),label=self.label)
if not self.start == "":
nodeXML.set("start" if not self.startopen else "startopen",self.start)
if not self.end == "":
nodeXML.set("end" if not self.endopen else "endopen" ,self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
# attributes
if self._attributes :
nodeXML.append(Attributes.getAttributesXML(self._attributes))
# spells
if self.spells :
print "found spells in node "+self.id
nodeXML.append(self.spells.getXML())
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception, e:
print self.label
print self._attributes
print e
traceback.print_exc()
exit()
def getAttributes(self):
attsFull=[]
for att in self._attributes :
attFull=self._graph.attributes["node"][att["id"]].copy()
attFull.update(att)
attsFull.append(attFull)
return attsFull
@staticmethod
def importXML(nodes_xml,graph_obj) :
for child in nodes_xml :
tag = ns_clean(child.tag).lower()
if tag == "node" :
node_xml = child
id = ""
label = ""
start = ""
startopen=False
end = ""
endopen=False
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = node_xml.attrib[attr]
if attr == "label" :
label = node_xml.attrib[attr]
if attr == "start" :
start = node_xml.attrib[attr]
if attr == "end" :
start = node_xml.attrib[attr]
if attr == "startopen" :
start = attvalue_xml.attrib[attr]
startopen=True
if attr == "endopen" :
end = attvalue_xml.attrib[attr]
endopen=True
if attr == "pid" :
pid = node_xml.attrib[attr]
attvalues_xml = []
spells=[]
for child in node_xml :
|
paulgirard/pygexf
|
39fa1d4238169c151966b2359f602c0a3decd82d
|
pygexf now supports 1.2 + lot of refactoring (see comments) + added a new test script
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index a61b4e4..3105d5b 100644
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,627 +1,1064 @@
# -*- coding: utf-8 -*-
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
from lxml import etree
-from datetime import *
+from datetime import date
+import itertools
+import traceback
# missing features :
- # load, validate, modify existing gexf file
- # slices / phylogeny / ...
+ # data validation regarding attribute types
+ # phylogeny
+
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
- # add a test based on existing example from gexf.net
- # add modification accessors like setStart ...
- # factorize attribute managment by creating an attribute class
- # add a test code utility to check that code will not use _variable outside objects
+def msg_unexpected_tag(expected, got) :
+ print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
+
+def ns_clean(token) :
+ i = token.find('}')
+ return token[i+1:]
+
class Gexf :
- def __init__(self,creator,description):
- self.creator=creator
- self.description=description
- self.graphs=[]
- self.xmlns="http://www.gephi.org/gexf/1.1draft"
- self.xsi="http://www.w3.org/2001/XMLSchema-instance"
- self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.1draft.xsd"
- self.viz="http://www.gexf.net/1.1draft/viz"
- self.version="1.1"
-
- def addGraph(self,type,mode,label):
- g = Graph(type,mode,label)
- self.graphs.append(g)
- return g
-
- def getXML(self):
- gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
-# gexfXML.set("xmlnsxsi",)
- gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
- meta = etree.SubElement(gexfXML, "meta")
- meta.set("lastmodified",datetime.now().isoformat())
- etree.SubElement(meta, "creator").text=self.creator
- etree.SubElement(meta, "description").text=self.description
- for graph in self.graphs :
- gexfXML.append(graph.getXML())
-
- return gexfXML
-
- def write(self,file):
- file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8'))
- self.print_stat()
-
- def print_stat(self) :
- for graph in self.graphs :
- graph.print_stat()
-
-
+ def __init__(self,creator,description):
+ self.creator=creator
+ self.description=description
+ self.graphs=[]
+ self.xmlns="http://www.gephi.org/gexf/1.2draft"
+ self.xsi="http://www.w3.org/2001/XMLSchema-instance"
+ self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.2draft.xsd"
+ self.viz="http://www.gexf.net/1.2draft/viz"
+ self.version="1.2"
+
+ def addGraph(self,type,mode,label,timeformat=""):
+ g = Graph(type,mode,label,timeformat)
+ self.graphs.append(g)
+ return g
+
+ def getXML(self):
+ gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
+# gexfXML.set("xmlnsxsi",)
+ gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
+ meta = etree.SubElement(gexfXML, "meta")
+ meta.set("lastmodified",date.today().isoformat())
+ etree.SubElement(meta, "creator").text=self.creator
+ etree.SubElement(meta, "description").text=self.description
+ for graph in self.graphs :
+ gexfXML.append(graph.getXML())
+
+ return gexfXML
+
+ def write(self,file):
+ file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8',xml_declaration=True))
+ self.print_stat()
+
+ def print_stat(self) :
+ for graph in self.graphs :
+ graph.print_stat()
+
+ @staticmethod
+ def importXML(gexf_file) :
+ """ import gexf xml meta tags to create a Gexf Object and delegate Graph extraction to Graph class"""
+ # parse the gexf file
+ parser = etree.XMLParser(ns_clean=True)
+ tree = etree.parse((gexf_file), parser)
+ # start create Gexf Object
+ gexf_xml = tree.getroot()
+ tag = ns_clean(gexf_xml.tag).lower()
+ if tag <> "gexf" :
+ msg_unexpected_tag("gexf", tag)
+ return
+ gexf_obj = None
+ for child in gexf_xml :
+ tag = ns_clean(child.tag).lower()
+ # create a gexf object by importing meta tag
+ if tag == "meta" :
+ meta_xml = child
+ for child in meta_xml :
+ tag = ns_clean(child.tag).lower()
+ if tag == "creator" :
+ creator = child.text
+ if tag == "description" :
+ description = child.text
+ gexf_obj=Gexf(creator=creator, description=description)
+ # export graph xml through Graph Class
+ if tag == "graph" :
+ graph_xml = child
+ if gexf_obj == None :
+ msg_unexpected_tag("meta", tag)
+ return
+ Graph.importXML(graph_xml,gexf_obj)
+ return gexf_obj
class Graph :
+
+ def __init__(self,type,mode,label,time_format="double",start="",end="") :
+
+ # control variable
+ self.authorizedType=("directed","undirected")
+ self.authorizedMode=("dynamic","static")
+ # time format
+ # Discrete: integer or double
+ # Continuous : date (yyyy-mm-dd) or dateTime
+ # default : double
+ self.authorizedTimeFormat=("integer","double","date","dateTime")
+
+ self.defaultTimeFormat="double"
+ self.defaultType="directed"
+ self.defaultMode="static"
+
+ self.label=label
+
+ if type in self.authorizedType :
+ self.type=type
+ else :
+ self.type=self.defaultType
+ if mode in self.authorizedMode :
+ self.mode=mode
+ else :
+ self.mode=self.defaultMode
+
+ if time_format in self.authorizedTimeFormat :
+ self.time_format=time_format
+ else :
+ self.time_format=self.defaultTimeFormat
+
+ self.start=start
+ self.end = end
+
+
+ self._attributes= Attributes()
+ self.attributes = self._attributes
+ self._nodes={}
+ self.nodes=self._nodes
+ self._edges={}
+ self.edges=self._edges
+
+ def addNode(self,id,label,start="",end="",startopen=False,endopen=False,pid="",r="",g="",b="",spells=[]) :
+ self._nodes[str(id)]=Node(self,id,label,start,end,pid,r,g,b,spells,startopen,endopen)
+ return self._nodes[str(id)]
+
+ def nodeExists(self,id) :
+ if id in self._nodes.keys():
+ return 1
+ else :
+ return 0
+
+ def addEdge(self,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
+ self._edges[str(id)]=Edge(self,id,source,target,weight,start,end,label,r,g,b,spells,startopen,endopen)
+ return self._edges[str(id)]
+
+ def addNodeAttribute(self,title,defaultValue=None,type="integer",mode="static", force_id="") :
+ # add to NodeAttributes
+ return self._attributes.declareAttribute("node",type,defaultValue,title,mode,force_id)
+
+ def addDefaultAttributesToNode(self,node) :
+ """ deprecated """
+ pass
+
+ def checkNodeAttribute(self,id,value,start,end):
+ """deprecated"""
+ pass
+ # check conformity with type is missing
+ # if id in self._nodesAttributes.keys() :
+# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
+# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
+# return 1
+# else :
+# raise Exception("attribute id unknown. Add Attribute to graph first")
+
+
+ def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static", force_id=""):
+ return self._attributes.declareAttribute("edge",type,defaultValue,title,mode,force_id)
+
+
+ def addDefaultAttributesToEdge(self,edge) :
+ """ deprecated """
+ pass
+
+ def checkEdgeAttribute(self,id,value,start,end):
+ """deprecated """
+ pass
+# # check conformity with type is missing
+# if id in self._edgesAttributes.keys() :
+# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
+# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
+# return 1
+# else :
+# raise Exception("attribute id unknown. Add Attribute to graph first")
+
+
+ def getXML(self) :
+ # return lxml etree element
+ graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label,timeformat=self.time_format)
+
+ for attributesElement in self.attributes.getAttributesDeclarationXML() :
+ graphXML.append(attributesElement)
+
+ nodesXML = etree.SubElement(graphXML, "nodes")
+ node_ids=self._nodes.keys()
+ node_ids.sort()
+ for id in node_ids :
+ nodesXML.append(self._nodes[id].getXML())
+
+ edgesXML = etree.SubElement(graphXML, "edges")
+ edge_ids=self._edges.keys()
+ edge_ids.sort()
+ for id in edge_ids :
+ edgesXML.append(self._edges[id].getXML())
+
+ return graphXML
+
+ @staticmethod
+ def importXML(graph_xml,gexf_obj) :
+ """ import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""
+ # get Graph attributes
+ type = ""
+ mode = ""
+ label = ""
+ timeformat="double"
+ for attr in graph_xml.attrib :
+ attr = attr.lower()
+ if attr == "defaultedgetype" :
+ type = graph_xml.attrib[attr]
+ if attr == "mode" :
+ mode = graph_xml.attrib[attr]
+ if attr == "label" :
+ label = graph_xml.attrib[attr]
+ if attr == "timeformat" :
+ timeformat = graph_xml.attrib[attr]
+ # create and attache the graph object to the Gexf object
+ graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)
+
+ for child in graph_xml :
+ tag = ns_clean(child.tag).lower()
+
+ if tag == "attributes" :
+ attributes_xml = child
+ # Delegate Attributes declaration to the attribute object
+ graph_obj.attributes.importAttributesXML(attributes_xml)
+
+ if tag == "nodes" :
+ nodes_xml = child
+ # Delegate nodes creation to the Node class
+ Node.importXML(nodes_xml,graph_obj)
+ if tag == "edges" :
+ edges_xml = child
+ # Delegate edges creation to the Edge class
+ Edge.importXML(edges_xml,graph_obj)
+
+ def print_stat(self):
+ print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
+ print "number of nodes : "+str(len(self._nodes))
+ print "number of edges : "+str(len(self._edges))
+
+class Attributes(dict):
+ """
+ attributes=
+ {
+ "node" :
+ { "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },
+ "edge" :
+ { "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },
+ }
+
+
+ """
+ def __init__(self):
+ self.type_choices=["integer","string","float","double","boolean","date","URI"]
+ self.attClass_choices=["node","edge"]
+ self.mode_choices=["static","dynamic"]
+ for attClass in self.attClass_choices :
+ self[attClass]={}
+
+ def declareAttribute(self,attClass,type,defaultValue,title="",mode="static",id=None) :
+ """
+ add a new attribute declaration to the graph
+ """
+ if attClass in self.attClass_choices :
+ # should add quality control here on type and defaultValue
+ # if no id given generating a numerical one based on dict length
+ if not id :
+ id = str(len(self[attClass]))
+ self[attClass][id]={"id":id,"type":type,"defaultValue":defaultValue,"mode":mode,"title":title}
+ return id
+ else :
+ raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(type_choices))
+
+
+ def makeAttributeInstance(self,attClass,id=None,value=None,start=None,end=None,startopen=False,endopen=False) :
+ """
+ generate an attribute to be include to a node or edge.
+ copied from the declared attributes, thus any attribute has to be declared first
+ """
+ if attClass in self.attClass_choices :
+ if id in self[attClass].keys() :
+ att={"id":id}
+ att["value"]=value if value else self[attClass][id].defaultValue
+ if self[attClass][id]["mode"]=="dynamic" and start or end :
+ # start & end will be discarded if the mode is set to static
+ if start :
+ att["start"]=start
+ if startopen :
+ att["startopen"]=startopen
+ if end :
+ att["end"]=end
+ if endopen :
+ att["endopen"]=endopen
+ return att
+ else :
+ raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute"%(id,))
+ else :
+ raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(self.type_choices))
+
+ def getAttributesDeclarationXML(self) :
+ """ generate attributes declaration XML """
+ # return lxml etree element
+ allAttributesXML=[]
+ if len(self)>0 :
+ # iter on node and then edge atts
+ for attClass,atts in self.iteritems() :
+ # group by mode
+ key_mode=lambda att : att["mode"]
+ atts_sorted_by_mode=sorted(atts.values(),key=key_mode,reverse=True)
+ for mode,atts in itertools.groupby(atts_sorted_by_mode,key_mode) :
+ # generate on attributes by mode
+ attributesXML = etree.Element("attributes")
+ attributesXML.set("class",attClass)
+ attributesXML.set("mode",mode)
+ # generate attribute by id order
+ for att in sorted(atts,key=lambda att: att["id"]) :
+ attributeXML=etree.SubElement(attributesXML, "attribute")
+ attributeXML.set("id",str(att["id"]))
+ attributeXML.set("title",att["title"])
+ attributeXML.set("type",att["type"])
+ if att["defaultValue"] :
+ etree.SubElement(attributeXML, "default").text=att["defaultValue"]
+ allAttributesXML.append(attributesXML)
+ return allAttributesXML
+
+ @staticmethod
+ def getAttributesXML(atts) :
+ """ get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""
+ if len(atts)>0:
+ attValuesXML = etree.Element("attvalues")
+ for att in atts :
+ attValueXML=etree.SubElement(attValuesXML, "attvalue")
+ attValueXML.set("for",str(att["id"]))
+ attValueXML.set("value",att["value"])
+ if "start" in att.keys() and not att["start"]=="" :
+ attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen",att["start"])
+ if "end" in att.keys() and not att["end"]=="" :
+ attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen",att["end"])
+ return attValuesXML
+ else :
+ return None
+
+ def importAttributesXML(self,attributes_xml):
+ """ get XML attributes declaration of a graph gexf"""
+ attr_class = None
+ mode = ""
+ for attr in attributes_xml.attrib :
+ attr = attr.lower()
+ if attr == "class" :
+ attr_class = attributes_xml.attrib[attr].lower()
+ if attr == "mode" :
+ mode = attributes_xml.attrib[attr]
+
+ for child in attributes_xml :
+ tag = ns_clean(child.tag).lower()
+ if tag == "attribute" :
+ attribute_xml = child
+ id = ""
+ title = ""
+ type = ""
+
+ for attr in attribute_xml.attrib :
+ attr = attr.lower()
+ if attr == "id" :
+ id = attribute_xml.attrib[attr]
+ if attr == "title" :
+ title = attribute_xml.attrib[attr]
+ if attr == "type" :
+ type = attribute_xml.attrib[attr]
+
+ default = ""
+
+ for child in attribute_xml :
+ tag = ns_clean(child.tag).lower()
+ if tag == "default" :
+ default = child.text
+
+ self.declareAttribute(attr_class,type,default,title,mode,id)
+
+ def importAttributesValuesXML(self,attClass,attvalues_xml):
+ """ import attributes values from attvalues gexf xml tag attached to nodes or edges"""
+ atts=[]
+ for attvalues in attvalues_xml :
+ for child in attvalues :
+ tag = ns_clean(child.tag).lower()
+ if tag == "attvalue" :
+ attvalue_xml = child
+ id = ""
+ value = ""
+ start = ""
+ startopen=False
+ end = ""
+ endopen=False
+ for attr in attvalue_xml.attrib :
+ if attr == "for" :
+ id = attvalue_xml.attrib[attr]
+ if attr == "value" :
+ value = attvalue_xml.attrib[attr]
+ if attr == "start" :
+ start = attvalue_xml.attrib[attr]
+ if attr == "end" :
+ end = attvalue_xml.attrib[attr]
+ if attr == "startopen" :
+ start = attvalue_xml.attrib[attr]
+ startopen = True
+ if attr == "endopen" :
+ end = attvalue_xml.attrib[attr]
+ endopen = True
+
+ atts.append(self.makeAttributeInstance(attClass,id,value,start,end,startopen,endopen))
+ return atts
+
+class Spells(list):
+ '''
+ spells are time periods
+ spells is a list of dictionaries
+ a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}
+ '''
+
+
+ def getXML(self):
+
+ spellsXML=etree.Element("spells")
+ for spell in self :
+ spellXML=etree.SubElement(spellsXML, "spell")
+ if "start" in spell.keys() :
+ spellXML.set("start",spell["start"])
+ if "end" in spell.keys() :
+ spellXML.set("end",spell["end"])
+ return spellsXML
-
-
-
- def __init__(self,type,mode,label,start="",end="") :
-
- # control variable
- self.authorizedType=("directed","undirected")
- self.authorizedMode=("dynamic","static")
- self.defaultType="directed"
- self.defaultMode="static"
- self.label=label
-
-
- if type in self.authorizedType :
- self.type=type
- else :
- self.type=self.defaultType
- if mode in self.authorizedMode :
- self.mode=mode
- else :
- self.mode=self.defaultMode
-
-
- self.start=start
-
- self.end = end
-
-
- self._nodesAttributes={}
- self._edgesAttributes={}
- self._nodes={}
- self._edges={}
-
- def addNode(self,id,label,start="",end="",pid="",r="",g="",b="") :
- self._nodes[id]=Node(self,id,label,start,end,pid,r,g,b)
- return self._nodes[id]
-
- def nodeExists(self,id) :
- if id in self._nodes.keys():
- return 1
- else :
- return 0
-
- def addEdge(self,id,source,target,weight="",start="",end="",label="") :
- self._edges[id]=Edge(self,id,source,target,weight,start,end,label)
- return self._edges[id]
-
- def addNodeAttribute(self,title,defaultValue,type="integer",mode="static", force_id="") :
- # add to NodeAttributes
- # generate id
- if force_id == "" :
- id=len(self._nodesAttributes)
- else :
- id=force_id
- self._nodesAttributes[id]={"title":title , "default":defaultValue, "mode":mode, "type":type} # modify Nodes with default
- #: bad idea and unecessary
- #for node in self._nodes.values():
- # node.addAttribute(id,defaultValue)
-
- return id
-
- def addDefaultAttributesToNode(self,node) :
- # add existing nodesattributes default values
- for id,values in self._nodesAttributes.iteritems() :
- node.addAttribute(id,values["default"])
-
- def checkNodeAttribute(self,id,value,start,end):
- # check conformity with type is missing
- if id in self._nodesAttributes.keys() :
- if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
- raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
- return 1
- else :
- raise Exception("attribute id unknown. Add Attribute to graph first")
-
-
- def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static", force_id=""):
- # add to NodeAttributes
- # generate id
- if force_id == "" :
- id=len(self._edgesAttributes)
- else :
- id=force_id
- self._edgesAttributes[id]={"title":title, "default":defaultValue, "mode":mode, "type":type } # modify Nodes with default
- #for edge in self._edges.values():
- # edge.addAttribute(id,defaultValue)
- return id
-
-
- def addDefaultAttributesToEdge(self,edge) :
- # add existing nodesattributes default values
- for id,values in self._edgesAttributes.iteritems() :
- edge.addAttribute(id,values["default"])
-
- def checkEdgeAttribute(self,id,value,start,end):
- # check conformity with type is missing
- if id in self._edgesAttributes.keys() :
- if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
- raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
- return 1
- else :
- raise Exception("attribute id unknown. Add Attribute to graph first")
-
-
- def getXML(self) :
- # return lxml etree element
- graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label)
- attributesXMLNodeDynamic = etree.SubElement(graphXML, "attributes")
- attributesXMLNodeDynamic.set("class","node")
- attributesXMLNodeDynamic.set("mode","dynamic")
- attributesXMLNodeStatic = etree.SubElement(graphXML, "attributes")
- attributesXMLNodeStatic.set("class","node")
- attributesXMLNodeStatic.set("mode","static")
-
- for id,value in self._nodesAttributes.iteritems() :
- if value["mode"]=="static" :
- attxml=attributesXMLNodeStatic
- else :
- attxml=attributesXMLNodeDynamic
-
- attributeXML=etree.SubElement(attxml, "attribute")
- attributeXML.set("id",str(id))
- attributeXML.set("title",value["title"])
- attributeXML.set("type",value["type"])
- etree.SubElement(attributeXML, "default").text=value["default"]
-
- attributesXMLEdgeDynamic = etree.SubElement(graphXML, "attributes")
- attributesXMLEdgeDynamic.set("class","edge")
- attributesXMLEdgeDynamic.set("mode","dynamic")
- attributesXMLEdgeStatic = etree.SubElement(graphXML, "attributes")
- attributesXMLEdgeStatic.set("class","edge")
- attributesXMLEdgeStatic.set("mode","static")
-
- for id,value in self._edgesAttributes.iteritems() :
- if value["mode"]=="static" :
- attxml=attributesXMLEdgeStatic
- else :
- attxml=attributesXMLEdgeDynamic
-
- attributeXML=etree.SubElement(attxml, "attribute")
- attributeXML.set("id",str(id))
- attributeXML.set("title",value["title"])
- attributeXML.set("type",value["type"])
- etree.SubElement(attributeXML, "default").text=value["default"]
-
- nodesXML = etree.SubElement(graphXML, "nodes")
- for node in self._nodes.values() :
- nodesXML.append(node.getXML())
-
- edgesXML = etree.SubElement(graphXML, "edges")
- for edge in self._edges.values() :
- edgesXML.append(edge.getXML())
-
- return graphXML
-
- def print_stat(self):
- print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
- print "number of nodes : "+str(len(self._nodes))
- print "number of edges : "+str(len(self._edges))
-
-
+ @staticmethod
+ def importXML(spellsxmltree):
+ return Spells([ spell.attrib for spell in spellsxmltree])
+
+
class Node :
- def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="") :
- self.id =id
- self.label=label
- self.start=start
- self.end=end
- self.pid=pid
- self._graph=graph
- self.setColor(r,g,b)
- if not self.pid=="" :
- if not self._graph.nodeExists(self.pid) :
- raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
-
- self._attributes=[]
-
- # add existing nodesattributes default values : bad idea and unecessary
- #self._graph.addDefaultAttributesToNode(self)
-
- def addAttribute(self,id,value,start="",end="") :
- if self._graph.checkNodeAttribute(id,value,start,end) :
- self._attributes.append({"id":id,"value":value,"start":start,"end":end})
-
-
- def getXML(self) :
- # return lxml etree element
- try :
- nodeXML = etree.Element("node",id=str(self.id),label=self.label)
- if not self.start == "":
- nodeXML.set("start",self.start)
- if not self.end == "":
- nodeXML.set("end",self.end)
- if not self.pid == "":
- nodeXML.set("pid",self.pid)
-
- attributesXML = etree.SubElement(nodeXML, "attvalues")
- for atts in self._attributes :
- attributeXML=etree.SubElement(attributesXML, "attvalue")
- attributeXML.set("for",str(atts["id"]))
-
- attributeXML.set("value",atts["value"])
-
- if not atts["start"]=="" :
- attributeXML.set("start",atts["start"])
- if not atts["end"]=="" :
- attributeXML.set("end",atts["end"])
-
- if not self.r=="" and not self.g=="" and not self.b=="" :
- #color : <viz:color r="239" g="173" b="66"/>
- colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
- colorXML.set("r",self.r)
- colorXML.set("g",self.g)
- colorXML.set("b",self.b)
-
- return nodeXML
- except Exception, e:
- print self.label
- print self._attributes
- print e
- exit()
-
- def setColor(self,r,g,b) :
- self.r=r
- self.g=g
- self.b=b
-
+ def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
+ self.id =id
+ self.label=label
+ self.start=start
+ self.startopen=startopen
+ self.end=end
+ self.endopen=endopen
+ self.pid=pid
+ self._graph=graph
+ self.setColor(r,g,b)
+
+ #spells expecting format = [{start:"",end:""},...]
+ self.spells= spells
+
+ if not self.pid=="" :
+ if not self._graph.nodeExists(self.pid) :
+ raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
+
+ self._attributes=[]
+ self.attributes=self._attributes
+
+ # add existing nodesattributes default values : bad idea and unecessary
+ #self._graph.addDefaultAttributesToNode(self)
+
+ def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :
+ self._attributes.append(makeAttributeInstance(self,"node",id,value,start,end,startopen,endopen))
+
+ def getXML(self) :
+ # return lxml etree element
+ try :
+ nodeXML = etree.Element("node",id=str(self.id),label=self.label)
+ if not self.start == "":
+ nodeXML.set("start" if not self.startopen else "startopen",self.start)
+ if not self.end == "":
+ nodeXML.set("end" if not self.endopen else "endopen" ,self.end)
+ if not self.pid == "":
+ nodeXML.set("pid",self.pid)
+
+ # attributes
+ if self._attributes :
+ nodeXML.append(Attributes.getAttributesXML(self._attributes))
+
+ # spells
+ if self.spells :
+ print "found spells in node "+self.id
+ nodeXML.append(self.spells.getXML())
+
+
+ if not self.r=="" and not self.g=="" and not self.b=="" :
+ #color : <viz:color r="239" g="173" b="66"/>
+ colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
+ colorXML.set("r",self.r)
+ colorXML.set("g",self.g)
+ colorXML.set("b",self.b)
+
+ return nodeXML
+ except Exception, e:
+ print self.label
+ print self._attributes
+ print e
+ traceback.print_exc()
+ exit()
+
+ def getAttributes(self):
+ attsFull=[]
+ for att in self._attributes :
+ attFull=self._graph.attributes["node"][att["id"]].copy()
+ attFull.update(att)
+ attsFull.append(attFull)
+ return attsFull
+
+ @staticmethod
+ def importXML(nodes_xml,graph_obj) :
+
+ for child in nodes_xml :
+ tag = ns_clean(child.tag).lower()
+ if tag == "node" :
+ node_xml = child
+ id = ""
+ label = ""
+ start = ""
+ startopen=False
+ end = ""
+ endopen=False
+ pid = ""
+ r = ""
+ g = ""
+ b = ""
+
+ for attr in node_xml.attrib :
+ attr = attr.lower()
+ if attr == "id" :
+ id = node_xml.attrib[attr]
+ if attr == "label" :
+ label = node_xml.attrib[attr]
+ if attr == "start" :
+ start = node_xml.attrib[attr]
+ if attr == "end" :
+ start = node_xml.attrib[attr]
+ if attr == "startopen" :
+ start = attvalue_xml.attrib[attr]
+ startopen=True
+ if attr == "endopen" :
+ end = attvalue_xml.attrib[attr]
+ endopen=True
+ if attr == "pid" :
+ pid = node_xml.attrib[attr]
+
+
+ attvalues_xml = []
+ spells=[]
+
+ for child in node_xml :
+ tag = ns_clean(child.tag).lower()
+ if tag == "attvalues" :
+ attvalues_xml.append(child)
+ if tag == "viz:color" :
+ r = child.attrib["r"]
+ g = child.attrib["g"]
+ b = child.attrib["b"]
+ if tag =="spells" :
+ spells=Spells.importXML(child)
+
+
+
+ node_obj = graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)
+ node_obj._attributes =graph_obj.attributes.importAttributesValuesXML("node",attvalues_xml)
+
+
+
+ def setColor(self,r,g,b) :
+ self.r=r
+ self.g=g
+ self.b=b
+
+ def __str__(self):
+ return self.label
+
class Edge :
- def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="") :
-
- self.id =id
- self._graph=graph
-
-
- if self._graph.nodeExists(source) :
- self._source=source
- else :
- raise Exception("source "+source+" node unknown, add nodes to graph first")
-
- if self._graph.nodeExists(target) :
- self._target=target
- else:
- raise Exception("target "+target+" node unknown, add nodes to graph first")
-
- self.start=start
- self.end=end
- self.weight=weight
- self.label=label
- self._attributes=[]
- # COLOR on edges isn't supported in GEXF
- self.setColor(r,g,b)
-
- # add existing nodesattributes default values : bad idea and unecessary
- #self._graph.addDefaultAttributesToEdge(self)
-
-
- def addAttribute(self,id,value,start="",end="") :
- if self._graph.checkEdgeAttribute(id,value,start,end) :
- self._attributes.append({"id":id,"value":value,"start":start,"end":end})
-
-
- def getXML(self) :
- # return lxml etree element
- try :
- edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
- if not self.start == "":
- edgeXML.set("start",self.start)
- if not self.end == "":
- edgeXML.set("end",self.end)
- if not self.weight == "":
- edgeXML.set("weight",str(self.weight))
- if not self.label == "":
- edgeXML.set("label",self.label)
-
-# COLOR on edges isn't supported in GEXF
- if not self.r=="" and not self.g=="" and not self.b=="" :
- #color : <viz:color r="239" g="173" b="66"/>
- colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.1draft/viz}color")
- colorXML.set("r",self.r)
- colorXML.set("g",self.g)
- colorXML.set("b",self.b)
-
-
- attributesXML = etree.SubElement(edgeXML, "attvalues")
- for atts in self._attributes :
- attributeXML=etree.SubElement(attributesXML, "attvalue")
- attributeXML.set("for",str(atts["id"]))
- attributeXML.set("value",atts["value"])
- if not atts["start"]=="" :
- attributeXML.set("start",atts["start"])
- if not atts["end"]=="" :
- attributeXML.set("end",atts["end"])
- return edgeXML
- except Exception, e:
- print self._source+" "+self._target
- print e
- exit()
-# COLOR on edges isn't supported in GEXF
- def setColor(self,r,g,b) :
- self.r=r
- self.g=g
- self.b=b
-
+ def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :
+
+ self.id =id
+ self._graph=graph
+
+
+ if self._graph.nodeExists(source) :
+ self._source=source
+ self.source=self._source
+ else :
+ raise Exception("source "+source+" node unknown, add nodes to graph first")
+
+ if self._graph.nodeExists(target) :
+ self._target=target
+ self.target=self._target
+ else:
+ raise Exception("target "+target+" node unknown, add nodes to graph first")
+
+ self.start=start
+ self.startopen=startopen
+ self.end=end
+ self.endopen=endopen
+
+ self.weight=weight
+ self.label=label
+ self._attributes=[]
+ self.attributes=self._attributes
+ # COLOR on edges now supported in GEXF 1.2
+ self.setColor(r,g,b)
+
+ #spells expecting format = [{start:"",end:""},...]
+ self.spells= Spells()
+
+ # add existing nodesattributes default values : bad idea and unecessary
+ #self._graph.addDefaultAttributesToEdge(self)
+
+
+ def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :
+ self._attributes.append(makeAttributeInstance(self,"node",id,value,start,end,startopen,endopen))
+
+
+ def getXML(self) :
+ # return lxml etree element
+ try :
+ edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
+ if not self.start == "":
+ edgeXML.set("start" if not self.startopen else "startopen",self.start)
+ if not self.end == "":
+ edgeXML.set("end" if not self.endopen else "endopen" ,self.end)
+ if not self.weight == "":
+ edgeXML.set("weight",str(self.weight))
+ if not self.label == "":
+ edgeXML.set("label",self.label)
+
+ # attributes
+ if self._attributes :
+ edgeXML.append(Attributes.getAttributesXML(self._attributes))
+
+ # spells
+ if self.spells :
+ spellsXML.append(self.spells.getXML())
+
+ # COLOR on edges is supported in GEXF since 1.2
+ if not self.r=="" and not self.g=="" and not self.b=="" :
+ #color : <viz:color r="239" g="173" b="66"/>
+ colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.2draft/viz}color")
+ colorXML.set("r",self.r)
+ colorXML.set("g",self.g)
+ colorXML.set("b",self.b)
+
+
+
+ return edgeXML
+ except Exception, e:
+ print self._source+" "+self._target
+ print e
+ exit()
+
+ def getAttributes(self):
+ attsFull=[]
+ for att in self._attributes :
+ attFull=self._graph.attributes["node"][att["id"]].copy()
+ attFull.update(att)
+ attsFull.append(attFull)
+ return attsFull
+
+ @staticmethod
+ def importXML(edges_xml,graph_obj) :
+
+ for child in edges_xml :
+
+ tag = ns_clean(child.tag).lower()
+ if tag == "edge" :
+ edge_xml = child
+ id = ""
+ source = ""
+ target = ""
+ weight = ""
+ start = ""
+ startopen=False
+ end = ""
+ endopen=False
+ label = ""
+ r = ""
+ g = ""
+ b = ""
+
+ for attr in edge_xml.attrib :
+ attr = attr.lower()
+ if attr == "id" :
+ id = edge_xml.attrib[attr]
+ if attr == "source" :
+ source = edge_xml.attrib[attr]
+ if attr == "target" :
+ target = edge_xml.attrib[attr]
+ if attr == "weight" :
+ weight = edge_xml.attrib[attr]
+ if attr == "start" :
+ start = edge_xml.attrib[attr]
+ if attr == "end" :
+ end = edge_xml.attrib[attr]
+ if attr == "startopen" :
+ start = edge_xml.attrib[attr]
+ startopen=True
+ if attr == "endopen" :
+ end = edge_xml.attrib[attr]
+ endopen=True
+ if attr == "label" :
+ label = edge_xml.attrib[attr]
+
+ spells=[]
+ attvalues_xml=[]
+ for child in edge_xml :
+ tag = ns_clean(child.tag).lower()
+ if tag == "attvalues" :
+ attvalues_xml.append(child)
+ if tag =="spells" :
+ spells=Spells.importXML(child)
+ if tag == "viz:color" :
+ r = child.attrib["r"]
+ g = child.attrib["g"]
+ b = child.attrib["b"]
+
+ edge_obj = graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)
+ edge_obj._attributes=graph_obj.attributes.importAttributesValuesXML("edge",attvalues_xml)
+
+
+
+# COLOR on edges is supported in GEXF since 1.2
+ def setColor(self,r,g,b) :
+ self.r=r
+ self.g=g
+ self.b=b
+
class GexfImport :
# class coded by elie Rotenberg, médialab 20/07/2010
+# deprecated : import XML codes are now included to the Gexf, Graph, Attribute, Node, Edge classes
def __init__(self, file_like) :
- parser = etree.XMLParser(ns_clean=True)
- tree = etree.parse(file_like, parser)
- gexf_xml = tree.getroot()
- tag = self.ns_clean(gexf_xml.tag).lower()
- if tag <> "gexf" :
- self.msg_unexpected_tag("gexf", tag)
- return
- self.gexf_obj = None
- for child in gexf_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "meta" :
- meta_xml = child
- self.gexf_obj = self.extract_gexf_obj(meta_xml)
- if tag == "graph" :
- graph_xml = child
- if self.gexf_obj == None :
- self.msg_unexpected_tag("meta", tag)
- return
- self.graph_obj = self.extract_graph_obj(graph_xml)
-
+ parser = etree.XMLParser(ns_clean=True)
+ tree = etree.parse(file_like, parser)
+ gexf_xml = tree.getroot()
+ tag = self.ns_clean(gexf_xml.tag).lower()
+ if tag <> "gexf" :
+ self.msg_unexpected_tag("gexf", tag)
+ return
+ self.gexf_obj = None
+ for child in gexf_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "meta" :
+ meta_xml = child
+ self.gexf_obj = self.extract_gexf_obj(meta_xml)
+ if tag == "graph" :
+ graph_xml = child
+ if self.gexf_obj == None :
+ self.msg_unexpected_tag("meta", tag)
+ return
+ self.graph_obj = self.extract_graph_obj(graph_xml)
+
def ns_clean(self, token) :
- i = token.find('}')
- return token[i+1:]
+ i = token.find('}')
+ return token[i+1:]
def msg_unexpected_tag(self, expected, got) :
- print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
+ print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
def extract_gexf_obj(self, meta_xml) :
for child in meta_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "creator" :
creator = child.text
if tag == "description" :
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml) :
- type = ""
- mode = ""
- label = ""
- for attr in graph_xml.attrib :
- attr = attr.lower()
- if attr == "defaultedgetype" :
- type = graph_xml.attrib[attr]
- if attr == "mode" :
- mode = graph_xml.attrib[attr]
- if attr == "label" :
- label = graph_xml.attrib[attr]
-
- self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label)
-
- for child in graph_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "attributes" :
- attributes_xml = child
- self.extract_attributes(attributes_xml)
- if tag == "nodes" :
- nodes_xml = child
- self.extract_nodes(nodes_xml)
- if tag == "edges" :
- edges_xml = child
- self.extract_edges(edges_xml)
+ type = ""
+ mode = ""
+ label = ""
+ timeformat="double"
+ for attr in graph_xml.attrib :
+ attr = attr.lower()
+ if attr == "defaultedgetype" :
+ type = graph_xml.attrib[attr]
+ if attr == "mode" :
+ mode = graph_xml.attrib[attr]
+ if attr == "label" :
+ label = graph_xml.attrib[attr]
+ if attr == "timeformat" :
+ timeformat = graph_xml.attrib[attr]
+
+ self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)
+
+ for child in graph_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "attributes" :
+ attributes_xml = child
+ self.extract_attributes(attributes_xml)
+ if tag == "nodes" :
+ nodes_xml = child
+ self.extract_nodes(nodes_xml)
+ if tag == "edges" :
+ edges_xml = child
+ self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml) :
- attr_class = None
- mode = ""
- for attr in attributes_xml.attrib :
- attr = attr.lower()
- if attr == "class" :
- attr_class = attributes_xml.attrib[attr].lower()
- if attr == "mode" :
- mode = attributes_xml.attrib[attr]
-
- for child in attributes_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "attribute" :
- attribute_xml = child
- self.extract_attribute(attribute_xml, attr_class, mode)
+ attr_class = None
+ mode = ""
+ for attr in attributes_xml.attrib :
+ attr = attr.lower()
+ if attr == "class" :
+ attr_class = attributes_xml.attrib[attr].lower()
+ if attr == "mode" :
+ mode = attributes_xml.attrib[attr]
+
+ for child in attributes_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "attribute" :
+ attribute_xml = child
+ self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode) :
- id = ""
- title = ""
- type = ""
-
- for attr in attribute_xml.attrib :
- attr = attr.lower()
- if attr == "id" :
- id = attribute_xml.attrib[attr]
- if attr == "title" :
- title = attribute_xml.attrib[attr]
- if attr == "type" :
- type = attribute_xml.attrib[attr]
-
- default = ""
-
- for child in attribute_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "default" :
- default = child.text
-
-
- if attr_class == "node" :
- self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)
-
- if attr_class == "edge" :
- self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)
-
- def extract_nodes(self, nodes_xml) :
- for child in nodes_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "node" :
- node_xml = child
- self.extract_node(node_xml)
+ id = ""
+ title = ""
+ type = ""
+
+ for attr in attribute_xml.attrib :
+ attr = attr.lower()
+ if attr == "id" :
+ id = attribute_xml.attrib[attr]
+ if attr == "title" :
+ title = attribute_xml.attrib[attr]
+ if attr == "type" :
+ type = attribute_xml.attrib[attr]
+
+ default = ""
+
+ for child in attribute_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "default" :
+ default = child.text
+
+
+ if attr_class == "node" :
+ self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)
+
+ if attr_class == "edge" :
+ self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)
+
+ def extract_nodes(self, nodes_xml) :
+ for child in nodes_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "node" :
+ node_xml = child
+ self.extract_node(node_xml)
def extract_node(self, node_xml) :
- id = ""
- label = ""
- start = ""
- end = ""
- pid = ""
- r = ""
- g = ""
- b = ""
-
- for attr in node_xml.attrib :
- attr = attr.lower()
- if attr == "id" :
- id = node_xml.attrib[attr]
- if attr == "label" :
- label = node_xml.attrib[attr]
- if attr == "start" :
- start = node_xml.attrib[attr]
- if attr == "end" :
- start = node_xml.attrib[attr]
- if attr == "pid" :
- pid = node_xml.attrib[attr]
-
- attvalues_xmls = []
-
- for child in node_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "attvalues" :
- attvalues_xmls.append(child)
- if tag == "viz:color" :
- r = child.attrib["r"]
- g = child.attrib["g"]
- b = child.attrib["b"]
-
- self.node_obj = self.graph_obj.addNode(id=id, label=label, start=start, end=end, pid=pid, r=r, g=g, b=b)
-
- for attvalues_xml in attvalues_xmls :
- self.extract_node_attvalues(attvalues_xml)
+ id = ""
+ label = ""
+ start = ""
+ startopen=False
+ end = ""
+ endopen=False
+ pid = ""
+ r = ""
+ g = ""
+ b = ""
+
+ for attr in node_xml.attrib :
+ attr = attr.lower()
+ if attr == "id" :
+ id = node_xml.attrib[attr]
+ if attr == "label" :
+ label = node_xml.attrib[attr]
+ if attr == "start" :
+ start = node_xml.attrib[attr]
+ if attr == "end" :
+ start = node_xml.attrib[attr]
+ if attr == "startopen" :
+ start = attvalue_xml.attrib[attr]
+ startopen=True
+ if attr == "endopen" :
+ end = attvalue_xml.attrib[attr]
+ endopen=True
+ if attr == "pid" :
+ pid = node_xml.attrib[attr]
+
+
+ attvalues_xmls = []
+ spells=[]
+
+ for child in node_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "attvalues" :
+ attvalues_xmls.append(child)
+ if tag == "viz:color" :
+ r = child.attrib["r"]
+ g = child.attrib["g"]
+ b = child.attrib["b"]
+ if tag =="spells" :
+ spells=[ spell.attrib for spell in child ]
+
+
+ self.node_obj = self.graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)
+
+ for attvalues_xml in attvalues_xmls :
+ self.extract_node_attvalues(attvalues_xml)
def extract_node_attvalues(self, attvalues_xml) :
- for child in attvalues_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "attvalue" :
- attvalue_xml = child
- self.extract_node_attvalue(attvalue_xml)
+ for child in attvalues_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "attvalue" :
+ attvalue_xml = child
+ self.extract_node_attvalue(attvalue_xml)
def extract_node_attvalue(self, attvalue_xml) :
- id = ""
- value = ""
- start = ""
- end = ""
- for attr in attvalue_xml.attrib :
- attr = attr.lower()
- if attr == "for" :
- id = attvalue_xml.attrib[attr]
- if attr == "value" :
- value = attvalue_xml.attrib[attr]
- if attr == "start" :
- start = attvalue_xml.attrib[attr]
- if attr == "end" :
- end = attvalue_xml.attrib[attr]
- self.node_obj.addAttribute(id=id, value=value, start=start, end=end)
-
+ id = ""
+ value = ""
+ start = ""
+ startopen=False
+ end = ""
+ endopen=False
+ for attr in attvalue_xml.attrib :
+ attr = attr.lower()
+ if attr == "for" :
+ id = attvalue_xml.attrib[attr]
+ if attr == "value" :
+ value = attvalue_xml.attrib[attr]
+ if attr == "start" :
+ start = attvalue_xml.attrib[attr]
+ if attr == "end" :
+ end = attvalue_xml.attrib[attr]
+ if attr == "startopen" :
+ start = attvalue_xml.attrib[attr]
+ startopen=True
+ if attr == "endopen" :
+ end = attvalue_xml.attrib[attr]
+ endopen=True
+ self.node_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)
+
def extract_edges(self, edges_xml) :
- for child in edges_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "edge" :
- edge_xml = child
- self.extract_edge(edge_xml)
+ for child in edges_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "edge" :
+ edge_xml = child
+ self.extract_edge(edge_xml)
def extract_edge(self, edge_xml) :
- id = ""
- source = ""
- target = ""
- weight = ""
- start = ""
- end = ""
- label = ""
- for attr in edge_xml.attrib :
- attr = attr.lower()
- if attr == "id" :
- id = edge_xml.attrib[attr]
- if attr == "source" :
- source = edge_xml.attrib[attr]
- if attr == "target" :
- target = edge_xml.attrib[attr]
- if attr == "weight" :
- weight = edge_xml.attrib[attr]
- if attr == "start" :
- start = edge_xml.attrib[attr]
- if attr == "end" :
- end = edge_xml.attrib[attr]
- if attr == "label" :
- label = edge_xml.attrib[attr]
-
- self.edge_obj = self.graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end, label=label)
-
- for child in edge_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "attvalues" :
- attvalues_xml = child
- self.extract_edge_attvalues(attvalues_xml)
+ id = ""
+ source = ""
+ target = ""
+ weight = ""
+ start = ""
+ startopen=False
+ end = ""
+ endopen=False
+ label = ""
+ r = ""
+ g = ""
+ b = ""
+
+ for attr in edge_xml.attrib :
+ attr = attr.lower()
+ if attr == "id" :
+ id = edge_xml.attrib[attr]
+ if attr == "source" :
+ source = edge_xml.attrib[attr]
+ if attr == "target" :
+ target = edge_xml.attrib[attr]
+ if attr == "weight" :
+ weight = edge_xml.attrib[attr]
+ if attr == "start" :
+ start = edge_xml.attrib[attr]
+ if attr == "end" :
+ end = edge_xml.attrib[attr]
+ if attr == "startopen" :
+ start = edge_xml.attrib[attr]
+ startopen=True
+ if attr == "endopen" :
+ end = edge_xml.attrib[attr]
+ endopen=True
+ if attr == "label" :
+ label = edge_xml.attrib[attr]
+
+ spells=[]
+ attvalues_xml=[]
+ for child in edge_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "attvalues" :
+ attvalues_xml = child
+ if tag =="spells" :
+ spells=[ spell.attrib for spell in child]
+ if tag == "viz:color" :
+ r = child.attrib["r"]
+ g = child.attrib["g"]
+ b = child.attrib["b"]
+
+ self.edge_obj = self.graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)
+ self.extract_edge_attvalues(attvalues_xml)
def extract_edge_attvalues(self, attvalues_xml) :
- for child in attvalues_xml :
- tag = self.ns_clean(child.tag).lower()
- if tag == "attvalue" :
- attvalue_xml = child
- self.extract_edge_attvalue(attvalue_xml)
+ for child in attvalues_xml :
+ tag = self.ns_clean(child.tag).lower()
+ if tag == "attvalue" :
+ attvalue_xml = child
+ self.extract_edge_attvalue(attvalue_xml)
-# def addAttribute(self,id,value,start="",end="") :
+# def addAttribute(self,id,value,start="",end="") :
def extract_edge_attvalue(self, attvalue_xml) :
- id = ""
- value = ""
- start = ""
- end = ""
- for attr in attvalue_xml.attrib :
- if attr == "for" :
- id = attvalue_xml.attrib[attr]
- if attr == "value" :
- value = attvalue_xml.attrib[attr]
- if attr == "start" :
- start = attvalue_xml.attrib[attr]
- if attr == "end" :
- end = attvalue_xml.attrib[attr]
-
- self.edge_obj.addAttribute(id=id, value=value, start=start, end=end)
+ id = ""
+ value = ""
+ start = ""
+ startopen=True
+ end = ""
+ endopen=True
+ for attr in attvalue_xml.attrib :
+ if attr == "for" :
+ id = attvalue_xml.attrib[attr]
+ if attr == "value" :
+ value = attvalue_xml.attrib[attr]
+ if attr == "start" :
+ start = attvalue_xml.attrib[attr]
+ if attr == "end" :
+ end = attvalue_xml.attrib[attr]
+ if attr == "startopen" :
+ startopen = attvalue_xml.attrib[attr]
+ if attr == "endopen" :
+ endopen = attvalue_xml.attrib[attr]
+
+ self.edge_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)
def gexf(self) :
- return self.gexf_obj
+ return self.gexf_obj
diff --git a/test/gexf.net.dynamics_openintervals.gexf b/test/gexf.net.dynamics_openintervals.gexf
new file mode 100644
index 0000000..232c039
--- /dev/null
+++ b/test/gexf.net.dynamics_openintervals.gexf
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2">
+ <meta lastmodifieddate="2009-03-20">
+ <creator>Gexf.net</creator>
+ <description>A Web network changing over time</description>
+ </meta>
+ <graph mode="dynamic" defaultedgetype="directed" timeformat="date">
+ <attributes class="node" mode="static">
+ <attribute id="0" title="url" type="string"/>
+ <attribute id="1" title="frog" type="boolean">
+ <default>true</default>
+ </attribute>
+ </attributes>
+ <attributes class="node" mode="dynamic">
+ <attribute id="2" title="indegree" type="float"/>
+ </attributes>
+ <attributes class="edge" mode="dynamic">
+ <attribute id="2" title="indegree" type="float"/>
+ </attributes>
+ <nodes>
+ <node id="0" label="Gephi" start="2009-03-01">
+ <attvalues>
+ <attvalue for="0" value="http://gephi.org"/>
+ <attvalue for="2" value="1"/>
+ </attvalues>
+ </node>
+ <node id="1" label="Network">
+ <attvalues>
+ <attvalue for="2" value="1" end="2009-03-01"/>
+ <attvalue for="2" value="2" startopen="2009-03-01" end="2009-03-10"/>
+ <attvalue for="2" value="1" start="2009-03-10"/>
+ </attvalues>
+ </node>
+ <node id="2" label="Visualization">
+ <attvalues>
+ <attvalue for="2" value="0" endopen="2009-03-01"/>
+ <attvalue for="2" value="1" start="2009-03-01"/>
+ </attvalues>
+ <spells>
+ <spell end="2009-03-01"/>
+ <spell start="2009-03-05" end="2009-03-10" />
+ </spells>
+ </node>
+ <node id="3" label="Graph">
+ <attvalues>
+ <attvalue for="1" value="false"/>
+ <attvalue for="2" value="0" end="2009-03-01"/>
+ <attvalue for="2" value="1" start="2009-03-01"/>
+ </attvalues>
+ </node>
+ </nodes>
+ <edges>
+ <edge id="0" source="0" target="1" startopen="2009-03-01">
+ <attvalues>
+ <attvalue for="2" value="1"/>
+ </attvalues>
+ </edge>
+ <edge id="1" source="0" target="2" start="2009-03-01" endopen="2009-03-10"/>
+ <edge id="2" source="1" target="0" start="2009-03-01"/>
+ <edge id="3" source="2" target="1" end="2009-03-10"/>
+ <edge id="4" source="0" target="3" start="2009-03-01"/>
+ </edges>
+ </graph>
+</gexf>
diff --git a/test/test.py b/test/test.py
index ac4bd91..76a7c81 100644
--- a/test/test.py
+++ b/test/test.py
@@ -1,21 +1,44 @@
#!/usr/bin/python
-from gexf import Gexf,GexfImport
+import sys,pprint
+
+sys.path.append('../gexf')
+from _gexf import Gexf, GexfImport
# test helloworld.gexf
gexf = Gexf("Paul Girard","A hello world! file")
graph=gexf.addGraph("directed","static","a hello world graph")
graph.addNode("0","hello")
graph.addNode("1","World")
graph.addEdge("0","0","1")
-output_file=open("hellowrld.gexf","w")
+output_file=open("helloworld.gexf","w")
gexf.write(output_file)
# test GexfImport
-f = open("exp.gexf")
-o = open("exp_bootstrap_bootstrap.gexf", "w+")
+f = open("gexf.net.dynamics_openintervals.gexf")
+gexf_import = Gexf.importXML(f)
+f.close()
+f = open("gexf.net.dynamics_openintervals.gexf")
+gexf_import2 = Gexf.importXML(f)
+f.close()
+print "test gexf comparision "+str(gexf_import==gexf_import2)
+
+
+
+graph=gexf_import.graphs[0]
+# display nodes list
+for node_id,node in graph.nodes.iteritems() :
+ print node.label
+ pprint.pprint(node.getAttributes(),indent=1,width=1)
+
+# display edges list
+for edgeid,edge in graph.edges.iteritems() :
+ print str(graph.nodes[edge.source])+" -> "+str(graph.nodes[edge.target])
+ pprint.pprint(edge.getAttributes(),indent=1,width=1)
+
+
+o = open("gexf.net.dynamics_openintervals_copied.gexf", "w")
-gexf_import = GexfImport(f).gexf()
gexf_import.write(o)
|
paulgirard/pygexf
|
7e19db9b7c1607f1ade0a6498aa21ef37d180866
|
remove str() on labels in getXml methods
|
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index a0e643c..a61b4e4 100644
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,627 +1,627 @@
# -*- coding: utf-8 -*-
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
from lxml import etree
from datetime import *
# missing features :
# load, validate, modify existing gexf file
# slices / phylogeny / ...
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
# add a test based on existing example from gexf.net
# add modification accessors like setStart ...
# factorize attribute managment by creating an attribute class
# add a test code utility to check that code will not use _variable outside objects
class Gexf :
def __init__(self,creator,description):
self.creator=creator
self.description=description
self.graphs=[]
self.xmlns="http://www.gephi.org/gexf/1.1draft"
self.xsi="http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.1draft.xsd"
self.viz="http://www.gexf.net/1.1draft/viz"
self.version="1.1"
def addGraph(self,type,mode,label):
g = Graph(type,mode,label)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified",datetime.now().isoformat())
etree.SubElement(meta, "creator").text=self.creator
etree.SubElement(meta, "description").text=self.description
for graph in self.graphs :
gexfXML.append(graph.getXML())
return gexfXML
def write(self,file):
file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8'))
self.print_stat()
def print_stat(self) :
for graph in self.graphs :
graph.print_stat()
class Graph :
def __init__(self,type,mode,label,start="",end="") :
# control variable
self.authorizedType=("directed","undirected")
self.authorizedMode=("dynamic","static")
self.defaultType="directed"
self.defaultMode="static"
self.label=label
if type in self.authorizedType :
self.type=type
else :
self.type=self.defaultType
if mode in self.authorizedMode :
self.mode=mode
else :
self.mode=self.defaultMode
self.start=start
self.end = end
self._nodesAttributes={}
self._edgesAttributes={}
self._nodes={}
self._edges={}
def addNode(self,id,label,start="",end="",pid="",r="",g="",b="") :
self._nodes[id]=Node(self,id,label,start,end,pid,r,g,b)
return self._nodes[id]
def nodeExists(self,id) :
if id in self._nodes.keys():
return 1
else :
return 0
def addEdge(self,id,source,target,weight="",start="",end="",label="") :
self._edges[id]=Edge(self,id,source,target,weight,start,end,label)
return self._edges[id]
def addNodeAttribute(self,title,defaultValue,type="integer",mode="static", force_id="") :
# add to NodeAttributes
# generate id
if force_id == "" :
id=len(self._nodesAttributes)
else :
id=force_id
self._nodesAttributes[id]={"title":title , "default":defaultValue, "mode":mode, "type":type} # modify Nodes with default
#: bad idea and unecessary
#for node in self._nodes.values():
# node.addAttribute(id,defaultValue)
return id
def addDefaultAttributesToNode(self,node) :
# add existing nodesattributes default values
for id,values in self._nodesAttributes.iteritems() :
node.addAttribute(id,values["default"])
def checkNodeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._nodesAttributes.keys() :
if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static", force_id=""):
# add to NodeAttributes
# generate id
if force_id == "" :
id=len(self._edgesAttributes)
else :
id=force_id
self._edgesAttributes[id]={"title":title, "default":defaultValue, "mode":mode, "type":type } # modify Nodes with default
#for edge in self._edges.values():
# edge.addAttribute(id,defaultValue)
return id
def addDefaultAttributesToEdge(self,edge) :
# add existing nodesattributes default values
for id,values in self._edgesAttributes.iteritems() :
edge.addAttribute(id,values["default"])
def checkEdgeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._edgesAttributes.keys() :
if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label)
attributesXMLNodeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeDynamic.set("class","node")
attributesXMLNodeDynamic.set("mode","dynamic")
attributesXMLNodeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeStatic.set("class","node")
attributesXMLNodeStatic.set("mode","static")
for id,value in self._nodesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLNodeStatic
else :
attxml=attributesXMLNodeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
attributesXMLEdgeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeDynamic.set("class","edge")
attributesXMLEdgeDynamic.set("mode","dynamic")
attributesXMLEdgeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeStatic.set("class","edge")
attributesXMLEdgeStatic.set("mode","static")
for id,value in self._edgesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLEdgeStatic
else :
attxml=attributesXMLEdgeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
nodesXML = etree.SubElement(graphXML, "nodes")
for node in self._nodes.values() :
nodesXML.append(node.getXML())
edgesXML = etree.SubElement(graphXML, "edges")
for edge in self._edges.values() :
edgesXML.append(edge.getXML())
return graphXML
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="") :
self.id =id
self.label=label
self.start=start
self.end=end
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkNodeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
- nodeXML = etree.Element("node",id=str(self.id),label=str(self.label))
+ nodeXML = etree.Element("node",id=str(self.id),label=self.label)
if not self.start == "":
nodeXML.set("start",self.start)
if not self.end == "":
nodeXML.set("end",self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
attributesXML = etree.SubElement(nodeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception, e:
print self.label
print self._attributes
print e
exit()
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class Edge :
def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="") :
self.id =id
self._graph=graph
if self._graph.nodeExists(source) :
self._source=source
else :
raise Exception("source "+source+" node unknown, add nodes to graph first")
if self._graph.nodeExists(target) :
self._target=target
else:
raise Exception("target "+target+" node unknown, add nodes to graph first")
self.start=start
self.end=end
self.weight=weight
self.label=label
self._attributes=[]
# COLOR on edges isn't supported in GEXF
self.setColor(r,g,b)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkEdgeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
if not self.start == "":
edgeXML.set("start",self.start)
if not self.end == "":
edgeXML.set("end",self.end)
if not self.weight == "":
edgeXML.set("weight",str(self.weight))
if not self.label == "":
- edgeXML.set("label",str(self.label))
+ edgeXML.set("label",self.label)
# COLOR on edges isn't supported in GEXF
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
attributesXML = etree.SubElement(edgeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
return edgeXML
except Exception, e:
print self._source+" "+self._target
print e
exit()
# COLOR on edges isn't supported in GEXF
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class GexfImport :
# class coded by elie Rotenberg, médialab 20/07/2010
def __init__(self, file_like) :
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(file_like, parser)
gexf_xml = tree.getroot()
tag = self.ns_clean(gexf_xml.tag).lower()
if tag <> "gexf" :
self.msg_unexpected_tag("gexf", tag)
return
self.gexf_obj = None
for child in gexf_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "meta" :
meta_xml = child
self.gexf_obj = self.extract_gexf_obj(meta_xml)
if tag == "graph" :
graph_xml = child
if self.gexf_obj == None :
self.msg_unexpected_tag("meta", tag)
return
self.graph_obj = self.extract_graph_obj(graph_xml)
def ns_clean(self, token) :
i = token.find('}')
return token[i+1:]
def msg_unexpected_tag(self, expected, got) :
print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
def extract_gexf_obj(self, meta_xml) :
for child in meta_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "creator" :
creator = child.text
if tag == "description" :
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml) :
type = ""
mode = ""
label = ""
for attr in graph_xml.attrib :
attr = attr.lower()
if attr == "defaultedgetype" :
type = graph_xml.attrib[attr]
if attr == "mode" :
mode = graph_xml.attrib[attr]
if attr == "label" :
label = graph_xml.attrib[attr]
self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label)
for child in graph_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attributes" :
attributes_xml = child
self.extract_attributes(attributes_xml)
if tag == "nodes" :
nodes_xml = child
self.extract_nodes(nodes_xml)
if tag == "edges" :
edges_xml = child
self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml) :
attr_class = None
mode = ""
for attr in attributes_xml.attrib :
attr = attr.lower()
if attr == "class" :
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode" :
mode = attributes_xml.attrib[attr]
for child in attributes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attribute" :
attribute_xml = child
self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode) :
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = attribute_xml.attrib[attr]
if attr == "title" :
title = attribute_xml.attrib[attr]
if attr == "type" :
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "default" :
default = child.text
if attr_class == "node" :
self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)
if attr_class == "edge" :
self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)
def extract_nodes(self, nodes_xml) :
for child in nodes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "node" :
node_xml = child
self.extract_node(node_xml)
def extract_node(self, node_xml) :
id = ""
label = ""
start = ""
end = ""
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = node_xml.attrib[attr]
if attr == "label" :
label = node_xml.attrib[attr]
if attr == "start" :
start = node_xml.attrib[attr]
if attr == "end" :
start = node_xml.attrib[attr]
if attr == "pid" :
pid = node_xml.attrib[attr]
attvalues_xmls = []
for child in node_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xmls.append(child)
if tag == "viz:color" :
r = child.attrib["r"]
g = child.attrib["g"]
b = child.attrib["b"]
self.node_obj = self.graph_obj.addNode(id=id, label=label, start=start, end=end, pid=pid, r=r, g=g, b=b)
for attvalues_xml in attvalues_xmls :
self.extract_node_attvalues(attvalues_xml)
def extract_node_attvalues(self, attvalues_xml) :
for child in attvalues_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
self.extract_node_attvalue(attvalue_xml)
def extract_node_attvalue(self, attvalue_xml) :
id = ""
value = ""
start = ""
end = ""
for attr in attvalue_xml.attrib :
attr = attr.lower()
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
self.node_obj.addAttribute(id=id, value=value, start=start, end=end)
def extract_edges(self, edges_xml) :
for child in edges_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "edge" :
edge_xml = child
self.extract_edge(edge_xml)
def extract_edge(self, edge_xml) :
id = ""
source = ""
target = ""
weight = ""
start = ""
end = ""
label = ""
for attr in edge_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = edge_xml.attrib[attr]
if attr == "source" :
source = edge_xml.attrib[attr]
if attr == "target" :
target = edge_xml.attrib[attr]
if attr == "weight" :
weight = edge_xml.attrib[attr]
if attr == "start" :
start = edge_xml.attrib[attr]
if attr == "end" :
end = edge_xml.attrib[attr]
if attr == "label" :
label = edge_xml.attrib[attr]
self.edge_obj = self.graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end, label=label)
for child in edge_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xml = child
self.extract_edge_attvalues(attvalues_xml)
def extract_edge_attvalues(self, attvalues_xml) :
for child in attvalues_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalue" :
attvalue_xml = child
self.extract_edge_attvalue(attvalue_xml)
# def addAttribute(self,id,value,start="",end="") :
def extract_edge_attvalue(self, attvalue_xml) :
id = ""
value = ""
start = ""
end = ""
for attr in attvalue_xml.attrib :
if attr == "for" :
id = attvalue_xml.attrib[attr]
if attr == "value" :
value = attvalue_xml.attrib[attr]
if attr == "start" :
start = attvalue_xml.attrib[attr]
if attr == "end" :
end = attvalue_xml.attrib[attr]
self.edge_obj.addAttribute(id=id, value=value, start=start, end=end)
def gexf(self) :
return self.gexf_obj
|
paulgirard/pygexf
|
4635392cb5cc846c3c8929d68cc002c6233559a6
|
add hello world test
|
diff --git a/VERSION b/VERSION
index 0c62199..ee1372d 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.2.1
+0.2.2
diff --git a/doc/conf.py b/doc/conf.py
index 05fcfde..5df1a5d 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -1,216 +1,216 @@
# -*- coding: utf-8 -*-
#
# Pygexf documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 18 16:06:18 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Pygexf'
copyright = u'2010, Paul Girard'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.2'
# The full version, including alpha/beta/rc tags.
-release = '0.2.1'
+release = '0.2.2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'Pygexfdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Pygexf.tex', u'Pygexf Documentation',
u'Paul Girard', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pygexf', u'Pygexf Documentation',
[u'Paul Girard'], 1)
]
diff --git a/setup.py b/setup.py
index 30bdbf2..c3d2181 100644
--- a/setup.py
+++ b/setup.py
@@ -1,8 +1,8 @@
from setuptools import setup
setup(name='pygexf',
- version='0.2.1',
+ version='0.2.2',
packages=['gexf'],
url='http://github.com/paulgirard/pygexf',
author='Paul Girard',
author_email='[email protected]'
)
diff --git a/test/test.py b/test/test.py
index 2191783..ac4bd91 100644
--- a/test/test.py
+++ b/test/test.py
@@ -1,9 +1,21 @@
#!/usr/bin/python
-import gexf
+from gexf import Gexf,GexfImport
+# test helloworld.gexf
+gexf = Gexf("Paul Girard","A hello world! file")
+graph=gexf.addGraph("directed","static","a hello world graph")
+
+graph.addNode("0","hello")
+graph.addNode("1","World")
+graph.addEdge("0","0","1")
+
+output_file=open("hellowrld.gexf","w")
+gexf.write(output_file)
+
+# test GexfImport
f = open("exp.gexf")
o = open("exp_bootstrap_bootstrap.gexf", "w+")
-gexf_import = gexf.GexfImport(f).gexf()
+gexf_import = GexfImport(f).gexf()
gexf_import.write(o)
|
paulgirard/pygexf
|
490a828d699fcf31ad1deac8d0d88abe19b8a61b
|
correct encoding declaration in _gesf.py and add gexfimport to __init__.py
|
diff --git a/gexf/__init__.py b/gexf/__init__.py
index 5145622..99603ef 100644
--- a/gexf/__init__.py
+++ b/gexf/__init__.py
@@ -1,4 +1,5 @@
from _gexf import Gexf
from _gexf import Node
from _gexf import Edge
-from _gexf import Graph
\ No newline at end of file
+from _gexf import Graph
+from _gexf import GexfImport
\ No newline at end of file
diff --git a/gexf/_gexf.py b/gexf/_gexf.py
index ce1f070..a0e643c 100644
--- a/gexf/_gexf.py
+++ b/gexf/_gexf.py
@@ -1,525 +1,525 @@
+# -*- coding: utf-8 -*-
+
#
# Gexf library in python
# see gephi.org and gexf.net
#
# repository : http://github.com/paulgirard/pygexf
# documentation : http://packages.python.org/pygexf
#
# main developper : Paul Girard, médialab Sciences Po
# licence : GPL v3
#
-# -*- coding: utf-8 -*-
-
from lxml import etree
from datetime import *
# missing features :
# load, validate, modify existing gexf file
# slices / phylogeny / ...
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
# add a test based on existing example from gexf.net
# add modification accessors like setStart ...
# factorize attribute managment by creating an attribute class
# add a test code utility to check that code will not use _variable outside objects
class Gexf :
def __init__(self,creator,description):
self.creator=creator
self.description=description
self.graphs=[]
self.xmlns="http://www.gephi.org/gexf/1.1draft"
self.xsi="http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.1draft.xsd"
self.viz="http://www.gexf.net/1.1draft/viz"
self.version="1.1"
def addGraph(self,type,mode,label):
g = Graph(type,mode,label)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified",datetime.now().isoformat())
etree.SubElement(meta, "creator").text=self.creator
etree.SubElement(meta, "description").text=self.description
for graph in self.graphs :
gexfXML.append(graph.getXML())
return gexfXML
def write(self,file):
file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8'))
self.print_stat()
def print_stat(self) :
for graph in self.graphs :
graph.print_stat()
class Graph :
def __init__(self,type,mode,label,start="",end="") :
# control variable
self.authorizedType=("directed","undirected")
self.authorizedMode=("dynamic","static")
self.defaultType="directed"
self.defaultMode="static"
self.label=label
if type in self.authorizedType :
self.type=type
else :
self.type=self.defaultType
if mode in self.authorizedMode :
self.mode=mode
else :
self.mode=self.defaultMode
self.start=start
self.end = end
self._nodesAttributes={}
self._edgesAttributes={}
self._nodes={}
self._edges={}
def addNode(self,id,label,start="",end="",pid="",r="",g="",b="") :
self._nodes[id]=Node(self,id,label,start,end,pid,r,g,b)
return self._nodes[id]
def nodeExists(self,id) :
if id in self._nodes.keys():
return 1
else :
return 0
def addEdge(self,id,source,target,weight="",start="",end="",label="") :
self._edges[id]=Edge(self,id,source,target,weight,start,end,label)
return self._edges[id]
def addNodeAttribute(self,title,defaultValue,type="integer",mode="static", force_id="") :
# add to NodeAttributes
# generate id
if force_id == "" :
id=len(self._nodesAttributes)
else :
id=force_id
self._nodesAttributes[id]={"title":title , "default":defaultValue, "mode":mode, "type":type} # modify Nodes with default
#: bad idea and unecessary
#for node in self._nodes.values():
# node.addAttribute(id,defaultValue)
return id
def addDefaultAttributesToNode(self,node) :
# add existing nodesattributes default values
for id,values in self._nodesAttributes.iteritems() :
node.addAttribute(id,values["default"])
def checkNodeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._nodesAttributes.keys() :
if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static", force_id=""):
# add to NodeAttributes
# generate id
if force_id == "" :
id=len(self._edgesAttributes)
else :
id=force_id
self._edgesAttributes[id]={"title":title, "default":defaultValue, "mode":mode, "type":type } # modify Nodes with default
#for edge in self._edges.values():
# edge.addAttribute(id,defaultValue)
return id
def addDefaultAttributesToEdge(self,edge) :
# add existing nodesattributes default values
for id,values in self._edgesAttributes.iteritems() :
edge.addAttribute(id,values["default"])
def checkEdgeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._edgesAttributes.keys() :
if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label)
attributesXMLNodeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeDynamic.set("class","node")
attributesXMLNodeDynamic.set("mode","dynamic")
attributesXMLNodeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeStatic.set("class","node")
attributesXMLNodeStatic.set("mode","static")
for id,value in self._nodesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLNodeStatic
else :
attxml=attributesXMLNodeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
attributesXMLEdgeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeDynamic.set("class","edge")
attributesXMLEdgeDynamic.set("mode","dynamic")
attributesXMLEdgeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeStatic.set("class","edge")
attributesXMLEdgeStatic.set("mode","static")
for id,value in self._edgesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLEdgeStatic
else :
attxml=attributesXMLEdgeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
nodesXML = etree.SubElement(graphXML, "nodes")
for node in self._nodes.values() :
nodesXML.append(node.getXML())
edgesXML = etree.SubElement(graphXML, "edges")
for edge in self._edges.values() :
edgesXML.append(edge.getXML())
return graphXML
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="") :
self.id =id
self.label=label
self.start=start
self.end=end
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkNodeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
nodeXML = etree.Element("node",id=str(self.id),label=str(self.label))
if not self.start == "":
nodeXML.set("start",self.start)
if not self.end == "":
nodeXML.set("end",self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
attributesXML = etree.SubElement(nodeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception, e:
print self.label
print self._attributes
print e
exit()
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class Edge :
def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="") :
self.id =id
self._graph=graph
if self._graph.nodeExists(source) :
self._source=source
else :
raise Exception("source "+source+" node unknown, add nodes to graph first")
if self._graph.nodeExists(target) :
self._target=target
else:
raise Exception("target "+target+" node unknown, add nodes to graph first")
self.start=start
self.end=end
self.weight=weight
self.label=label
self._attributes=[]
# COLOR on edges isn't supported in GEXF
self.setColor(r,g,b)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkEdgeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
if not self.start == "":
edgeXML.set("start",self.start)
if not self.end == "":
edgeXML.set("end",self.end)
if not self.weight == "":
edgeXML.set("weight",str(self.weight))
if not self.label == "":
edgeXML.set("label",str(self.label))
# COLOR on edges isn't supported in GEXF
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
attributesXML = etree.SubElement(edgeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
return edgeXML
except Exception, e:
print self._source+" "+self._target
print e
exit()
# COLOR on edges isn't supported in GEXF
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class GexfImport :
# class coded by elie Rotenberg, médialab 20/07/2010
def __init__(self, file_like) :
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(file_like, parser)
gexf_xml = tree.getroot()
tag = self.ns_clean(gexf_xml.tag).lower()
if tag <> "gexf" :
self.msg_unexpected_tag("gexf", tag)
return
self.gexf_obj = None
for child in gexf_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "meta" :
meta_xml = child
self.gexf_obj = self.extract_gexf_obj(meta_xml)
if tag == "graph" :
graph_xml = child
if self.gexf_obj == None :
self.msg_unexpected_tag("meta", tag)
return
self.graph_obj = self.extract_graph_obj(graph_xml)
def ns_clean(self, token) :
i = token.find('}')
return token[i+1:]
def msg_unexpected_tag(self, expected, got) :
print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)
def extract_gexf_obj(self, meta_xml) :
for child in meta_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "creator" :
creator = child.text
if tag == "description" :
description = child.text
return Gexf(creator=creator, description=description)
def extract_graph_obj(self, graph_xml) :
type = ""
mode = ""
label = ""
for attr in graph_xml.attrib :
attr = attr.lower()
if attr == "defaultedgetype" :
type = graph_xml.attrib[attr]
if attr == "mode" :
mode = graph_xml.attrib[attr]
if attr == "label" :
label = graph_xml.attrib[attr]
self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label)
for child in graph_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attributes" :
attributes_xml = child
self.extract_attributes(attributes_xml)
if tag == "nodes" :
nodes_xml = child
self.extract_nodes(nodes_xml)
if tag == "edges" :
edges_xml = child
self.extract_edges(edges_xml)
def extract_attributes(self, attributes_xml) :
attr_class = None
mode = ""
for attr in attributes_xml.attrib :
attr = attr.lower()
if attr == "class" :
attr_class = attributes_xml.attrib[attr].lower()
if attr == "mode" :
mode = attributes_xml.attrib[attr]
for child in attributes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attribute" :
attribute_xml = child
self.extract_attribute(attribute_xml, attr_class, mode)
def extract_attribute(self, attribute_xml, attr_class, mode) :
id = ""
title = ""
type = ""
for attr in attribute_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = attribute_xml.attrib[attr]
if attr == "title" :
title = attribute_xml.attrib[attr]
if attr == "type" :
type = attribute_xml.attrib[attr]
default = ""
for child in attribute_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "default" :
default = child.text
if attr_class == "node" :
self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)
if attr_class == "edge" :
self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)
def extract_nodes(self, nodes_xml) :
for child in nodes_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "node" :
node_xml = child
self.extract_node(node_xml)
def extract_node(self, node_xml) :
id = ""
label = ""
start = ""
end = ""
pid = ""
r = ""
g = ""
b = ""
for attr in node_xml.attrib :
attr = attr.lower()
if attr == "id" :
id = node_xml.attrib[attr]
if attr == "label" :
label = node_xml.attrib[attr]
if attr == "start" :
start = node_xml.attrib[attr]
if attr == "end" :
start = node_xml.attrib[attr]
if attr == "pid" :
pid = node_xml.attrib[attr]
attvalues_xmls = []
for child in node_xml :
tag = self.ns_clean(child.tag).lower()
if tag == "attvalues" :
attvalues_xmls.append(child)
if tag == "viz:color" :
|
paulgirard/pygexf
|
fa06652545df7acca7807e6b7fd257ec7ac90842
|
correct bug in __init__
|
diff --git a/gexf/__init__.py b/gexf/__init__.py
index 1de6adb..5145622 100644
--- a/gexf/__init__.py
+++ b/gexf/__init__.py
@@ -1,4 +1,4 @@
-from gexf import Gexf
-from gexf import Node
-from gexf import Edge
-from gexf import Graph
\ No newline at end of file
+from _gexf import Gexf
+from _gexf import Node
+from _gexf import Edge
+from _gexf import Graph
\ No newline at end of file
|
paulgirard/pygexf
|
394b019732637aea034723c4597d050f1ec47e5d
|
packaging to pypi
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..dc2ad2e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+html
+*.pyc
+dist
+build
diff --git a/__init__.py b/LICENSE
similarity index 100%
rename from __init__.py
rename to LICENSE
diff --git a/MANIFEST b/MANIFEST
new file mode 100644
index 0000000..7cdbc59
--- /dev/null
+++ b/MANIFEST
@@ -0,0 +1,5 @@
+README
+setup.py
+gexf/__init__.py
+gexf/_gexf.py
+test/test_pygexf.py
diff --git a/README b/README
new file mode 100644
index 0000000..e69de29
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..e69de29
diff --git a/doc/conf.py b/doc/conf.py
new file mode 100644
index 0000000..e69de29
diff --git a/gexf/__init__.py b/gexf/__init__.py
new file mode 100644
index 0000000..1de6adb
--- /dev/null
+++ b/gexf/__init__.py
@@ -0,0 +1,4 @@
+from gexf import Gexf
+from gexf import Node
+from gexf import Edge
+from gexf import Graph
\ No newline at end of file
diff --git a/gexf.py b/gexf/_gexf.py
similarity index 100%
rename from gexf.py
rename to gexf/_gexf.py
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..328aaaa
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,8 @@
+from distutils.core import setup
+setup(name='pygexf',
+ version='0.1',
+ packages=['gexf'],
+ url='http://github.com/paulgirard/pygexf',
+ author='Paul Girard',
+ author_email='[email protected]'
+ )
\ No newline at end of file
diff --git a/test/test_pygexf.py b/test/test_pygexf.py
new file mode 100644
index 0000000..e69de29
|
paulgirard/pygexf
|
480e38a9bb7a6c11a928960655db67d28517f313
|
correct bug in addEdgeAttribute in graph (return id missing)
|
diff --git a/gexf.py b/gexf.py
index 92d024b..050635e 100644
--- a/gexf.py
+++ b/gexf.py
@@ -1,360 +1,361 @@
# -*- coding: utf-8 -*-
from lxml import etree
from datetime import *
# missing features :
# load, validate, modify existing gexf file
# slices / phylogeny / ...
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
# add a test based on existing example from gexf.net
# add modification accessors like setStart ...
# factorize attribute managment by creating an attribute class
# add a test code utility to check that code will not use _variable outside objects
class Gexf :
def __init__(self,creator,description):
self.creator=creator
self.description=description
self.graphs=[]
self.xmlns="http://www.gephi.org/gexf/1.1draft"
self.xsi="http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.1draft.xsd"
self.viz="http://www.gexf.net/1.1draft/viz"
self.version="1.1"
def addGraph(self,type,mode,label):
g = Graph(type,mode,label)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified",datetime.now().isoformat())
etree.SubElement(meta, "creator").text=self.creator
etree.SubElement(meta, "description").text=self.description
for graph in self.graphs :
gexfXML.append(graph.getXML())
return gexfXML
def write(self,file):
file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8'))
self.print_stat()
def print_stat(self) :
for graph in self.graphs :
graph.print_stat()
class Graph :
def __init__(self,type,mode,label,start="",end="") :
# control variable
self.authorizedType=("directed","undirected")
self.authorizedMode=("dynamic","static")
self.defaultType="directed"
self.defaultMode="static"
self.label=label
if type in self.authorizedType :
self.type=type
else :
self.type=self.defaultType
if mode in self.authorizedMode :
self.mode=mode
else :
self.mode=self.defaultMode
self.start=start
self.end = end
self._nodesAttributes={}
self._edgesAttributes={}
self._nodes={}
self._edges={}
def addNode(self,id,label,start="",end="",pid="") :
self._nodes[id]=Node(self,id,label,start,end,pid)
return self._nodes[id]
def nodeExists(self,id) :
if id in self._nodes.keys():
return 1
else :
return 0
def addEdge(self,id,source,target,weight="",start="",end="",label="") :
self._edges[id]=Edge(self,id,source,target,weight,start,end,label)
return self._edges[id]
def addNodeAttribute(self,title,defaultValue,type="integer",mode="static") :
# add to NodeAttributes
# generate id
id=len(self._nodesAttributes)
self._nodesAttributes[id]={"title":title , "default":defaultValue, "mode":mode, "type":type} # modify Nodes with default
#: bad idea and unecessary
#for node in self._nodes.values():
# node.addAttribute(id,defaultValue)
return id
def addDefaultAttributesToNode(self,node) :
# add existing nodesattributes default values
for id,values in self._nodesAttributes.iteritems() :
node.addAttribute(id,values["default"])
def checkNodeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._nodesAttributes.keys() :
if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static"):
# add to NodeAttributes
# generate id
id=len(self._edgesAttributes)
self._edgesAttributes[id]={"title":title, "default":defaultValue, "mode":mode, "type":type } # modify Nodes with default
#for edge in self._edges.values():
# edge.addAttribute(id,defaultValue)
+ return id
def addDefaultAttributesToEdge(self,edge) :
# add existing nodesattributes default values
for id,values in self._edgesAttributes.iteritems() :
edge.addAttribute(id,values["default"])
def checkEdgeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._edgesAttributes.keys() :
if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label)
attributesXMLNodeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeDynamic.set("class","node")
attributesXMLNodeDynamic.set("mode","dynamic")
attributesXMLNodeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeStatic.set("class","node")
attributesXMLNodeStatic.set("mode","static")
for id,value in self._nodesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLNodeStatic
else :
attxml=attributesXMLNodeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
attributesXMLEdgeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeDynamic.set("class","edge")
attributesXMLEdgeDynamic.set("mode","dynamic")
attributesXMLEdgeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeStatic.set("class","edge")
attributesXMLEdgeStatic.set("mode","static")
for id,value in self._edgesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLEdgeStatic
else :
attxml=attributesXMLEdgeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
nodesXML = etree.SubElement(graphXML, "nodes")
for node in self._nodes.values() :
nodesXML.append(node.getXML())
edgesXML = etree.SubElement(graphXML, "edges")
for edge in self._edges.values() :
edgesXML.append(edge.getXML())
return graphXML
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="") :
self.id =id
self.label=label
self.start=start
self.end=end
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkNodeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
nodeXML = etree.Element("node",id=self.id,label=str(self.label))
if not self.start == "":
nodeXML.set("start",self.start)
if not self.end == "":
nodeXML.set("end",self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
attributesXML = etree.SubElement(nodeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception as e:
print self.label
print self._attributes
print e
exit()
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class Edge :
def __init__(self,graph,id,source,target,weight="",start="",end="",label=""):
# COLOR on edges isn't supported in GEXF
# ,r="",g="",b="") :
self.id =id
self._graph=graph
if self._graph.nodeExists(source) :
self._source=source
else :
raise Exception("source "+source+" node unknown, add nodes to graph first")
if self._graph.nodeExists(target) :
self._target=target
else:
raise Exception("target "+target+" node unknown, add nodes to graph first")
self.start=start
self.end=end
self.weight=weight
self.label=label
self._attributes=[]
# COLOR on edges isn't supported in GEXF
# self.setColor(r,g,b)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkEdgeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
if not self.start == "":
edgeXML.set("start",self.start)
if not self.end == "":
edgeXML.set("end",self.end)
if not self.weight == "":
edgeXML.set("weight",str(self.weight))
if not self.label == "":
edgeXML.set("label",str(self.label))
# COLOR on edges isn't supported in GEXF
# if not self.r=="" and not self.g=="" and not self.b=="" :
# #color : <viz:color r="239" g="173" b="66"/>
# colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.1draft/viz}color")
# colorXML.set("r",self.r)
# colorXML.set("g",self.g)
# colorXML.set("b",self.b)
attributesXML = etree.SubElement(edgeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
return edgeXML
except Exception as e:
print self._source+" "+self._target
print e
exit()
# COLOR on edges isn't supported in GEXF
# def setColor(self,r,g,b) :
# self.r=r
# self.g=g
# self.b=b
\ No newline at end of file
|
paulgirard/pygexf
|
81b69ec2322011129dd419df8c78e0da0a8922d7
|
comment viz color on edges (not supported n GEXF)
|
diff --git a/gexf.py b/gexf.py
index d6980d4..92d024b 100644
--- a/gexf.py
+++ b/gexf.py
@@ -1,356 +1,360 @@
# -*- coding: utf-8 -*-
from lxml import etree
from datetime import *
# missing features :
# load, validate, modify existing gexf file
# slices / phylogeny / ...
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
# add a test based on existing example from gexf.net
# add modification accessors like setStart ...
# factorize attribute managment by creating an attribute class
# add a test code utility to check that code will not use _variable outside objects
class Gexf :
def __init__(self,creator,description):
self.creator=creator
self.description=description
self.graphs=[]
self.xmlns="http://www.gephi.org/gexf/1.1draft"
self.xsi="http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.1draft.xsd"
self.viz="http://www.gexf.net/1.1draft/viz"
self.version="1.1"
def addGraph(self,type,mode,label):
g = Graph(type,mode,label)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified",datetime.now().isoformat())
etree.SubElement(meta, "creator").text=self.creator
etree.SubElement(meta, "description").text=self.description
for graph in self.graphs :
gexfXML.append(graph.getXML())
return gexfXML
def write(self,file):
file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8'))
self.print_stat()
def print_stat(self) :
for graph in self.graphs :
graph.print_stat()
class Graph :
def __init__(self,type,mode,label,start="",end="") :
# control variable
self.authorizedType=("directed","undirected")
self.authorizedMode=("dynamic","static")
self.defaultType="directed"
self.defaultMode="static"
self.label=label
if type in self.authorizedType :
self.type=type
else :
self.type=self.defaultType
if mode in self.authorizedMode :
self.mode=mode
else :
self.mode=self.defaultMode
self.start=start
self.end = end
self._nodesAttributes={}
self._edgesAttributes={}
self._nodes={}
self._edges={}
def addNode(self,id,label,start="",end="",pid="") :
self._nodes[id]=Node(self,id,label,start,end,pid)
return self._nodes[id]
def nodeExists(self,id) :
if id in self._nodes.keys():
return 1
else :
return 0
def addEdge(self,id,source,target,weight="",start="",end="",label="") :
self._edges[id]=Edge(self,id,source,target,weight,start,end,label)
return self._edges[id]
def addNodeAttribute(self,title,defaultValue,type="integer",mode="static") :
# add to NodeAttributes
# generate id
id=len(self._nodesAttributes)
self._nodesAttributes[id]={"title":title , "default":defaultValue, "mode":mode, "type":type} # modify Nodes with default
#: bad idea and unecessary
#for node in self._nodes.values():
# node.addAttribute(id,defaultValue)
return id
def addDefaultAttributesToNode(self,node) :
# add existing nodesattributes default values
for id,values in self._nodesAttributes.iteritems() :
node.addAttribute(id,values["default"])
def checkNodeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._nodesAttributes.keys() :
if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static"):
# add to NodeAttributes
# generate id
id=len(self._edgesAttributes)
self._edgesAttributes[id]={"title":title, "default":defaultValue, "mode":mode, "type":type } # modify Nodes with default
#for edge in self._edges.values():
# edge.addAttribute(id,defaultValue)
def addDefaultAttributesToEdge(self,edge) :
# add existing nodesattributes default values
for id,values in self._edgesAttributes.iteritems() :
edge.addAttribute(id,values["default"])
def checkEdgeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._edgesAttributes.keys() :
if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label)
attributesXMLNodeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeDynamic.set("class","node")
attributesXMLNodeDynamic.set("mode","dynamic")
attributesXMLNodeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeStatic.set("class","node")
attributesXMLNodeStatic.set("mode","static")
for id,value in self._nodesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLNodeStatic
else :
attxml=attributesXMLNodeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
attributesXMLEdgeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeDynamic.set("class","edge")
attributesXMLEdgeDynamic.set("mode","dynamic")
attributesXMLEdgeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeStatic.set("class","edge")
attributesXMLEdgeStatic.set("mode","static")
for id,value in self._edgesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLEdgeStatic
else :
attxml=attributesXMLEdgeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
nodesXML = etree.SubElement(graphXML, "nodes")
for node in self._nodes.values() :
nodesXML.append(node.getXML())
edgesXML = etree.SubElement(graphXML, "edges")
for edge in self._edges.values() :
edgesXML.append(edge.getXML())
return graphXML
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="") :
self.id =id
self.label=label
self.start=start
self.end=end
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkNodeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
nodeXML = etree.Element("node",id=self.id,label=str(self.label))
if not self.start == "":
nodeXML.set("start",self.start)
if not self.end == "":
nodeXML.set("end",self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
attributesXML = etree.SubElement(nodeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception as e:
print self.label
print self._attributes
print e
exit()
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class Edge :
- def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="") :
+ def __init__(self,graph,id,source,target,weight="",start="",end="",label=""):
+# COLOR on edges isn't supported in GEXF
+# ,r="",g="",b="") :
self.id =id
self._graph=graph
if self._graph.nodeExists(source) :
self._source=source
else :
raise Exception("source "+source+" node unknown, add nodes to graph first")
if self._graph.nodeExists(target) :
self._target=target
else:
raise Exception("target "+target+" node unknown, add nodes to graph first")
self.start=start
self.end=end
self.weight=weight
self.label=label
self._attributes=[]
- self.setColor(r,g,b)
+ # COLOR on edges isn't supported in GEXF
+# self.setColor(r,g,b)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkEdgeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
if not self.start == "":
edgeXML.set("start",self.start)
if not self.end == "":
edgeXML.set("end",self.end)
if not self.weight == "":
edgeXML.set("weight",str(self.weight))
if not self.label == "":
edgeXML.set("label",str(self.label))
-
- if not self.r=="" and not self.g=="" and not self.b=="" :
- #color : <viz:color r="239" g="173" b="66"/>
- colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.1draft/viz}color")
- colorXML.set("r",self.r)
- colorXML.set("g",self.g)
- colorXML.set("b",self.b)
+
+# COLOR on edges isn't supported in GEXF
+# if not self.r=="" and not self.g=="" and not self.b=="" :
+# #color : <viz:color r="239" g="173" b="66"/>
+# colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.1draft/viz}color")
+# colorXML.set("r",self.r)
+# colorXML.set("g",self.g)
+# colorXML.set("b",self.b)
attributesXML = etree.SubElement(edgeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
return edgeXML
except Exception as e:
print self._source+" "+self._target
print e
exit()
-
- def setColor(self,r,g,b) :
- self.r=r
- self.g=g
- self.b=b
+# COLOR on edges isn't supported in GEXF
+# def setColor(self,r,g,b) :
+# self.r=r
+# self.g=g
+# self.b=b
\ No newline at end of file
|
paulgirard/pygexf
|
004ed80923a57b1b2f06db00e26b8fab5dce8b97
|
correct bugs viz color on edges
|
diff --git a/gexf.py b/gexf.py
index 9c56917..d6980d4 100644
--- a/gexf.py
+++ b/gexf.py
@@ -1,355 +1,356 @@
# -*- coding: utf-8 -*-
from lxml import etree
from datetime import *
# missing features :
# load, validate, modify existing gexf file
# slices / phylogeny / ...
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
# add a test based on existing example from gexf.net
# add modification accessors like setStart ...
# factorize attribute managment by creating an attribute class
# add a test code utility to check that code will not use _variable outside objects
class Gexf :
def __init__(self,creator,description):
self.creator=creator
self.description=description
self.graphs=[]
self.xmlns="http://www.gephi.org/gexf/1.1draft"
self.xsi="http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.1draft.xsd"
self.viz="http://www.gexf.net/1.1draft/viz"
self.version="1.1"
def addGraph(self,type,mode,label):
g = Graph(type,mode,label)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified",datetime.now().isoformat())
etree.SubElement(meta, "creator").text=self.creator
etree.SubElement(meta, "description").text=self.description
for graph in self.graphs :
gexfXML.append(graph.getXML())
return gexfXML
def write(self,file):
file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8'))
self.print_stat()
def print_stat(self) :
for graph in self.graphs :
graph.print_stat()
class Graph :
def __init__(self,type,mode,label,start="",end="") :
# control variable
self.authorizedType=("directed","undirected")
self.authorizedMode=("dynamic","static")
self.defaultType="directed"
self.defaultMode="static"
self.label=label
if type in self.authorizedType :
self.type=type
else :
self.type=self.defaultType
if mode in self.authorizedMode :
self.mode=mode
else :
self.mode=self.defaultMode
self.start=start
self.end = end
self._nodesAttributes={}
self._edgesAttributes={}
self._nodes={}
self._edges={}
def addNode(self,id,label,start="",end="",pid="") :
self._nodes[id]=Node(self,id,label,start,end,pid)
return self._nodes[id]
def nodeExists(self,id) :
if id in self._nodes.keys():
return 1
else :
return 0
def addEdge(self,id,source,target,weight="",start="",end="",label="") :
self._edges[id]=Edge(self,id,source,target,weight,start,end,label)
return self._edges[id]
def addNodeAttribute(self,title,defaultValue,type="integer",mode="static") :
# add to NodeAttributes
# generate id
id=len(self._nodesAttributes)
self._nodesAttributes[id]={"title":title , "default":defaultValue, "mode":mode, "type":type} # modify Nodes with default
#: bad idea and unecessary
#for node in self._nodes.values():
# node.addAttribute(id,defaultValue)
return id
def addDefaultAttributesToNode(self,node) :
# add existing nodesattributes default values
for id,values in self._nodesAttributes.iteritems() :
node.addAttribute(id,values["default"])
def checkNodeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._nodesAttributes.keys() :
if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static"):
# add to NodeAttributes
# generate id
id=len(self._edgesAttributes)
self._edgesAttributes[id]={"title":title, "default":defaultValue, "mode":mode, "type":type } # modify Nodes with default
#for edge in self._edges.values():
# edge.addAttribute(id,defaultValue)
def addDefaultAttributesToEdge(self,edge) :
# add existing nodesattributes default values
for id,values in self._edgesAttributes.iteritems() :
edge.addAttribute(id,values["default"])
def checkEdgeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._edgesAttributes.keys() :
if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label)
attributesXMLNodeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeDynamic.set("class","node")
attributesXMLNodeDynamic.set("mode","dynamic")
attributesXMLNodeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeStatic.set("class","node")
attributesXMLNodeStatic.set("mode","static")
for id,value in self._nodesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLNodeStatic
else :
attxml=attributesXMLNodeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
attributesXMLEdgeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeDynamic.set("class","edge")
attributesXMLEdgeDynamic.set("mode","dynamic")
attributesXMLEdgeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeStatic.set("class","edge")
attributesXMLEdgeStatic.set("mode","static")
for id,value in self._edgesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLEdgeStatic
else :
attxml=attributesXMLEdgeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
nodesXML = etree.SubElement(graphXML, "nodes")
for node in self._nodes.values() :
nodesXML.append(node.getXML())
edgesXML = etree.SubElement(graphXML, "edges")
for edge in self._edges.values() :
edgesXML.append(edge.getXML())
return graphXML
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="") :
self.id =id
self.label=label
self.start=start
self.end=end
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkNodeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
nodeXML = etree.Element("node",id=self.id,label=str(self.label))
if not self.start == "":
nodeXML.set("start",self.start)
if not self.end == "":
nodeXML.set("end",self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
attributesXML = etree.SubElement(nodeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception as e:
print self.label
print self._attributes
print e
exit()
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class Edge :
def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="") :
self.id =id
self._graph=graph
if self._graph.nodeExists(source) :
self._source=source
else :
raise Exception("source "+source+" node unknown, add nodes to graph first")
if self._graph.nodeExists(target) :
self._target=target
else:
raise Exception("target "+target+" node unknown, add nodes to graph first")
self.start=start
self.end=end
self.weight=weight
self.label=label
self._attributes=[]
+ self.setColor(r,g,b)
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkEdgeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
if not self.start == "":
edgeXML.set("start",self.start)
if not self.end == "":
edgeXML.set("end",self.end)
if not self.weight == "":
edgeXML.set("weight",str(self.weight))
if not self.label == "":
edgeXML.set("label",str(self.label))
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
- colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
+ colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
attributesXML = etree.SubElement(edgeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
return edgeXML
except Exception as e:
print self._source+" "+self._target
print e
exit()
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
\ No newline at end of file
|
paulgirard/pygexf
|
81497f7b1ec6a6a2a671ff0a848c243bb64082a4
|
add viz color to edges
|
diff --git a/gexf.py b/gexf.py
index af93d4a..9c56917 100644
--- a/gexf.py
+++ b/gexf.py
@@ -1,342 +1,355 @@
# -*- coding: utf-8 -*-
from lxml import etree
from datetime import *
# missing features :
# load, validate, modify existing gexf file
# slices / phylogeny / ...
# evolution ideas :
# add display stats on graph composition when exportingto xml
# add anti-paralell edges test
# add a test based on existing example from gexf.net
# add modification accessors like setStart ...
# factorize attribute managment by creating an attribute class
# add a test code utility to check that code will not use _variable outside objects
class Gexf :
def __init__(self,creator,description):
self.creator=creator
self.description=description
self.graphs=[]
self.xmlns="http://www.gephi.org/gexf/1.1draft"
self.xsi="http://www.w3.org/2001/XMLSchema-instance"
self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.1draft.xsd"
self.viz="http://www.gexf.net/1.1draft/viz"
self.version="1.1"
def addGraph(self,type,mode,label):
g = Graph(type,mode,label)
self.graphs.append(g)
return g
def getXML(self):
gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})
# gexfXML.set("xmlnsxsi",)
gexfXML.set("{xsi}schemaLocation",self.schemaLocation)
meta = etree.SubElement(gexfXML, "meta")
meta.set("lastmodified",datetime.now().isoformat())
etree.SubElement(meta, "creator").text=self.creator
etree.SubElement(meta, "description").text=self.description
for graph in self.graphs :
gexfXML.append(graph.getXML())
return gexfXML
def write(self,file):
file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8'))
self.print_stat()
def print_stat(self) :
for graph in self.graphs :
graph.print_stat()
class Graph :
def __init__(self,type,mode,label,start="",end="") :
# control variable
self.authorizedType=("directed","undirected")
self.authorizedMode=("dynamic","static")
self.defaultType="directed"
self.defaultMode="static"
self.label=label
if type in self.authorizedType :
self.type=type
else :
self.type=self.defaultType
if mode in self.authorizedMode :
self.mode=mode
else :
self.mode=self.defaultMode
self.start=start
self.end = end
self._nodesAttributes={}
self._edgesAttributes={}
self._nodes={}
self._edges={}
def addNode(self,id,label,start="",end="",pid="") :
self._nodes[id]=Node(self,id,label,start,end,pid)
return self._nodes[id]
def nodeExists(self,id) :
if id in self._nodes.keys():
return 1
else :
return 0
def addEdge(self,id,source,target,weight="",start="",end="",label="") :
self._edges[id]=Edge(self,id,source,target,weight,start,end,label)
return self._edges[id]
def addNodeAttribute(self,title,defaultValue,type="integer",mode="static") :
# add to NodeAttributes
# generate id
id=len(self._nodesAttributes)
self._nodesAttributes[id]={"title":title , "default":defaultValue, "mode":mode, "type":type} # modify Nodes with default
#: bad idea and unecessary
#for node in self._nodes.values():
# node.addAttribute(id,defaultValue)
return id
def addDefaultAttributesToNode(self,node) :
# add existing nodesattributes default values
for id,values in self._nodesAttributes.iteritems() :
node.addAttribute(id,values["default"])
def checkNodeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._nodesAttributes.keys() :
if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static"):
# add to NodeAttributes
# generate id
id=len(self._edgesAttributes)
self._edgesAttributes[id]={"title":title, "default":defaultValue, "mode":mode, "type":type } # modify Nodes with default
#for edge in self._edges.values():
# edge.addAttribute(id,defaultValue)
def addDefaultAttributesToEdge(self,edge) :
# add existing nodesattributes default values
for id,values in self._edgesAttributes.iteritems() :
edge.addAttribute(id,values["default"])
def checkEdgeAttribute(self,id,value,start,end):
# check conformity with type is missing
if id in self._edgesAttributes.keys() :
if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :
raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")
return 1
else :
raise Exception("attribute id unknown. Add Attribute to graph first")
def getXML(self) :
# return lxml etree element
graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label)
attributesXMLNodeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeDynamic.set("class","node")
attributesXMLNodeDynamic.set("mode","dynamic")
attributesXMLNodeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLNodeStatic.set("class","node")
attributesXMLNodeStatic.set("mode","static")
for id,value in self._nodesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLNodeStatic
else :
attxml=attributesXMLNodeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
attributesXMLEdgeDynamic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeDynamic.set("class","edge")
attributesXMLEdgeDynamic.set("mode","dynamic")
attributesXMLEdgeStatic = etree.SubElement(graphXML, "attributes")
attributesXMLEdgeStatic.set("class","edge")
attributesXMLEdgeStatic.set("mode","static")
for id,value in self._edgesAttributes.iteritems() :
if value["mode"]=="static" :
attxml=attributesXMLEdgeStatic
else :
attxml=attributesXMLEdgeDynamic
attributeXML=etree.SubElement(attxml, "attribute")
attributeXML.set("id",str(id))
attributeXML.set("title",value["title"])
attributeXML.set("type",value["type"])
etree.SubElement(attributeXML, "default").text=value["default"]
nodesXML = etree.SubElement(graphXML, "nodes")
for node in self._nodes.values() :
nodesXML.append(node.getXML())
edgesXML = etree.SubElement(graphXML, "edges")
for edge in self._edges.values() :
edgesXML.append(edge.getXML())
return graphXML
def print_stat(self):
print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end
print "number of nodes : "+str(len(self._nodes))
print "number of edges : "+str(len(self._edges))
class Node :
def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="") :
self.id =id
self.label=label
self.start=start
self.end=end
self.pid=pid
self._graph=graph
self.setColor(r,g,b)
if not self.pid=="" :
if not self._graph.nodeExists(self.pid) :
raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")
self._attributes=[]
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToNode(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkNodeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
nodeXML = etree.Element("node",id=self.id,label=str(self.label))
if not self.start == "":
nodeXML.set("start",self.start)
if not self.end == "":
nodeXML.set("end",self.end)
if not self.pid == "":
nodeXML.set("pid",self.pid)
attributesXML = etree.SubElement(nodeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
if not self.r=="" and not self.g=="" and not self.b=="" :
#color : <viz:color r="239" g="173" b="66"/>
colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
colorXML.set("r",self.r)
colorXML.set("g",self.g)
colorXML.set("b",self.b)
return nodeXML
except Exception as e:
print self.label
print self._attributes
print e
exit()
def setColor(self,r,g,b) :
self.r=r
self.g=g
self.b=b
class Edge :
- def __init__(self,graph,id,source,target,weight="",start="",end="",label="") :
+ def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="") :
self.id =id
self._graph=graph
if self._graph.nodeExists(source) :
self._source=source
else :
raise Exception("source "+source+" node unknown, add nodes to graph first")
if self._graph.nodeExists(target) :
self._target=target
else:
raise Exception("target "+target+" node unknown, add nodes to graph first")
self.start=start
self.end=end
self.weight=weight
self.label=label
self._attributes=[]
# add existing nodesattributes default values : bad idea and unecessary
#self._graph.addDefaultAttributesToEdge(self)
def addAttribute(self,id,value,start="",end="") :
if self._graph.checkEdgeAttribute(id,value,start,end) :
self._attributes.append({"id":id,"value":value,"start":start,"end":end})
def getXML(self) :
# return lxml etree element
try :
edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))
if not self.start == "":
edgeXML.set("start",self.start)
if not self.end == "":
edgeXML.set("end",self.end)
if not self.weight == "":
edgeXML.set("weight",str(self.weight))
if not self.label == "":
edgeXML.set("label",str(self.label))
+
+ if not self.r=="" and not self.g=="" and not self.b=="" :
+ #color : <viz:color r="239" g="173" b="66"/>
+ colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")
+ colorXML.set("r",self.r)
+ colorXML.set("g",self.g)
+ colorXML.set("b",self.b)
+
attributesXML = etree.SubElement(edgeXML, "attvalues")
for atts in self._attributes :
attributeXML=etree.SubElement(attributesXML, "attvalue")
attributeXML.set("for",str(atts["id"]))
attributeXML.set("value",atts["value"])
if not atts["start"]=="" :
attributeXML.set("start",atts["start"])
if not atts["end"]=="" :
attributeXML.set("end",atts["end"])
return edgeXML
except Exception as e:
print self._source+" "+self._target
print e
exit()
+
+ def setColor(self,r,g,b) :
+ self.r=r
+ self.g=g
+ self.b=b
\ No newline at end of file
|
paulgirard/pygexf
|
d521a3790584de8511248f2a12c47f681063b6a1
|
add __init__.py package descriptor
|
diff --git a/__init__.py b/__init__.py
new file mode 100644
index 0000000..e69de29
|
andermic/CS531
|
c64966adb4ee5a9e41cf27b7890128a48bf0d639
|
Finished prog4 write-up
|
diff --git a/prog4/.notes.txt.swp b/prog4/.notes.txt.swp
deleted file mode 100644
index 910bf31..0000000
Binary files a/prog4/.notes.txt.swp and /dev/null differ
diff --git a/prog4/.prog4.py.swp b/prog4/.prog4.py.swp
index 6829f54..6ab6a3b 100644
Binary files a/prog4/.prog4.py.swp and b/prog4/.prog4.py.swp differ
diff --git a/prog4/notes.txt b/prog4/notes.txt
index da3e14f..b7a466c 100644
--- a/prog4/notes.txt
+++ b/prog4/notes.txt
@@ -1,21 +1,28 @@
get_action as shown on page 270. Modify alg so that agent only shoots if it has
sensed a blocking stench.
Should display the solution for a single problem, as well as the stats for the
solutions of multiple problems
ASTAR RETURNS A TUPLE OF ACTIONS,GOAL_SQUARE, INSTEAD OF JUST A LIST OF ACTIONS
Don't forget to update the knowledge base with the time and agent location
Knowledge base:
the square that glitters contains gold
Vocab:
Actions:
forward
turn(left) and turn(right)
grab
shoot
climb
report:
agent initially faces north
+
+abstract
+pseudocode
+encoded knowledge in first-order logic
+experimental setup
+results
+discussion/conclusion
diff --git a/prog4/output.txt b/prog4/output.txt
index 02904a0..d409335 100644
--- a/prog4/output.txt
+++ b/prog4/output.txt
@@ -1,217 +1,214 @@
============================== Prover9 ===============================
Prover9 (32) version 2009-11A, November 2009.
-Process 4995 was started by andermic on andermic-laptop,
-Wed Dec 1 21:40:31 2010
+Process 6039 was started by andermic on andermic-laptop,
+Thu Dec 2 07:04:04 2010
The command was "./prover9 -f input.txt".
============================== end of head ===========================
============================== INPUT =================================
% Reading from file input.txt
formulas(assumptions).
at(agent,sq00,t0).
cur = t0.
WumpusAlive.
haveArrow.
square(x) <-> x = sq00 | x = sq01 | x = sq02 | x = sq03 | x = sq10 | x = sq11 | x = sq12 | x = sq13 | x = sq20 | x = sq21 | x = sq22 | x = sq23 | x = sq30 | x = sq31 | x = sq32 | x = sq33.
adjacent(x,y) <-> square(x) & square(y) & (x = sq00 & y = sq01 | x = sq00 & y = sq10 | x = sq01 & y = sq00 | x = sq01 & y = sq02 | x = sq01 & y = sq11 | x = sq02 & y = sq01 | x = sq02 & y = sq03 | x = sq02 & y = sq12 | x = sq03 & y = sq02 | x = sq03 & y = sq13 | x = sq10 & y = sq00 | x = sq10 & y = sq11 | x = sq10 & y = sq20 | x = sq11 & y = sq01 | x = sq11 & y = sq10 | x = sq11 & y = sq12 | x = sq11 & y = sq21 | x = sq12 & y = sq02 | x = sq12 & y = sq11 | x = sq12 & y = sq13 | x = sq12 & y = sq22 | x = sq13 & y = sq03 | x = sq13 & y = sq12 | x = sq13 & y = sq23 | x = sq20 & y = sq10 | x = sq20 & y = sq21 | x = sq20 & y = sq30 | x = sq21 & y = sq11 | x = sq21 & y = sq20 | x = sq21 & y = sq22 | x = sq21 & y = sq31 | x = sq22 & y = sq12 | x = sq22 & y = sq21 | x = sq22 & y = sq23 | x = sq22 & y = sq32 | x = sq23 & y = sq13 | x = sq23 & y = sq22 | x = sq23 & y = sq33 | x = sq30 & y = sq20 | x = sq30 & y = sq31 | x = sq31 & y = sq21 | x = sq31 & y = sq30 | x = sq31 & y = sq32 | x = sq32 & y = sq22 | x = sq32 & y = sq31 | x = sq32 & y = sq33 | x = sq33 & y = sq23 | x = sq33 & y = sq32).
time(x) <-> x = t0 | x = t1 | x = t2 | x = t3 | x = t4 | x = t5 | x = t6 | x = t7 | x = t8 | x = t9 | x = t10 | x = t11 | x = t12 | x = t13 | x = t14 | x = t15 | x = t16 | x = t17 | x = t18 | x = t19 | x = t20 | x = t21 | x = t22 | x = t23 | x = t24 | x = t25 | x = t26 | x = t27 | x = t28 | x = t29 | x = t30 | x = t31 | x = t32 | x = t33 | x = t34 | x = t35 | x = t36 | x = t37 | x = t38 | x = t39 | x = t40 | x = t41 | x = t42 | x = t43 | x = t44 | x = t45 | x = t46 | x = t47 | x = t48 | x = t49 | x = t50 | x = t51 | x = t52 | x = t53 | x = t54 | x = t55 | x = t56 | x = t57 | x = t58 | x = t59 | x = t60 | x = t61 | x = t62 | x = t63 | x = t64 | x = t65 | x = t66 | x = t67 | x = t68 | x = t69 | x = t70 | x = t71 | x = t72 | x = t73 | x = t74 | x = t75 | x = t76 | x = t77 | x = t78 | x = t79 | x = t80 | x = t81 | x = t82 | x = t83 | x = t84 | x = t85 | x = t86 | x = t87 | x = t88 | x = t89 | x = t90 | x = t91 | x = t92 | x = t93 | x = t94 | x = t95 | x = t96 | x = t97 | x = t98 | x = t99.
visited(x) <-> (exists y (time(y) & at(agent,x,y))).
ok(x) <-> -pit(x) & -at(Wumpus,x,cur).
(exists x (square(x) & (exists y (time(y) & at(Wumpus,x,y))))) -> (all y all z (square(z) & x != z -> -at(Wumpus,z,y))).
(exists x (square(x) & (exists y (time(y) & at(Wumpus,x,y))))) & WumpusAlive -> at(Wumpus,x,cur).
-WumpusAlive -> (all x (square(x) -> -at(Wumpus,x,cur))).
breezy(x) <-> (exists y (adjacent(x,y) & pit(y))).
smelly(x) & WumpusAlive <-> (exists y (adjacent(x,y) & at(Wumpus,y,cur))).
end_of_list.
formulas(goals).
visited(sq33).
end_of_list.
============================== end of input ==========================
============================== PROCESS NON-CLAUSAL FORMULAS ==========
% Formulas that are not ordinary clauses:
1 square(x) <-> x = sq00 | x = sq01 | x = sq02 | x = sq03 | x = sq10 | x = sq11 | x = sq12 | x = sq13 | x = sq20 | x = sq21 | x = sq22 | x = sq23 | x = sq30 | x = sq31 | x = sq32 | x = sq33 # label(non_clause). [assumption].
Prover catching signal 2.
============================== STATISTICS ============================
Given=0. Generated=0. Kept=0. proofs=0.
Usable=0. Sos=0. Demods=0. Limbo=0, Disabled=0. Hints=0.
Kept_by_rule=0, Deleted_by_rule=0.
Forward_subsumed=0. Back_subsumed=0.
Sos_limit_deleted=0. Sos_displaced=0. Sos_removed=0.
New_demodulators=0 (0 lex), Back_demodulated=0. Back_unit_deleted=0.
Demod_attempts=0. Demod_rewrites=0.
Res_instance_prunes=0. Para_instance_prunes=0. Basic_paramod_prunes=0.
Nonunit_fsub_feature_tests=0. Nonunit_bsub_feature_tests=0.
Megabytes=0.17.
-User_CPU=0.04, System_CPU=0.00, Wall_clock=0.
+User_CPU=0.03, System_CPU=0.01, Wall_clock=0.
Megs malloced by palloc(): 20.
type (bytes each) gets frees in use bytes
chunk ( 104) 1080 1080 0 0.0 K
string_buf ( 8) 1029 1029 0 0.0 K
token ( 20) 2634 2634 0 0.0 K
pterm ( 16) 1348 1348 0 0.0 K
hashtab ( 8) 2 2 0 0.0 K
hashnode ( 8) 104 104 0 0.0 K
term ( 20) 8205 6981 1224 23.9 K
term arg arrays: 3.3 K
attribute ( 12) 1 0 1 0.0 K
ilist ( 8) 524 393 131 1.0 K
plist ( 8) 470 3 467 3.6 K
i2list ( 12) 134 134 0 0.0 K
just ( 12) 32 0 32 0.4 K
parajust ( 16) 0 0 0 0.0 K
instancejust ( 8) 0 0 0 0.0 K
ivyjust ( 24) 0 0 0 0.0 K
-formula ( 28) 3977 3189 788 21.5 K
- formula arg arrays: 9.3 K
+formula ( 28) 4939 3919 1020 27.9 K
+ formula arg arrays: 22.9 K
topform ( 52) 32 0 32 1.6 K
clist_pos ( 20) 0 0 0 0.0 K
clist ( 16) 0 0 0 0.0 K
context ( 808) 0 0 0 0.0 K
trail ( 12) 0 0 0 0.0 K
ac_match_pos (70044) 0 0 0 0.0 K
ac_match_free_vars_pos (20020)
0 0 0 0.0 K
btm_state ( 60) 0 0 0 0.0 K
btu_state ( 60) 0 0 0 0.0 K
ac_position (285432) 0 0 0 0.0 K
fpa_trie ( 20) 0 0 0 0.0 K
fpa_state ( 28) 0 0 0 0.0 K
fpa_index ( 12) 0 0 0 0.0 K
fpa_chunk ( 20) 0 0 0 0.0 K
fpa_list ( 16) 0 0 0 0.0 K
fpa_list chunks: 0.0 K
discrim ( 12) 0 0 0 0.0 K
discrim_pos ( 16) 0 0 0 0.0 K
flat2 ( 32) 0 0 0 0.0 K
flat ( 48) 0 0 0 0.0 K
flatterm ( 32) 0 0 0 0.0 K
mindex ( 28) 0 0 0 0.0 K
mindex_pos ( 56) 0 0 0 0.0 K
lindex ( 12) 0 0 0 0.0 K
clash ( 40) 0 0 0 0.0 K
di_tree ( 12) 0 0 0 0.0 K
avl_node ( 20) 0 0 0 0.0 K
Memory report, 1 @ 20 = 20 megs (0.16 megs used).
List 1, length 69, 0.3 K
-List 2, length 118, 0.9 K
+List 2, length 119, 0.9 K
List 3, length 46, 0.5 K
-List 4, length 201, 3.1 K
-List 5, length 361, 7.1 K
-List 6, length 7, 0.2 K
-List 7, length 276, 7.5 K
-List 8, length 5, 0.2 K
-List 9, length 4, 0.1 K
-List 10, length 4, 0.2 K
-List 11, length 20, 0.9 K
-List 12, length 34, 1.6 K
-List 13, length 87, 4.4 K
-List 14, length 54, 3.0 K
-List 15, length 19, 1.1 K
-List 16, length 3, 0.2 K
+List 4, length 203, 3.2 K
+List 5, length 362, 7.1 K
+List 6, length 14, 0.3 K
+List 7, length 84, 2.3 K
+List 8, length 20, 0.6 K
+List 9, length 9, 0.3 K
+List 10, length 5, 0.2 K
+List 11, length 11, 0.5 K
+List 12, length 12, 0.6 K
+List 13, length 10, 0.5 K
+List 16, length 1, 0.1 K
List 17, length 3, 0.2 K
List 18, length 1, 0.1 K
List 19, length 1, 0.1 K
List 20, length 1, 0.1 K
List 21, length 1, 0.1 K
List 22, length 1, 0.1 K
List 23, length 1, 0.1 K
List 24, length 1, 0.1 K
List 25, length 1, 0.1 K
List 26, length 415, 42.1 K
List 27, length 1, 0.1 K
List 28, length 1, 0.1 K
List 29, length 1, 0.1 K
List 30, length 1, 0.1 K
List 31, length 1, 0.1 K
List 32, length 1, 0.1 K
List 33, length 1, 0.1 K
List 34, length 1, 0.1 K
List 35, length 1, 0.1 K
List 36, length 1, 0.1 K
List 37, length 1, 0.1 K
List 38, length 1, 0.1 K
List 39, length 1, 0.2 K
List 40, length 1, 0.2 K
List 41, length 1, 0.2 K
List 42, length 1, 0.2 K
List 43, length 1, 0.2 K
List 44, length 1, 0.2 K
List 45, length 1, 0.2 K
List 46, length 1, 0.2 K
List 47, length 1, 0.2 K
-List 48, length 1, 0.2 K
+List 48, length 2, 0.4 K
List 49, length 1, 0.2 K
List 50, length 1, 0.2 K
List 51, length 1, 0.2 K
List 52, length 1, 0.2 K
List 53, length 1, 0.2 K
List 54, length 1, 0.2 K
List 55, length 1, 0.2 K
List 56, length 1, 0.2 K
List 57, length 1, 0.2 K
List 58, length 1, 0.2 K
List 59, length 1, 0.2 K
List 60, length 1, 0.2 K
List 61, length 1, 0.2 K
List 62, length 1, 0.2 K
List 63, length 1, 0.2 K
List 64, length 1, 0.2 K
List 65, length 1, 0.3 K
List 66, length 1, 0.3 K
List 67, length 1, 0.3 K
List 68, length 1, 0.3 K
List 69, length 1, 0.3 K
List 70, length 1, 0.3 K
List 71, length 1, 0.3 K
List 72, length 1, 0.3 K
List 73, length 1, 0.3 K
List 74, length 1, 0.3 K
List 75, length 1, 0.3 K
List 76, length 1, 0.3 K
List 77, length 1, 0.3 K
List 78, length 1, 0.3 K
List 79, length 1, 0.3 K
List 80, length 1, 0.3 K
List 81, length 1, 0.3 K
List 82, length 1, 0.3 K
List 83, length 1, 0.3 K
List 84, length 1, 0.3 K
List 85, length 1, 0.3 K
List 86, length 1, 0.3 K
List 87, length 1, 0.3 K
List 88, length 1, 0.3 K
List 89, length 1, 0.3 K
List 90, length 1, 0.4 K
List 91, length 1, 0.4 K
List 92, length 1, 0.4 K
List 93, length 1, 0.4 K
List 94, length 1, 0.4 K
List 95, length 1, 0.4 K
List 96, length 1, 0.4 K
List 97, length 1, 0.4 K
List 98, length 1, 0.4 K
List 99, length 1, 0.4 K
-List 320, length 1, 1.2 K
============================== SELECTOR REPORT =======================
Sos_deleted=0, Sos_displaced=0, Sos_size=0
SELECTOR PART PRIORITY ORDER SIZE SELECTED
============================== end of selector report ================
============================== end of statistics =====================
Exiting.
-Process 4995 exit (SIGINT) Wed Dec 1 21:40:31 2010
+Process 6039 exit (SIGINT) Thu Dec 2 07:04:04 2010
diff --git a/prog4/prog4.pdf b/prog4/prog4.pdf
new file mode 100644
index 0000000..451bc61
Binary files /dev/null and b/prog4/prog4.pdf differ
diff --git a/prog4/prog4.py b/prog4/prog4.py
index 757ba49..081d316 100644
--- a/prog4/prog4.py
+++ b/prog4/prog4.py
@@ -1,556 +1,556 @@
from os import system
from random import randint
from itertools import product
FILE_NAME = 'worlds.txt'
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
class WumpusWorld:
world = list()
def __init__(self, w):
if w == []:
self.world = self.make_random_world()
else:
self.world = w
# Generate a random wumpus world
def make_random_world(self):
# Make a dictionary for each square, which will hold whether that
# square contains a pit, wumpus, breeze, stench, or gold.
world = [[{'p':False,'w':False,'b':False,'s':False,'g':False} for i in range(4)] for j in range(4)]
# Make a wumpus and some gold on unique squares.
e = []
while len(e) != 2:
sq = randint(1,15)
row = sq / 4
col = sq % 4
if [row,col] in e:
continue
e.append([row,col])
# Make some pits on unique squares
for sq in range(1,15):
row = sq / 4
col = sq % 4
if [row,col] in e:
continue
if randint(1,5) == 1:
e.append([row,col])
# Populate world with wumpus and stenches
world[e[0][0]][e[0][1]]['w'] = True
if e[0][0] > 0:
world[e[0][0] - 1][e[0][1]]['s'] = True
if e[0][0] < 3:
world[e[0][0] + 1][e[0][1]]['s'] = True
if e[0][1] > 0:
world[e[0][0]][e[0][1] - 1]['s'] = True
if e[0][1] < 3:
world[e[0][0]][e[0][1] + 1]['s'] = True
# Place gold
world[e[1][0]][e[1][1]]['g'] = True
# Populate world with pits and breezes
for i in range(2, len(e)):
world[e[i][0]][e[i][1]]['p'] = True
if e[i][0] > 0:
world[e[i][0] - 1][e[i][1]]['b'] = True
if e[i][0] < 3:
world[e[i][0] + 1][e[i][1]]['b'] = True
if e[i][1] > 0:
world[e[i][0]][e[i][1] - 1]['b'] = True
if e[i][1] < 3:
world[e[i][0]][e[i][1] + 1]['b'] = True
return world
def display(self, loc):
system('clear')
print 'A - Agent'
print 'P - Pit'
print 'W - Wumpus'
print 'B - Breeze'
print 'S - Stench'
print 'G - Gold'
print
w = self.world
rows = range(4)
rows.reverse()
for r in rows:
print ' _______ _______ _______ _______'
rtext = '|'
for c in range(4):
rtext += '%d,%d |' % (c+1,r+1)
print rtext
rtext = '|'
for c in range(4):
rtext += ' %s |' % {True:'A', False:' '}[loc == [r,c]]
print rtext
rtext = ''
for c in range(4):
s = w[r][c]
rtext += '| '
for l in ['p','w','b','s','g']:
if s[l]:
rtext += l.upper()
else:
rtext += ' '
rtext += ' '
rtext += '|'
print rtext
print '|_______|_______|_______|_______|'
class HumanAgent:
loc = [0,0]
facing = NORTH
def get_action(self, percept):
ri = raw_input('\nTake an action by entering the corresponding letter in square brackets ([f]orward, turn [l]eft, turn [r]ight, [g]rab, [c]limb, [s]hoot): ')
return {'f':'forward','l':'turn_left','r':'turn_right','g':'grab','c':'climb','s':'shoot'}.get(ri)
class ComputerAgent:
KB = []
t = 0
plan = []
loc = [0,0]
facing = NORTH
KB_LOC = 0
KB_CUR = 1
KB_WA = 2
KB_HA = 3
# Initialize the agent by adding the atemporal physics of the wumpus world
# to the KB.
def __init__(self):
# Start the agent at location 0,0
self.KB.append('at(agent, sq00, t0)')
# Leave space for the current time
self.KB.append('cur = t0')
# In the beginning, the wumpus is alive and the agent has an arrow
self.KB.append('WumpusAlive')
self.KB.append('haveArrow')
# Define squares
squares = []
for i in range(4):
for j in range(4):
squares.append('sq%d%d' % (i,j))
self.KB.append('square(x) <-> ((x = %s' % (') | (x = ').join(squares)+ '))')
# Define adjacency
adj_list = []
for r1 in range(4):
for c1 in range(4):
for r2 in range(4):
for c2 in range(4):
if r1 == r2:
if abs(c1 - c2) == 1:
adj_list.append(['sq%d%d' % (r1,c1), 'sq%d%d' % (r2,c2)])
if c1 == c2:
if abs(r1 - r2) == 1:
adj_list.append(['sq%d%d' % (r1,c1), 'sq%d%d' % (r2,c2)])
adj_str = ' | '.join(('((x = %s) & (y = %s))' % (i[0],i[1])) for i in adj_list)
self.KB.append('adjacent(x,y) <-> square(x) & square(y) & (%s)' % adj_str)
# Define time
self.KB.append('time(x) <-> (%s)' % ' | '.join([('(x = t%d)' % i) for i in range(100)]) )
# Define visited
self.KB.append('visited(x) <-> (exists y ((time(y)) & (at(agent, x, y))))')
# A square is safe iff it contains no wumpus and no pit
self.KB.append('ok(x) <-> (-(pit(x)) & -(at(Wumpus, x, cur)))')
# If there was ever a wumpus in a square, there is no wumpus in any other square
self.KB.append('(exists x (square(x) & (exists y (time(y) & (at(Wumpus, x, y)))))) -> (all y( all z( (square(z) & (x != z)) -> -(at(Wumpus, z, y)))))')
# Once a wumpus is found to be at a square, it is always at that square unless it is killed
self.KB.append('((exists x (square(x) & (exists y (time(y) & (at(Wumpus, x, y)))))) & WumpusAlive) -> (at(Wumpus, x, cur))')
# If the wumpus is dead then there is no wumpus on any square
self.KB.append('(-WumpusAlive) -> (all x ((square(x)) -> (-(at(Wumpus, x, cur)))))')
# A square is breezy iff there is a pit that is adjacent to it
self.KB.append('breezy(x) <-> (exists y ((adjacent(x,y)) & pit(y)))')
# A square is smelly iff there is a wumpus that is adjacent to it
self.KB.append('(smelly(x) & WumpusAlive) <-> (exists y ((adjacent(x,y)) & (at(Wumpus, y, cur))))')
# Helper function for plan_route. Return the value of the smallest
# Manhattan Distance to a goal square from the current square.
def heur(self, cur_square, goals):
smallest = -1
for goal in goals:
dist = abs(cur_square[0] - goal[0]) + abs(cur_square[1] - goal[1])
if (smallest == -1) or (dist < smallest):
smallest = dist
return smallest
# Helper function for plan_route. Return the actions possible from the
# current square.
def actions(self, cur_square, facing):
min_actions = ['turn_left', 'turn_right']
if facing == NORTH:
if cur_square[0] == 3:
return min_actions
elif facing == EAST:
if cur_square[1] == 3:
return min_actions
elif facing == SOUTH:
if cur_square[0] == 0:
return min_actions
elif facing == WEST:
if cur_square[1] == 0:
return min_actions
return min_actions + ['forward']
# Helper function for plan_route. Insert a given node into the frontier to
# maintain a descending order by f value.
def insert(self, node, frontier):
for i in range(len(frontier)):
if node['f'] >= frontier[i]['f']:
frontier.insert(i,node)
return
frontier.append(node)
# Use A* to calculate a sequence of actions that will bring an agent from
# the given location to one of the goal locations
def plan_route(self, current, goals, allowed):
root = {}
root['sq'] = current[0]
root['facing'] = current[1]
root['g'] = 0
root['f'] = root['g'] + self.heur(root['sq'], goals)
root['parent'] = None
root['action'] = None
frontier = [root]
explored = []
while True:
if frontier == []:
return False
node = frontier.pop()
if node['sq'] in goals:
solution = []
while node[parent] != None:
solution.append(node['action'])
node = node['parent']
solution.reverse()
return solution, node['sq'], node['facing']
explored += [node['sq'], node['facing']]
for action in self.actions(node['sq'], node['facing']):
child = {}
child['sq'] = node['sq']
child['facing'] = node['facing']
if action == 'forward':
s = child['sq']
child['sq'] = {NORTH:[s[0]+1,s[1]], EAST:[s[0],s[1]+1], SOUTH:[s[0]-1,s[1]], WEST:[s[0],s[1]-1]}[child['facing']]
elif action == 'turn_right':
child['facing'] = (child['facing'] + 1) % 4
elif action == 'turn_left':
child['facing'] = (child['facing'] - 1) % 4
if child['sq'] not in allowed:
continue
child['g'] = node['g'] + 1
child['f'] = child['g'] + self.heur(child['sq'], goals)
child['parent'] = node
child['action'] = action
if [child['sq'], child['facing']] not in explored + [[i['sq'], i['facing']] for i in frontier]:
self.insert(child, frontier)
for i in range(len(frontier)):
if [child['sq'], child['facing']] == [frontier[i]['sq'], frontier[i]['facing']]:
if child['f'] < frontier[i]['f']:
frontier = frontier[:i] + frontier[i+1:]
self.insert(child, frontier)
# Use A* to calculate a sequence of actions that lines up a shot to a
# possible wumpus location, and then shoot.
def plan_shot(self, current, possible_wumpus, safe):
goals = []
for sq in safe:
if (sq[0] == possible_wumpus[0]) or (sq[1] == possible_wumpus[1]):
goals.append(safe)
if goals == []:
return []
actions, goal_square, goal_facing = self.plan_route([current[0],current[1]], goals, safe)
- if found_goal[0] == possible_wumpus[0]:
- if found_goal[1] > possible_wumpus[1]:
+ if goal_square[0] == possible_wumpus[0]:
+ if goal_square[1] > possible_wumpus[1]:
need_to_face = WEST
else:
need_to_face = EAST
else:
- if found_goal[0] > possible_wumpus[0]:
+ if goal_square[0] > possible_wumpus[0]:
need_to_face = SOUTH
else:
need_to_face = NORTH
if abs(need_to_face - goal_facing) == 2:
actions += ['turn_right', 'turn_right']
elif need_to_face - goal_facing == 1:
actions.append('turn_right')
elif need_to_face - goal_facing == -1:
actions.append('turn_left')
actions.append('shoot')
return actions
# Return a list of facts that correspond to a given percept
def make_percept_sentence(self, percept):
self.KB[self.KB_CUR] = 'cur = t%d' % self.t
self.KB[self.KB_LOC] = 'at(agent, sq%d%d, t%d)' % (self.loc[0],self.loc[1],self.t)
facts = []
if percept['stench']:
facts.append('smelly(sq%d%d)' % (self.loc[0], self.loc[1]))
if percept['breeze']:
facts.append('breezy(sq%d%d)' % (self.loc[0], self.loc[1]))
if percept['scream']:
KB[KB_WA] = '-WumpusAlive'
return facts
# Return a list of facts that correpond to a given action
def make_action_sentence(self, percept):
if percept['shoot']:
KB[KB_HA] = '-haveArrow'
return facts
# Give the theorem prover a query and the current KB, and see if the query
# is provably true
def ask(self, query):
stream = open('input.txt', 'w')
stream.write('formulas(assumptions).\n')
for fact in self.KB:
stream.write(' %s.\n' % fact)
stream.write('end_of_list.\n\n')
stream.write('formulas(goals).\n')
stream.write(' %s.\n' % query)
stream.write('end_of_list.')
stream.close()
system('./prover9 -f input.txt > output.txt')
status_line = open('input.txt', 'r').readlines()[-3]
if 'failure' in status_line:
return False
return True
# Add a set of facts to the KB
def tell(self, facts):
self.KB += facts
# Ask the agent to provide the best action given its current KB and the
- # current percept
+ # current percept. Based on Russell & Norvig p. 270.
def get_action(self, percept):
self.tell(self.make_percept_sentence(percept))
safe = [[i[0],i[1]] for i in product(range(4),range(4)) if self.ask('ok(sq%d%d)' % (i[0],i[1]))]
if percept['glitter']:
self.plan = ['grab'] + plan_route([self.loc,self.facing], [0,0], safe)[0] + ['climb']
if self.plan == []:
unvisited = set([])
for i in product(range(4),range(4)):
if not self.ask('visited(sq%d%d)' % (i[0],i[1])):
unvisted.append([i[0],i[1]])
self.plan = self.plan_route([self.loc,self.facing], [i for i in unvisited if i in safe], safe)[0]
if self.plan == [] and self.ask('haveArrow' % self.t):
possible_wumpus = [[i[0],i[1]] for i in product(range(4),range(4)) if not self.ask('-(at(Wumpus, sq%d%d, cur))' % (i[0],i[1]))]
self.plan = self.plan_shot([self.loc,self.facing], possible_wumpus, safe)
if self.plan == []:
not_unsafe = [[i[0],i[1]] for i in product(range(4),range(4)) if not self.ask('-(ok(sq%d%d))' % (i[0],i[1]))]
self.plan = self.plan_route([self.loc,self.facing], [i for i in unvisited if i in not_unsafe], safe)[0]
if self.plan == []:
self.plan = self.plan_route([self.loc,self.facing], [0,0], safe)[0] + ['climb']
action = self.plan[0]
self.plan = self.plan[1:]
t = t + 1
return action
class Simulation:
ww = None
agent = None
loc = [0,0]
facing = NORTH
has_arrow = True
# Initialize the simulation by storing the wumpus world given, and then
# run the simulation
def __init__(self, ww, agent):
self.ww = ww
self.agent = agent
self.run()
# Run the simulation by giving the agent percepts and asking for actions,
# until the agent dies or climbs out.
def run(self):
self.ww.display(self.loc)
print
print 'Agent is facing %s' % {0:'north', 1:'east', 2:'south', 3:'west'}[self.facing]
print 'Press enter to continue...'
raw_input()
scream = False
bump = False
while True:
# Construct a percept
percept = {}
percept['stench'] = self.ww.world[self.loc[0]][self.loc[1]]['s']
percept['breeze'] = self.ww.world[self.loc[0]][self.loc[1]]['b']
percept['glitter'] = self.ww.world[self.loc[0]][self.loc[1]]['g']
percept['scream'] = scream
percept['bump'] = bump
print 'Current percept: %s' % str(percept)
# Get an action based on current percept
action = self.agent.get_action(percept)
# Process action
scream = False
bump = False
if action == 'forward':
if self.facing == NORTH:
if self.loc[0] == 3:
bump = True
else:
self.loc[0] += 1
if self.facing == EAST:
if self.loc[1] == 3:
bump = True
else:
self.loc[1] += 1
if self.facing == SOUTH:
if self.loc[0] == 0:
bump = True
else:
self.loc[0] -= 1
if self.facing == WEST:
if self.loc[1] == 0:
bump = True
else:
self.loc[1] -= 1
self.agent.loc = self.loc
agent_sq = self.ww.world[self.loc[0]][self.loc[1]]
if agent_sq['w']:
self.ww.display(self.loc)
print '\nYou were killed by the wumpus\n'
return
if agent_sq['p']:
self.ww.display(self.loc)
print '\nYou fell to your death down a pit\n'
return
elif action == 'turn_left':
self.facing = (self.facing - 1) % 4
self.agent.facing = self.facing
elif action == 'turn_right':
self.facing = (self.facing + 1) % 4
self.agent.facing = self.facing
elif action == 'grab':
if self.ww.world[self.loc[0]][self.loc[1]]['g']:
self.ww.world[self.loc[0]][self.loc[1]]['g'] = False
elif action == 'shoot':
dir = {NORTH:[self.loc[0]+1,4], EAST:[self.loc[1]+1,4], SOUTH:[0,self.loc[0]], WEST:[0,self.loc[1]]}[self.facing]
if self.has_arrow:
self.has_arrow = False
for i in range(*dir):
if self.facing % 2 == 0:
if self.ww.world[i][self.loc[1]]['w']:
self.ww.world[i][self.loc[1]]['w'] = False
scream = True
else:
if self.ww.world[self.loc[0]][i]['w']:
self.ww.world[self.loc[0]][i]['w'] = False
scream = True
elif action == 'climb':
if self.loc == [0,0]:
return
else:
print 'INVALID ACTION TAKEN'
exit()
self.ww.display(self.loc)
print
print 'Last action: %s' % action
print 'Agent is facing %s' % {0:'north', 1:'east', 2:'south', 3:'west'}[self.facing]
print 'Press enter to continue...'
raw_input()
# Generate 100 random wumpus worlds and write them to a file
def generate_worlds():
fstream = open(FILE_NAME, 'w')
for i in range(100):
w = WumpusWorld([])
fstream.write('%d\n' % i)
w.world.reverse()
for row in w.world:
for s in row:
fstream.write('|')
for l in ['p','w','b','s','g']:
if s[l]:
fstream.write(l.upper())
else:
fstream.write(' ')
fstream.write('\n')
fstream.write('\n')
fstream.close()
# Read pre-generated worlds from file
def read_worlds():
lines = open(FILE_NAME, 'r').readlines()
worlds = []
for w in range(100):
worlds.append([])
for r in range(4):
worlds[w].append([])
line = lines[w*6+r+1]
for c in range(4):
worlds[w][r].append({})
for l in range(5):
if line[c*6+1+l] == ' ':
worlds[w][r][c][['p','w','b','s','g'][l]] = False
else:
worlds[w][r][c][['p','w','b','s','g'][l]] = True
worlds[w].reverse()
worlds[w] = WumpusWorld(worlds[w])
return worlds
system('clear')
print 'Who will solve a wumpus world?'
print ' 1 - Human'
print ' 2 - Computer'
select = raw_input('Select: ')
if select not in ['1','2']:
print 'ERROR: INVALID SELECTION'
exit()
else:
select2 = raw_input('\nWhich wumpus world? [0-99] ')
if int(select2) not in range(100):
print 'ERROR: INVALID SELECTION'
else:
if select == '1':
Simulation(read_worlds()[int(select2)],HumanAgent())
if select == '2':
Simulation(read_worlds()[int(select2)],ComputerAgent())
diff --git a/prog4/prog4.tex b/prog4/prog4.tex
new file mode 100644
index 0000000..92f228f
--- /dev/null
+++ b/prog4/prog4.tex
@@ -0,0 +1,293 @@
+\documentclass[10 pt.]{article}
+\author{Michael Anderson}
+\title{Navigating Wumpus World Environments Using Theorem Proving Software}
+\begin{document}
+\maketitle
+\begin{abstract}
+In this brief report I investigate the feasibility of using theorem proving
+software alongside domain-specific routines to implement an agent that, as
+successfully as possible, navigates toy Wumpus World environments. For brevity,
+it is assumed that the reader is already familiar with the Wumpus World.
+
+The challenges of this project included the modeling of the Wumpus World and
+its various ideosyncracies in code, implementing an appropriate version of A*
+search that allowed the agent to move from one part of the world to another as
+quickly as possible, and the conversion of the ideosyncracies of the Wumpus
+World to first-order logic for the theorem prover.
+
+Although the Prover-9 package turned out to be far too slow in practice to be
+incorporated into an agent for this world, I learned much about first-order logic and
+theorem proving software that will be useful in future projects that require
+such tools.
+\end{abstract}
+\newpage
+\section{Implementation}
+\subsection{High Level Overview}
+The implemented system contains several interacting parts, some of which will
+be explained in further detail. All of the code was written in Python 2.4.3.
+
+The WumpusWorld class holds the 4 $\times$ 4
+grid, along with the locations of the pits, the wumpus, and the gold. It is
+also responsible for displaying the environment to the user, and it is
+capable of generating random Wumpus Worlds that conform to the constraints of
+the domain.
+
+The HumanAgent class gives the user the ability to take actions
+within a particular wumpus world, i.e. the user is the agent. The main purpose
+of this class is for testing, to ensure that the system responds appropriately
+as actions are taken by an agent.
+
+The ComputerAgent class is the meat of the project. This class is the
+implementation of an agent that can be given percepts as input and asked for
+actions as output, and its chief responsibility is to find the
+most reasonable action given what it has so far perceived about a wumpus world
+environment.
+
+Finally, the Simulation class acts as the controller. It iteratively gives
+percepts to a given agent (either human or computer), prompts it for actions,
+makes changes to the environment and the position of the agent based on those
+actions, and outputs information to the console.
+
+\subsection{Computer Agent}
+To interact successfully with a WW environment, the agent keeps several data
+members in memory. The agent is aware of its current location within the grid,
+the number of actions so far taken (the current time), the direction it is
+facing at any given moment, and the queue of actions that should be taken next
+if there are any (the "plan"), and the knowledge base.
+
+KB holds a list of all of the information that the agent has
+accumulated about the environment it is occupying, in a first-order logic
+format that is consistent with Prover-9's lexicon. When the agent
+is created, the KB is initialized with all of the atemporal "physics" of the
+environment, such as:
+
+\vspace{1 pc} \noindent Definition of a visited square:
+\[
+Visited(x) \leftrightarrow \exists y \; At(Agent, x, y)
+\]
+
+\vspace{1 pc} \noindent A square is breezy iff there is a pit that is adjacent to it:
+\[
+Breezy(x) \leftrightarrow \exists y \; Adjacent(x,y) \wedge Pit(y)
+\]
+
+\vspace{1 pc} \noindent A square is safe iff it contains no wumpus and no pit:
+\[
+OK(x) \leftrightarrow \neg Pit(x) \wedge \neg At(Wumpus, x, current\_time)
+\]
+
+As the agent explores the WW environment, it receives percepts that give it
+additional information that it can use to make inferences, such as where
+breezes and stenches are, whether the wumpus is still alive, and whether the
+agent still has an arrow to fire. All of this information is appended into the
+KB as it is received.
+
+\vspace{1 pc} The ComputerAgent class also contains several member functions.
+The important ones are plan\_route(), plan\_shot(), ask(), tell(), and
+get\_action().
+
+plan\_route() is responsible for finding the set of actions that move the agent
+from one square in the world to another. This is done by using a
+domain-specific implementation of A*, with the following pseudocode:
+
+\begin{verbatim}
+plan_route(self, current, facing, goals, allowed):
+ root_node <- A new node with the current square and facing the current direction
+ root_node.g <- 0
+ root_node.f <- root_node.g + calculate_heuristic(root_node.square, goals)
+ root_node.action <- NULL
+ root_node.parent <- NULL
+ frontier <- [root_node]
+ explored <- [ ]
+
+ loop:
+ if the frontier is empty:
+ return False
+ n = frontier.pop()
+ if n.square is one of the goals:
+ solution <- [ ]
+ while n has a parent:
+ solution <- solution + [n.action]
+ n <- n.parent
+ return solution, n.square, n.facing
+ explored <- explored + [n.square]
+ for each action that can be taken from n:
+ child <- A new node that is the same as n
+ if action is forward:
+ child.square <- child.square with new row/column, dependant on facing
+ elif action is turn_right:
+ child.facing <- child.facing turned 90 degrees clockwise
+ elif action is turn_left:
+ child.facing <- child.facing turned 90 degrees counter-clockwise
+ if child.square is not in allowed:
+ continue
+ child.g <- n.g + 1
+ child.f <- child.g + calculate_heuristic(child.square, goals)
+ child.parent <- n
+ child.action <- action
+ if child.square is not in either explored or frontier:
+ add child to the frontier queue, keep the queue sorted by f
+ for each frontier_node in frontier:
+ if the child is in the frontier with a lower f cost:
+ remove the more expensive node from frontier
+ add child to the frontier queue, keep the queue sorted by f
+\end{verbatim}
+
+The heuristic used in this A* algorithm is the minimum of the Manhattan
+Distances to the goal squares.
+
+\vspace{1 pc} plan\_shot is used when the agent wants to fire the arrow at
+where it thinks the wumpus might be. The agent must travel to the closest
+that lines up a shot with where the wumpus might be, and then plan to shoot in
+the appropriate direction. Pseudocode for it is:
+
+\begin{verbatim}
+plan_shot(self, cur_sq, cur_facing, possible_wumpus, safe):
+ goals <- the possible_wumpus squares that are also safe
+ if goals is empty then return
+ actions, goal_square, goal_facing = self.plan_route(cur_sq, cur_facing, goals, safe)
+ actions <- actions + [some turns to face the agent in the direction of the wumpus]
+ actions <- actions + [shoot]
+ return actions
+\end{verbatim}
+
+ask() takes a query, and returns true if the query can be inferred from the
+current KB, and false if it cannot. ask() constructs an input file with all of
+the current KB given as assumptions and the query given as the goal to be
+proved, in the format and lexicon that Prover-9 expects. ask() then executes
+Prover-9, and reads the contents of an output file to see if it was
+successful in finding a proof for the query.
+
+tell() is a one-liner that simply adds a given list of facts to the KB.
+
+get\_action() is the top-level function of ComputerAgent, that calls all of the
+others. It takes a percept, and returns the best action in the given situation.
+It is very similar to the hybrid-wumpus-agent function given on p. 270 of
+Russell \& Norvig. Its pseudocode is:
+
+\begin{verbatim}
+get_action(self, percept):
+ tell(make_percept_sentence(percept))
+ safe <- squares which ask(ok(square)) is true
+ if percept.glitter
+ plan <- [grab] + plan_route(current_sq, facing, starting_sq, safe) + [climb]
+ if plan is empty
+ unvisited <- squares such that ask(visited(square)) is false
+ plan <- plan_route(cur_sq, cur_facing, squares in both unvisited and safe, safe)
+ if plan is empty and ask(haveArrow,t)
+ possible_wumpus <- squares for which ask(-at(Wumpus, square, cur_time)) is false
+ plan <- plan_shot(cur_sq, cur_facing, possible_wumpus, safe)
+ if plan is empty
+ not_unsafe <- squares for which ask(-ok(square)) is false
+ plan <- plan_route(cur_sq, cur_facing, sqs in unvisited and not_unsafe, safe)
+ if plan is empty
+ plan <- plan_route(cur_sq, cur_facing, [1,1], safe) + ['climb']
+ action <- plan.pop()
+ time <- time + 1
+ return action
+\end{verbatim}
+
+\subsection{Simulation}
+The Simulation class is the top level controller of the system. Unlike the
+agent, it knows the entire state of the world. It takes an agent (either human
+or computer), feeds it percepts and
+then asks it for actions. Although it is actually implemented as a class, it
+could have easily been written as an equivalent stand-alone function with the
+following pseudocode:
+
+\begin{verbatim}
+simulation(WumpusWorld ww, Agent a):
+ ww.display()
+
+ loop
+ percept <- the condition of the world at the agent's current time and location
+ output percept to the console
+
+ action <- a.get_action(percept)
+
+ if action is forward
+ if the agent is not facing a wall
+ move the agent forward
+ else:
+ make next percept have a bump
+ if the agent has moves into a pit or wumpus then end the simulation
+ elif action is turn left
+ turn the agent 90 degrees counter-clockwise
+ elif action is turn right
+ turn the agent 90 degrees clockwise
+ elif action is grab
+ agent gets the gold if there is any
+ elif action is shoot
+ if the agent has an arrow
+ if the shot is lined up with the wumpus
+ remove the wumpus from the world
+ make next percept have a scream
+ elif action is climb
+ if agent.location is [1,1] then end the simulation
+ else:
+ output 'INVALID ACTION TAKEN' to the console
+ end simulation
+
+ output last action taken to the console
+ pause until the user presses a key
+\end{verbatim}
+
+\section{Experimental Setup}
+To experiment with various WW environments, it was also necessary to create a
+couple more minor stand-alone functions. generate\_worlds() was responsible for
+creating 100 random WW environments that conformed to the Wumpus World
+constraints, and then outputting them to a worlds.txt file. In this way,
+various experiments could be run on a single set of unchanging wumpus worlds,
+to reduce the effects of random chance. read\_worlds() is called at the
+beginning of every run of the program, and this function opens world.txt, and
+reads in its contents into an array of WumpusWorld instances. Once that occurs,
+the Simulation class can be instantiated and given any of those instances to
+work in.
+
+\section{Results}
+Unfortunately, the results of running the simulation on various wumpus worlds
+was not very successful. Each time the simulation gets an action from the
+ComputerAgent instance, ask() must be called dozens of times. However, even the
+initial KB is so large that Prover-9 cannot work quickly enough to make this
+feasible. After several minutes of working on even a single query, my computer
+was not able to complete the search for a proof. I do know that Prover-9 was
+actually working, and not just glitching out because I entered information
+incorrectly, because it outputs its progress as it performs its search, and it
+displays an error if it receives a statement in a format it cannot understand.
+Furthermore, Prover-9 worked quickly and correctly with simpler test problems.
+
+One inefficiency in my knowledge representation was that each square had its
+own constant variable, as did each time. This is because Prover-9 seemed to be
+unable to handle integer addition and subtraction except under highly
+restricted circumstances. This made the representation of adjacency rather
+large, because each pair of adjacent squares needed their own individual
+statement. If squares could have been represented by one variable instead of
+sixteen, perhaps the theorem prover would have run much faster. The number of
+statements to be processed seemed to be simply much too large.
+
+I also attempted to use the Vampire theorem prover, but was frustrated by the
+lack of documentation available online. Ultimately, the few examples that were
+given were not sufficient to demonstrate the functionality I wished to use.
+
+\section{Conclusion}
+Although the experiment failed, I believe that the system was generally
+well-designed. The Simulation and WumpusWorld classes worked correctly and the
+environment was accurately represented, confirmed by testing
+with a HumanAgent instance. The hybrid-wumpus-agent algorithm in the book
+made sense and it was fairly straightforward to implement my own version of it.
+Representing the characteristics of the wumpus
+world with first-order logic took some thought, the
+main concern was making sure that my representation was complete and gave the
+agent the knowledge base needed to make all of the inferences possible in a
+given situation. Once I decided on the knowledge that needed to be represented,
+converting that knowledge to first-order logic statements was not too difficult.
+
+As can often be expected, the most difficult part of the project was learning
+how to use new pieces of software, i.e. the theorem provers. With more time, it is
+possible I would have figured out how to fully use Vampire and had more luck
+with it, or found some sort of workaround within the mess that is Prover-9's
+documentation to the problem of not being able to use integer addition and
+subtraction. There also may have been other theorem provers out there that
+were worth trying.
+
+\end{document}
|
andermic/CS531
|
50aa9930d162ffb04c36be9f2d8feb2575183f1f
|
hw5, hw6, working on prog4
|
diff --git a/hw5/hw5.aux b/hw5/hw5.aux
new file mode 100644
index 0000000..f23e546
--- /dev/null
+++ b/hw5/hw5.aux
@@ -0,0 +1 @@
+\relax
diff --git a/hw5/hw5.log b/hw5/hw5.log
new file mode 100644
index 0000000..35b0223
--- /dev/null
+++ b/hw5/hw5.log
@@ -0,0 +1,166 @@
+This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) (format=pdflatex 2010.10.11) 11 NOV 2010 08:16
+entering extended mode
+ %&-line parsing enabled.
+**hw5.tex
+(./hw5.tex
+LaTeX2e <2005/12/01>
+Babel <v3.8h> and hyphenation patterns for english, usenglishmax, dumylang, noh
+yphenation, loaded.
+(/usr/share/texmf-texlive/tex/latex/base/article.cls
+Document Class: article 2005/09/16 v1.4f Standard LaTeX document class
+(/usr/share/texmf-texlive/tex/latex/base/size10.clo
+File: size10.clo 2005/09/16 v1.4f Standard LaTeX file (size option)
+)
+\c@part=\count79
+\c@section=\count80
+\c@subsection=\count81
+\c@subsubsection=\count82
+\c@paragraph=\count83
+\c@subparagraph=\count84
+\c@figure=\count85
+\c@table=\count86
+\abovecaptionskip=\skip41
+\belowcaptionskip=\skip42
+\bibindent=\dimen102
+)
+(/usr/share/texmf-texlive/tex/latex/graphics/graphicx.sty
+Package: graphicx 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texmf-texlive/tex/latex/graphics/keyval.sty
+Package: keyval 1999/03/16 v1.13 key=value parser (DPC)
+\KV@toks@=\toks14
+)
+(/usr/share/texmf-texlive/tex/latex/graphics/graphics.sty
+Package: graphics 2006/02/20 v1.0o Standard LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texmf-texlive/tex/latex/graphics/trig.sty
+Package: trig 1999/03/16 v1.09 sin cos tan (DPC)
+)
+(/etc/texmf/tex/latex/config/graphics.cfg
+File: graphics.cfg 2007/01/18 v1.5 graphics configuration of teTeX/TeXLive
+)
+Package graphics Info: Driver file: pdftex.def on input line 90.
+
+(/usr/share/texmf-texlive/tex/latex/pdftex-def/pdftex.def
+File: pdftex.def 2007/01/08 v0.04d Graphics/color for pdfTeX
+\Gread@gobject=\count87
+))
+\Gin@req@height=\dimen103
+\Gin@req@width=\dimen104
+)
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsmath.sty
+Package: amsmath 2000/07/18 v2.13 AMS math features
+\@mathmargin=\skip43
+
+For additional information on amsmath, use the `?' option.
+(/usr/share/texmf-texlive/tex/latex/amsmath/amstext.sty
+Package: amstext 2000/06/29 v2.01
+
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsgen.sty
+File: amsgen.sty 1999/11/30 v2.0
+\@emptytoks=\toks15
+\ex@=\dimen105
+))
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsbsy.sty
+Package: amsbsy 1999/11/29 v1.2d
+\pmbraise@=\dimen106
+)
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsopn.sty
+Package: amsopn 1999/12/14 v2.01 operator names
+)
+\inf@bad=\count88
+LaTeX Info: Redefining \frac on input line 211.
+\uproot@=\count89
+\leftroot@=\count90
+LaTeX Info: Redefining \overline on input line 307.
+\classnum@=\count91
+\DOTSCASE@=\count92
+LaTeX Info: Redefining \ldots on input line 379.
+LaTeX Info: Redefining \dots on input line 382.
+LaTeX Info: Redefining \cdots on input line 467.
+\Mathstrutbox@=\box26
+\strutbox@=\box27
+\big@size=\dimen107
+LaTeX Font Info: Redeclaring font encoding OML on input line 567.
+LaTeX Font Info: Redeclaring font encoding OMS on input line 568.
+\macc@depth=\count93
+\c@MaxMatrixCols=\count94
+\dotsspace@=\muskip10
+\c@parentequation=\count95
+\dspbrk@lvl=\count96
+\tag@help=\toks16
+\row@=\count97
+\column@=\count98
+\maxfields@=\count99
+\andhelp@=\toks17
+\eqnshift@=\dimen108
+\alignsep@=\dimen109
+\tagshift@=\dimen110
+\tagwidth@=\dimen111
+\totwidth@=\dimen112
+\lineht@=\dimen113
+\@envbody=\toks18
+\multlinegap=\skip44
+\multlinetaggap=\skip45
+\mathdisplay@stack=\toks19
+LaTeX Info: Redefining \[ on input line 2666.
+LaTeX Info: Redefining \] on input line 2667.
+) (./hw5.aux)
+\openout1 = `hw5.aux'.
+
+LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+ [1
+
+{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}]
+Underfull \hbox (badness 10000) in paragraph at lines 12--13
+
+ []
+
+
+Overfull \hbox (88.53429pt too wide) in paragraph at lines 14--51
+[][]
+ []
+
+
+Underfull \hbox (badness 10000) in paragraph at lines 59--63
+
+ []
+
+[2] [3]
+Underfull \hbox (badness 10000) in paragraph at lines 160--163
+
+ []
+
+[4] (./hw5.aux) )
+Here is how much of TeX's memory you used:
+ 1176 strings out of 95086
+ 13475 string characters out of 1183254
+ 71906 words of memory out of 1500000
+ 4384 multiletter control sequences out of 10000+50000
+ 8111 words of font info for 30 fonts, out of 1200000 for 2000
+ 28 hyphenation exceptions out of 8191
+ 27i,7n,21p,224b,244s stack positions out of 5000i,500n,6000p,200000b,5000s
+</usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmbx10.pfb></
+usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmmi10.pfb></usr/share/texmf-tex
+live/fonts/type1/bluesky/cm/cmmi7.pfb></usr/share/texmf-texlive/fonts/type1/blu
+esky/cm/cmr10.pfb></usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmr12.pfb></
+usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmr17.pfb></usr/share/texmf-texl
+ive/fonts/type1/bluesky/cm/cmr7.pfb></usr/share/texmf-texlive/fonts/type1/blues
+ky/cm/cmsy10.pfb>
+Output written on hw5.pdf (4 pages, 54800 bytes).
+PDF statistics:
+ 47 PDF objects out of 1000 (max. 8388607)
+ 0 named destinations out of 1000 (max. 131072)
+ 1 words of extra memory for PDF output out of 10000 (max. 10000000)
+
diff --git a/hw5/hw5.pdf b/hw5/hw5.pdf
new file mode 100644
index 0000000..3b9ba0a
Binary files /dev/null and b/hw5/hw5.pdf differ
diff --git a/hw5/hw5.tex b/hw5/hw5.tex
new file mode 100644
index 0000000..ea4f497
--- /dev/null
+++ b/hw5/hw5.tex
@@ -0,0 +1,167 @@
+\documentclass{article}
+\usepackage[pdftex]{graphicx}
+\usepackage{amsmath}
+\author{Michael Anderson}
+\title{Homework Set 5}
+\begin{document}
+\maketitle
+\newpage
+\begin{enumerate}
+\item[\textbf{7.1}]
+
+The set of possible models for the presence of pits and a wumpus in [1,3],[2,2], and [3,1] is:\\
+
+\begin{tabular}{ c c c c c c c l }
+
+& P in [1,3] & P in [2,2] & P in [3,1] & W in [1,3] & W in [2,2] & W in [3,1] & Notes\\
+1 & N & N & N & N & N & N & $\alpha_2$ \\
+2 & N & N & N & N & N & Y & $\alpha_2$ \\
+3 & N & N & N & N & Y & N & $\alpha_2$ \\
+4 & N & N & N & Y & N & N & $\alpha_2$, $\alpha_3$ \\
+5 & N & N & Y & N & N & N & $\alpha_2$ \\
+6 & N & N & Y & N & N & Y & $\alpha_2$ \\
+7 & N & N & Y & N & Y & N & $\alpha_2$ \\
+8 & N & N & Y & Y & N & N & $KB$, $\alpha_2$, $\alpha_3$ \\
+9 & N & Y & N & N & N & N & \\
+10 & N & Y & N & N & N & Y & \\
+11 & N & Y & N & N & Y & N & \\
+12 & N & Y & N & Y & N & N & $\alpha_3$ \\
+13 & N & Y & Y & N & N & N & \\
+14 & N & Y & Y & N & N & Y & \\
+15 & N & Y & Y & N & Y & N & \\
+16 & N & Y & Y & Y & N & N & $\alpha_3$ \\
+17 & Y & N & N & N & N & N & $\alpha_2$ \\
+18 & Y & N & N & N & N & Y & $\alpha_2$ \\
+19 & Y & N & N & N & Y & N & $\alpha_2$ \\
+20 & Y & N & N & Y & N & N & $\alpha_2$, $\alpha_3$ \\
+21 & Y & N & Y & N & N & N & $\alpha_2$ \\
+22 & Y & N & Y & N & N & Y & $\alpha_2$ \\
+23 & Y & N & Y & N & Y & N & $\alpha_2$ \\
+24 & Y & N & Y & Y & N & N & $\alpha_2$, $\alpha_3$ \\
+25 & Y & Y & N & N & N & N & \\
+26 & Y & Y & N & N & N & Y & \\
+27 & Y & Y & N & N & Y & N & \\
+28 & Y & Y & N & Y & N & N & $\alpha_3$ \\
+29 & Y & Y & Y & N & N & N & \\
+30 & Y & Y & Y & N & N & Y & \\
+31 & Y & Y & Y & N & Y & N & \\
+32 & Y & Y & Y & Y & N & N & $\alpha_3$ \\
+
+\end{tabular}
+
+Since in all models where $KB$ is true (only model 8), $\alpha_2$
+and $\alpha_3$ are also true, $KB \models \alpha_2$ and $KB \models \alpha_3$.
+
+\item[\textbf{7.2}]
+
+It is given that:
+
+$1: mythical \Rightarrow immortal$\\
+$2: \neg mythical \Rightarrow (mortal \wedge mammal)$\\
+$3: (immortal \vee mammal) \Rightarrow horned $\\
+$4: horned \Rightarrow magical$\\
+
+To attempt to prove $mythical$, assume $\neg mythical$ and look for a
+contradiction. By 2, this leads to $mortal$ and $mammal$, which leads to
+$horned$ and $magical$ by 3 and 4. Since no further inferences can be made, and
+since no contradiction is derived, it is not provable that the unicorn is
+mythical.
+
+Since $mythical$ is either true or false, by 1 and 2 $immortal \vee (mortal
+\wedge mammal)$. By 3, this implies $horned$, and then by 4 this implies
+$magical$. It is provable that the unicorn is magical and horned.
+
+\item[\textbf{7.6}]
+
+\begin{enumerate}
+\item[a)]
+True. By the property of monotonicity for KB's, adding to a KB cannot
+reduce the set of statements that it entails. It is given that $\alpha \models
+\gamma$ or $\beta \models \gamma$. If $\alpha \models \gamma$, then adding
+$\beta$ to $\alpha$ does not reduce its power to entail $\gamma$. Similarly, if
+$\beta \models \gamma$, then adding $\alpha$ does not reduce $\beta$'s power.
+
+\item[b)]
+True. By the truth table of $and$, knowing $(\beta \wedge \gamma)$ implies separately
+that $\beta$ is true and $\gamma$ is true. So any KB that entails $(\beta \wedge
+\gamma)$ also entails them separately.
+
+\item[c)]
+False. Given any arbitrary knowledge base, it can be said that the price of tea in
+China is either some arbitrary value $p$, or it is not. But if the knowledge base has nothing to do
+with tea whatsoever, than it does not entail that the price of tea in China is
+$p$, and it does not entail that it isn't either.
+
+\end{enumerate}
+
+\item[\textbf{7.10}]
+\begin{enumerate}
+\item[a)]
+Valid because implications cannot be false when their left and right sides have
+the same truth value.
+
+\item[b)]
+Neither. Not valid because if $Smoke$ is true and $Fire$ is false, the
+sentence is false. Not unsatisfiable because the sentence is satisfied if for
+example $Smoke$ and $Fire$ are both true.
+
+\item[c)]
+Neither. Not valid because the sentence is false if $Smoke$ is false and $Fire$
+is true. Not unsatisfiable because the sentence is satisfied if for example
+both $Smoke$ and $Fire$ are true.
+
+\item[d)]
+Valid because $Fire \vee \neg Fire$ is always true, and anything or'ed with
+that is true also.
+
+\item[e)]
+Valid because the sentence is true for all combinations of values of the three
+variables.
+
+\item[f)]
+Valid because the sentence is true for all combinations of values of the three
+variables.
+
+\item[g)]
+Valid because the sentence is true if any of $Big$, $Dumb$, or $Big \Rightarrow
+Dumb$ are true, and $Big \Rightarrow Dumb$ can only be false when $Big$ is true.
+\end{enumerate}
+
+\item[\textbf{7.22}]
+\begin{enumerate}
+\item[a)]
+$(X_{1,2} \wedge X_{2,1}) \vee (X_{1,2} \wedge X_{2,2}) \vee (X_{2,1} \wedge X_{2,2})$
+
+\item[b)]
+Make a disjunctive clause for each of the n choose k combinations of squares,
+and $or$ them together. Each combination represents one of the possible
+placements of k mines into the n neighbors. To turn this disjunctive form into
+CNF, use De Morgan's Laws and/or the distributive law.
+
+\item[c)]
+Use the process described in b) for every currently visible, numbered square on
+the board. Put all CNF clauses generated into DPLL. If DPLL returns a
+definitive value for a given square, than that square for certain does or does
+not contain a mine depending on the value returned. If it does not, then it is
+not provable that the square contains or does not contain a mine
+
+\item[d)]
+Since there are N choose M ways to place M mines into N squares, the number of
+clauses at any give point is $O(N choose M)$.
+
+\item[e)]
+If DPLL in c) does not return a definitive value for a square, it may still be
+provable that a square does not contain a mine due to the global constraint.
+
+\item[f)]
+\end{enumerate}
+
+\item[\textbf{7.26}]
+$FacingEast^{t+1} = (FacingEast^t \wedge (\neg TurnRight^t \wedge \neg TurnLeft^t))$ \\
+$ \vee (FacingSouth^t \wedge TurnLeft^t)$ \\
+$ \vee (FacingNorth^t \wedge TurnRight^t)$ \\
+
+$WumpusAlive^{t+1} = WumpusAlive^t \wedge \neg(Shoot^t \wedge Scream^{t+1}$)
+
+\end{enumerate}
+\end{document}
diff --git a/hw6/hw6.aux b/hw6/hw6.aux
new file mode 100644
index 0000000..f23e546
--- /dev/null
+++ b/hw6/hw6.aux
@@ -0,0 +1 @@
+\relax
diff --git a/hw6/hw6.log b/hw6/hw6.log
new file mode 100644
index 0000000..11509bf
--- /dev/null
+++ b/hw6/hw6.log
@@ -0,0 +1,316 @@
+This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) (format=pdflatex 2010.10.11) 18 NOV 2010 08:03
+entering extended mode
+ %&-line parsing enabled.
+**hw6.tex
+(./hw6.tex
+LaTeX2e <2005/12/01>
+Babel <v3.8h> and hyphenation patterns for english, usenglishmax, dumylang, noh
+yphenation, loaded.
+(/usr/share/texmf-texlive/tex/latex/base/article.cls
+Document Class: article 2005/09/16 v1.4f Standard LaTeX document class
+(/usr/share/texmf-texlive/tex/latex/base/size10.clo
+File: size10.clo 2005/09/16 v1.4f Standard LaTeX file (size option)
+)
+\c@part=\count79
+\c@section=\count80
+\c@subsection=\count81
+\c@subsubsection=\count82
+\c@paragraph=\count83
+\c@subparagraph=\count84
+\c@figure=\count85
+\c@table=\count86
+\abovecaptionskip=\skip41
+\belowcaptionskip=\skip42
+\bibindent=\dimen102
+)
+(/usr/share/texmf-texlive/tex/latex/graphics/graphicx.sty
+Package: graphicx 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texmf-texlive/tex/latex/graphics/keyval.sty
+Package: keyval 1999/03/16 v1.13 key=value parser (DPC)
+\KV@toks@=\toks14
+)
+(/usr/share/texmf-texlive/tex/latex/graphics/graphics.sty
+Package: graphics 2006/02/20 v1.0o Standard LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texmf-texlive/tex/latex/graphics/trig.sty
+Package: trig 1999/03/16 v1.09 sin cos tan (DPC)
+)
+(/etc/texmf/tex/latex/config/graphics.cfg
+File: graphics.cfg 2007/01/18 v1.5 graphics configuration of teTeX/TeXLive
+)
+Package graphics Info: Driver file: pdftex.def on input line 90.
+
+(/usr/share/texmf-texlive/tex/latex/pdftex-def/pdftex.def
+File: pdftex.def 2007/01/08 v0.04d Graphics/color for pdfTeX
+\Gread@gobject=\count87
+))
+\Gin@req@height=\dimen103
+\Gin@req@width=\dimen104
+)
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsmath.sty
+Package: amsmath 2000/07/18 v2.13 AMS math features
+\@mathmargin=\skip43
+
+For additional information on amsmath, use the `?' option.
+(/usr/share/texmf-texlive/tex/latex/amsmath/amstext.sty
+Package: amstext 2000/06/29 v2.01
+
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsgen.sty
+File: amsgen.sty 1999/11/30 v2.0
+\@emptytoks=\toks15
+\ex@=\dimen105
+))
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsbsy.sty
+Package: amsbsy 1999/11/29 v1.2d
+\pmbraise@=\dimen106
+)
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsopn.sty
+Package: amsopn 1999/12/14 v2.01 operator names
+)
+\inf@bad=\count88
+LaTeX Info: Redefining \frac on input line 211.
+\uproot@=\count89
+\leftroot@=\count90
+LaTeX Info: Redefining \overline on input line 307.
+\classnum@=\count91
+\DOTSCASE@=\count92
+LaTeX Info: Redefining \ldots on input line 379.
+LaTeX Info: Redefining \dots on input line 382.
+LaTeX Info: Redefining \cdots on input line 467.
+\Mathstrutbox@=\box26
+\strutbox@=\box27
+\big@size=\dimen107
+LaTeX Font Info: Redeclaring font encoding OML on input line 567.
+LaTeX Font Info: Redeclaring font encoding OMS on input line 568.
+\macc@depth=\count93
+\c@MaxMatrixCols=\count94
+\dotsspace@=\muskip10
+\c@parentequation=\count95
+\dspbrk@lvl=\count96
+\tag@help=\toks16
+\row@=\count97
+\column@=\count98
+\maxfields@=\count99
+\andhelp@=\toks17
+\eqnshift@=\dimen108
+\alignsep@=\dimen109
+\tagshift@=\dimen110
+\tagwidth@=\dimen111
+\totwidth@=\dimen112
+\lineht@=\dimen113
+\@envbody=\toks18
+\multlinegap=\skip44
+\multlinetaggap=\skip45
+\mathdisplay@stack=\toks19
+LaTeX Info: Redefining \[ on input line 2666.
+LaTeX Info: Redefining \] on input line 2667.
+) (./hw6.aux)
+\openout1 = `hw6.aux'.
+
+LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+ [1
+
+{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}]
+Underfull \hbox (badness 10000) in paragraph at lines 11--13
+
+ []
+
+
+Underfull \hbox (badness 10000) in paragraph at lines 14--20
+
+ []
+
+
+Underfull \hbox (badness 10000) in paragraph at lines 21--25
+
+ []
+
+[2]
+Overfull \hbox (61.35713pt too wide) in paragraph at lines 85--86
+[]$\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1 \OML/cmm/m/it/10 Occup
+ation\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1\OML/cmm/m/it/10 ; Sur
+geon\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ) \OT1/cmr/m/n/10 [\OMS/cmsy/m/n/10 9\OM
+L/cmm/m/it/10 p\OT1/cmr/m/n/10 2 \OML/cmm/m/it/10 Customer\OT1/cmr/m/n/10 (\OML
+/cmm/m/it/10 p\OT1/cmr/m/n/10 1\OML/cmm/m/it/10 ; p\OT1/cmr/m/n/10 2) \OMS/cmsy
+/m/n/10 ^ \OML/cmm/m/it/10 Occupation\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cm
+r/m/n/10 2\OML/cmm/m/it/10 ; Lawyer\OT1/cmr/m/n/10 )]$
+ []
+
+
+Overfull \hbox (112.89655pt too wide) detected at line 100
+\OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 s Breezy\OT1/cmr/m/n/10 (\O
+ML/cmm/m/it/10 s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ) 9\OML/cmm/m/it/10 r Adjace
+nt\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r; s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ^ \O
+ML/cmm/m/it/10 Pit\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r\OT1/cmr/m/n/10 )) \OMS/cm
+sy/m/n/10 ^ \OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 s \OMS/cmsy/m/n
+/10 :\OT1/cmr/m/n/10 [\OML/cmm/m/it/10 Breezy\OT1/cmr/m/n/10 (\OML/cmm/m/it/10
+s\OT1/cmr/m/n/10 )] \OMS/cmsy/m/n/10 ) :\OT1/cmr/m/n/10 [\OMS/cmsy/m/n/10 9\OML
+/cmm/m/it/10 r Adjacent\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r; s\OT1/cmr/m/n/10 )
+\OMS/cmsy/m/n/10 ^ \OML/cmm/m/it/10 Pit\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r\OT1/
+cmr/m/n/10 )])
+ []
+
+
+Overfull \hbox (97.34096pt too wide) detected at line 104
+\OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 s Breezy\OT1/cmr/m/n/10 (\O
+ML/cmm/m/it/10 s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ) 9\OML/cmm/m/it/10 r Adjace
+nt\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r; s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ^ \O
+ML/cmm/m/it/10 Pit\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r\OT1/cmr/m/n/10 )) \OMS/cm
+sy/m/n/10 ^ \OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 s Breezy\OT1/cm
+r/m/n/10 (\OML/cmm/m/it/10 s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 _ :\OT1/cmr/m/
+n/10 [\OMS/cmsy/m/n/10 9\OML/cmm/m/it/10 r Adjacent\OT1/cmr/m/n/10 (\OML/cmm/m/
+it/10 r; s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ^ \OML/cmm/m/it/10 Pit\OT1/cmr/m/n
+/10 (\OML/cmm/m/it/10 r\OT1/cmr/m/n/10 )])
+ []
+
+
+Overfull \hbox (97.34096pt too wide) detected at line 108
+\OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 s Breezy\OT1/cmr/m/n/10 (\O
+ML/cmm/m/it/10 s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ) 9\OML/cmm/m/it/10 r Adjace
+nt\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r; s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ^ \O
+ML/cmm/m/it/10 Pit\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r\OT1/cmr/m/n/10 )) \OMS/cm
+sy/m/n/10 ^ \OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 s \OMS/cmsy/m/n
+/10 :\OT1/cmr/m/n/10 [\OMS/cmsy/m/n/10 9\OML/cmm/m/it/10 r Adjacent\OT1/cmr/m/n
+/10 (\OML/cmm/m/it/10 r; s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ^ \OML/cmm/m/it/10
+ Pit\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r\OT1/cmr/m/n/10 )] \OMS/cmsy/m/n/10 _
+\OML/cmm/m/it/10 Breezy\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 s\OT1/cmr/m/n/10 ))
+ []
+
+
+Overfull \hbox (88.45203pt too wide) detected at line 112
+\OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 s Breezy\OT1/cmr/m/n/10 (\O
+ML/cmm/m/it/10 s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ) 9\OML/cmm/m/it/10 r Adjace
+nt\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r; s\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ^ \O
+ML/cmm/m/it/10 Pit\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r\OT1/cmr/m/n/10 )) \OMS/cm
+sy/m/n/10 ^ \OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 s \OMS/cmsy/m/n
+/10 9\OML/cmm/m/it/10 r Adjacent\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 r; s\OT1/cmr/
+m/n/10 ) \OMS/cmsy/m/n/10 ^ \OML/cmm/m/it/10 Pit\OT1/cmr/m/n/10 (\OML/cmm/m/it/
+10 r\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ) \OML/cmm/m/it/10 Breezy\OT1/cmr/m/n/10
+ (\OML/cmm/m/it/10 s\OT1/cmr/m/n/10 ))
+ []
+
+
+Overfull \hbox (45.4019pt too wide) detected at line 144
+\OT1/cmr/m/n/10 [\OMS/cmsy/m/n/10 9\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1\OML/cmm/
+m/it/10 ; p\OT1/cmr/m/n/10 2(\OMS/cmsy/m/n/10 :\OT1/cmr/m/n/10 (\OMS/cmsy/m/n/1
+0 9\OML/cmm/m/it/10 y\OT1/cmr/m/n/10 1\OML/cmm/m/it/10 ; z\OT1/cmr/m/n/10 1 (1
+\OML/cmm/m/it/10 < y\OT1/cmr/m/n/10 1) \OMS/cmsy/m/n/10 ^ \OT1/cmr/m/n/10 (\OML
+/cmm/m/it/10 y\OT1/cmr/m/n/10 1 \OML/cmm/m/it/10 < p\OT1/cmr/m/n/10 1) \OMS/cms
+y/m/n/10 ^ \OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 :\OT1/cmr/m/n/10 [(\OML/cmm/m/it/1
+0 y\OT1/cmr/m/n/10 1 \OMS/cmsy/m/n/10 ^^B \OML/cmm/m/it/10 z\OT1/cmr/m/n/10 1)
+\OML/cmm/m/it/10 < p\OT1/cmr/m/n/10 1] \OMS/cmsy/m/n/10 ^ :\OT1/cmr/m/n/10 [\OM
+L/cmm/m/it/10 p\OT1/cmr/m/n/10 1 \OML/cmm/m/it/10 < \OT1/cmr/m/n/10 (\OML/cmm/m
+/it/10 y\OT1/cmr/m/n/10 1 \OMS/cmsy/m/n/10 ^^B \OML/cmm/m/it/10 z\OT1/cmr/m/n/1
+0 1)])))\OMS/cmsy/m/n/10 ^
+ []
+
+
+Overfull \hbox (12.5616pt too wide) detected at line 146
+\OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 :\OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 9\OML/cmm/
+m/it/10 y\OT1/cmr/m/n/10 2\OML/cmm/m/it/10 ; z\OT1/cmr/m/n/10 2 (1 \OML/cmm/m/i
+t/10 < y\OT1/cmr/m/n/10 2) \OMS/cmsy/m/n/10 ^ \OT1/cmr/m/n/10 (\OML/cmm/m/it/10
+ y\OT1/cmr/m/n/10 2 \OML/cmm/m/it/10 < p\OT1/cmr/m/n/10 2) \OMS/cmsy/m/n/10 ^ \
+OT1/cmr/m/n/10 (\OMS/cmsy/m/n/10 :\OT1/cmr/m/n/10 [(\OML/cmm/m/it/10 y\OT1/cmr/
+m/n/10 2 \OMS/cmsy/m/n/10 ^^B \OML/cmm/m/it/10 z\OT1/cmr/m/n/10 2) \OML/cmm/m/i
+t/10 < p\OT1/cmr/m/n/10 2] \OMS/cmsy/m/n/10 ^ :\OT1/cmr/m/n/10 [\OML/cmm/m/it/1
+0 p\OT1/cmr/m/n/10 2 \OML/cmm/m/it/10 < \OT1/cmr/m/n/10 (\OML/cmm/m/it/10 y\OT1
+/cmr/m/n/10 2 \OMS/cmsy/m/n/10 ^^B \OML/cmm/m/it/10 z\OT1/cmr/m/n/10 2)])))\OMS
+/cmsy/m/n/10 ^
+ []
+
+
+Underfull \hbox (badness 10000) in paragraph at lines 152--177
+
+ []
+
+[3]
+Overfull \hbox (37.27252pt too wide) in paragraph at lines 181--183
+[]$\OMS/cmsy/m/n/10 9\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1 \OML/cmm/m/it/10 Stude
+nt\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1) \OMS/cmsy/m/n/10 ^ \OML
+/cmm/m/it/10 Took\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1\OML/cmm/m
+/it/10 ; Greek\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ^ \OML/cmm/m/it/10 Spring\OT1/
+cmr/m/n/10 2001(\OML/cmm/m/it/10 Greek\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ^ \OT1
+/cmr/m/n/10 [\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 2 (\OML/cmm/m/
+it/10 Student\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 2) \OMS/cmsy/m/
+n/10 ^
+ []
+
+
+Overfull \hbox (14.03604pt too wide) in paragraph at lines 189--191
+[]$\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 p \OT1/cmr/m/n/10 (\OML/cmm/m/it/10 UKBor
+n\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ^ \OT1/c
+mr/m/n/10 [(\OML/cmm/m/it/10 UKResident\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 Father
+\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 )) \OMS/cmsy/m/n/10 _ \OML/c
+mm/m/it/10 UKbyBirth\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 Father\OT1/cmr/m/n/10 (\O
+ML/cmm/m/it/10 p\OT1/cmr/m/n/10 )) \OMS/cmsy/m/n/10 _
+ []
+
+
+Overfull \hbox (64.98778pt too wide) in paragraph at lines 189--191
+\OML/cmm/m/it/10 UKbyDescent\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 Father\OT1/cmr/m/
+n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 ))) \OMS/cmsy/m/n/10 ^ \OT1/cmr/m/n/10
+(\OML/cmm/m/it/10 UKResident\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 Mother\OT1/cmr/m/
+n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 )) \OMS/cmsy/m/n/10 _ \OML/cmm/m/it/10
+UKbyBirth\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 Mother\OT1/cmr/m/n/10 (\OML/cmm/m/it
+/10 p\OT1/cmr/m/n/10 )) \OMS/cmsy/m/n/10 _
+ []
+
+
+Overfull \hbox (27.4387pt too wide) in paragraph at lines 191--192
+[]$\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 p \OT1/cmr/m/n/10 ([\OML/cmm/m/it/10 UKby
+Birth\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 Father\OT1/cmr/m/n/10 (\OML/cmm/m/it/10
+p\OT1/cmr/m/n/10 )) \OMS/cmsy/m/n/10 _ \OML/cmm/m/it/10 UKbyBirth\OT1/cmr/m/n/1
+0 (\OML/cmm/m/it/10 Mother\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 ))
+] \OMS/cmsy/m/n/10 ^ :\OML/cmm/m/it/10 UKBorn\OT1/cmr/m/n/10 (\OML/cmm/m/it/10
+p\OT1/cmr/m/n/10 )) \OMS/cmsy/m/n/10 )
+ []
+
+
+Overfull \hbox (33.57263pt too wide) in paragraph at lines 192--194
+[]$\OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1 \OML/cmm/m/it/10 Job\O
+T1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1\OML/cmm/m/it/10 ; Politician
+\OT1/cmr/m/n/10 ) \OMS/cmsy/m/n/10 ) \OT1/cmr/m/n/10 [(\OMS/cmsy/m/n/10 9\OML/c
+mm/m/it/10 p\OT1/cmr/m/n/10 2 \OMS/cmsy/m/n/10 8\OML/cmm/m/it/10 t Fool\OT1/cmr
+/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1\OML/cmm/m/it/10 ; p\OT1/cmr/m/n/10
+ 2\OML/cmm/m/it/10 ; t\OT1/cmr/m/n/10 )) \OMS/cmsy/m/n/10 ^ \OT1/cmr/m/n/10 (\O
+MS/cmsy/m/n/10 8\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 2 \OMS/cmsy/m/n/10 9\OML/cmm/
+m/it/10 t Fool\OT1/cmr/m/n/10 (\OML/cmm/m/it/10 p\OT1/cmr/m/n/10 1\OML/cmm/m/it
+/10 ; p\OT1/cmr/m/n/10 2\OML/cmm/m/it/10 ; t\OT1/cmr/m/n/10 )) \OMS/cmsy/m/n/10
+ ^
+ []
+
+[4] [5] (./hw6.aux) )
+Here is how much of TeX's memory you used:
+ 1177 strings out of 95086
+ 13493 string characters out of 1183254
+ 68906 words of memory out of 1500000
+ 4385 multiletter control sequences out of 10000+50000
+ 8111 words of font info for 30 fonts, out of 1200000 for 2000
+ 28 hyphenation exceptions out of 8191
+ 27i,6n,21p,224b,238s stack positions out of 5000i,500n,6000p,200000b,5000s
+</usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmbx10.pf
+b></usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmex10.pfb></usr/share/texmf
+-texlive/fonts/type1/bluesky/cm/cmmi10.pfb></usr/share/texmf-texlive/fonts/type
+1/bluesky/cm/cmmi5.pfb></usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmmi7.p
+fb></usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmr10.pfb></usr/share/texmf
+-texlive/fonts/type1/bluesky/cm/cmr12.pfb></usr/share/texmf-texlive/fonts/type1
+/bluesky/cm/cmr17.pfb></usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmr7.pfb
+></usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmsy10.pfb>
+Output written on hw6.pdf (5 pages, 64144 bytes).
+PDF statistics:
+ 58 PDF objects out of 1000 (max. 8388607)
+ 0 named destinations out of 1000 (max. 131072)
+ 1 words of extra memory for PDF output out of 10000 (max. 10000000)
+
diff --git a/hw6/hw6.pdf b/hw6/hw6.pdf
new file mode 100644
index 0000000..197eefa
Binary files /dev/null and b/hw6/hw6.pdf differ
diff --git a/hw6/hw6.tex b/hw6/hw6.tex
new file mode 100644
index 0000000..3c952f4
--- /dev/null
+++ b/hw6/hw6.tex
@@ -0,0 +1,198 @@
+\documentclass{article}
+\usepackage[pdftex]{graphicx}
+\usepackage{amsmath}
+\author{Michael Anderson}
+\title{Homework Set 6}
+\begin{document}
+\maketitle
+\newpage
+\begin{enumerate}
+\item[\textbf{8.3}]
+Each constant symbol in $c$ may be mapped to any of the objects in the domain
+D, so there are $D^c$ possible sets of mappings.\\
+
+$k$-ary relations contain a set
+permutations of size $k$ pulled from the set of constant objects, giving
+$P^c_k$ such permutations, each of which either is or is not contained within
+a given relation. Thus, there are $2^{P^c_k}$ possible k-ary relations. Since
+there are $p_k$ many orthogonal k-ary relations, there are
+$\prod^A_{k=1} 2^{(P^c_k)(p_k)}$ many possible sets of relations.\\
+
+In a $k$-ary function each of the $P^c_k$ tuples is mapped to one of the $c$
+constant symbols or the invisible object, giving $(P^c_k)(c+1)$ possible
+functions. There are then $\prod^A_{k=1} [(P^c_k)(c+1)]^{p_k}$ many possible
+sets of functions.\\
+
+Since the mappings of constant objects, the functions, and the relations are
+all orthogonal to each other, the total number of possible models is:
+\[
+(D^c)(\prod^A_{k=1} 2^{(P^c_k)(p_k)})(\prod^A_{k=1} [(P^c_k)(c+1)]^{p_k})
+\]
+
+\item[\textbf{8.9}]
+\begin{enumerate}
+\item[a)]
+\begin{enumerate}
+\item[i.] 2, because function arguments can only contain terms.
+\item[ii.] 1
+\item[iii.] 3, because this can be true if only one of Paris or Marseilles are in France.
+\end{enumerate}
+
+\item[b)]
+\begin{enumerate}
+\item[i.] 1
+\item[ii.] 3, because it is always true if $c$ can take non-country values.
+\item[iii.] 3, because it is always true if $c$ can take non-country values.
+\item[iv.] 2, because function arguments can only contain terms.
+\end{enumerate}
+
+\item[c)]
+\begin{enumerate}
+\item[i.] 3, because it is always false if $c$ can take non-country values.
+\item[ii.] 1
+\item[iii.] 3, because it is false even if c is ever not a country, and is also
+not in South America.
+\item[iv.] 3, because it is always false if $c$ can take non-country values.
+\end{enumerate}
+
+\item[d)]
+\begin{enumerate}
+\item[i.] 1
+\item[ii.] 1
+\item[iii.] 3, because it is true if some regions in Europe border a region in
+South America.
+\item[iv.] 1
+\end{enumerate}
+
+\item[e)]
+\begin{enumerate}
+\item[i.] 1
+\item[ii.] 1
+\item[iii.] 3, because it is false if x or y are not countries, or if they share
+a border, or they share a map color.
+\item[iv.] 2, because the grammar does not contain $\ne$.
+\end{enumerate}
+
+\end{enumerate}
+\item[\textbf{8.10}]
+\begin{enumerate}
+\item[a)] $Occupation(Emily, Surgeon) \vee Occupation(Emily, Lawyer)$
+\item[b)] $Occupation(Joe, Actor) \wedge [\exists o \; \neg(o=Actor) \wedge Occupation(Joe, o)]$
+\item[c)] $\forall p \; Occupation(p, Surgeon) \Rightarrow Occupation(p, Doctor)$
+\item[d)] $\neg[\exists p \; Occupation(p,Lawyer) \wedge Customer(Joe,p)]$
+\item[e)] $\exists p \; Boss(p,Emily) \wedge Occupation(p, Lawyer)$
+\item[f)] $\exists p1 \; [\forall p2 \; Customer(p2,p1) \Rightarrow Occupation(p2,Doctor)]$
+\item[g)] $\forall p1 \; Occupation(p1,Surgeon) \Rightarrow [\exists p2 \; Customer(p1,p2) \wedge Occupation(p2, Lawyer)]$
+\end{enumerate}
+
+\item[\textbf{8.13}]
+\begin{enumerate}
+\item[a)]
+\[
+\forall s \; Breezy(s) \Rightarrow \exists r \; Adjacent(r,s) \wedge Pit(r)
+\]\[
+\forall s \; \neg[Breezy(s)] \Rightarrow \neg[\exists r \; Adjacent(r,s) \wedge Pit(r)]
+\]
+Now reduce the conjunction to Equation (8.4):
+\[
+(\forall s \; Breezy(s) \Rightarrow \exists r \; Adjacent(r,s) \wedge Pit(r)) \wedge
+(\forall s \; \neg[Breezy(s)] \Rightarrow \neg[\exists r \; Adjacent(r,s) \wedge Pit(r)])
+\]
+\[
+(\forall s \; Breezy(s) \Rightarrow \exists r \; Adjacent(r,s) \wedge Pit(r)) \wedge
+(\forall s \; Breezy(s) \; \vee \; \neg[\exists r \; Adjacent(r,s) \wedge Pit(r)])
+\]
+\[
+(\forall s \; Breezy(s) \Rightarrow \exists r \; Adjacent(r,s) \wedge Pit(r)) \wedge
+(\forall s \; \neg[\exists r \; Adjacent(r,s) \wedge Pit(r)] \; \vee \; Breezy(s))
+\]
+\[
+(\forall s \; Breezy(s) \Rightarrow \exists r \; Adjacent(r,s) \wedge Pit(r)) \wedge
+(\forall s \; \exists r \; Adjacent(r,s) \wedge Pit(r) \Rightarrow Breezy(s))
+\]
+\[
+\forall s \; Breezy(s) \Leftrightarrow \exists r \; Adjacent(r,s) \wedge Pit(r)
+\]
+
+\item[b)]
+\[
+\forall s \; Pit(s) \Rightarrow [\forall r \; Adjacent(r,s) \Rightarrow Breezy(r)]
+\]
+This is insufficient, because we are only saying that a pit causes breezes in
+adjacent squares. Equation (8.4) also implies that a breeze causes a pit in one
+or more adjacent squares. Thus the following axiom is also necessary:
+\[
+\forall s \; Breezy(s) \Rightarrow \exists r \; Adjacent(r,s) \wedge Pit(r)
+\]
+\end{enumerate}
+
+\item[\textbf{8.20}]
+\begin{enumerate}
+\item[a)]
+\[
+\exists y \; \neg(y \times (1+1) < x) \wedge \neg(x < y \times (1+1))
+\]
+\item[b)]
+\[
+\neg(\exists y,z \; (1<y) \wedge (y<x) \wedge (\neg[(y \times z) < x] \wedge \neg[x < (y \times z)]))
+\]
+\item[c)]
+\[
+\forall x \; [\exists y \; \neg(y \times (1+1) < x) \wedge \neg(x < y \times (1+1))] \Rightarrow
+\]\[
+[\exists p1,p2 (\neg(\exists y1,z1 \; (1<y1) \wedge (y1<p1) \wedge(\neg[(y1 \times z1) < p1] \wedge \neg[p1 < (y1 \times z1)]))) \wedge
+\]\[
+(\neg(\exists y2,z2 \; (1<y2) \wedge (y2<p2) \wedge (\neg[(y2 \times z2) < p2] \wedge \neg[p2 < (y2 \times z2)]))) \wedge
+\]\[
+\neg[(p1+p2) < x] \wedge \neg[x < (p1+p2)]]
+\]
+\end{enumerate}
+
+\item[\textbf{8.24}]
+$Student(p)$: Predicate. Person p is a student.\\
+$Spring2001(c)$: Preciate. Class c was offered in Spring 2001.\\
+$Took(p, c)$: Predicate. Person p took class c.\\
+$Passed(p, c)$: Predicate. Person p passed class c.\\
+$Score(c)$: Function. Returns the best score in class c.\\
+$Higher(s1, s2)$: Predicate. Score s1 is higher than score s2.\\
+$Buy(p, o)$: Predicate. Person p buys policy o.\\
+$Smart(p)$: Predicate. Person p is smart.\\
+$Expensive(o)$: Predicate. Policy o is expensive.\\
+$Job(p, j)$: Predicate. Person p has job j.\\
+$Sell(p1, p2)$ Predicate. Person p1 sells policies to person p2.\\
+$Insured(p)$: Predicate. Person p is insured.\\
+$ManInTown(p)$: Predicate. Person p is a man in town.\\
+$Shaves(p1, p2)$: Predicate. Person p1 shaves person p2.\\
+$UKBorn(p)$: Predicate. Person p was born in the UK.\\
+$UKbyBirth(p)$: Predicate. Person p is a UK citizen by birth.\\
+$UKbyDescent(p)$: Predicate. Person p is a UK citizen by descent.\\
+$UKResident(p)$: Predicate. Person p is a UK Resident.\\
+$Father(p)$: Function. Returns the father of p.
+$Mother(p)$: Function. Returns the mother of p.
+$Fool(p1,p2,t)$ Predicate. Person p1 can fool person p2 at time t.\\
+$Speaks(x,l)$ Predicate. Person x speaks language l.\\
+$French, Greek$: Constants denoting classes.\\
+$Agent, Barber, Politician$: Constants denoting jobs.
+$Greek_person$: Constant denoting an ethnicity.\\
+
+\begin{enumerate}
+\item[a)] $\exists p \; Student(p) \wedge Took(p,French) \wedge Spring2001(French)$
+\item[b)] $\forall p \; [Student(p) \wedge Took(p,French)] \Rightarrow Passed(p,French)$
+\item[c)] $\exists p1 \; Student(p1) \wedge Took(p1,Greek) \wedge Spring2001(Greek)
+\wedge [\forall p2 \; (Student(p2) \wedge Took(p2,Greek) \wedge Spring2001(Greek)]]$
+\item[d)] $Higher(Score(Greek), Score(French))$
+\item[e)] $\forall p \; [\exists o \; Buy(p, o)] \Rightarrow Smart(p)$
+\item[f)] $\neg[\exists p,o \; Buy(p, o) \wedge Expensive(o)]$
+\item[g)] $\exists p1 \; Job(p1, Agent) \wedge [\forall p2 \; Sell(p1, p2) \Rightarrow \neg Insured(p2)]$
+\item[h)] $\exists p1 \; Job(p1, Barber) \wedge [\forall p2 \; (ManInTown(p2)
+\wedge \neg Shaves(p2, p2)) \Rightarrow Shaves(p1, p2)]$
+\item[i)] $\forall p \; (UKBorn(p) \wedge [(UKResident(Father(p)) \vee UKbyBirth(Father(p)) \vee UKbyDescent(Father(p)))
+\wedge (UKResident(Mother(p)) \vee UKbyBirth(Mother(p)) \vee UKbyDescent(Mother(p)))]) \Rightarrow UkbyBirth(p)$
+\item[j)] $\forall p \; ([UKbyBirth(Father(p)) \vee UKbyBirth(Mother(p))] \wedge \neg UKBorn(p)) \Rightarrow UKbyDescent(p)$
+\item[k)] $\forall p1 \; Job(p1,Politician) \Rightarrow [(\exists p2 \; \forall t \; Fool(p1,p2,t)) \wedge
+(\forall p2 \; \exists t \; Fool(p1,p2,t)) \wedge \neg(\forall p2,t \; Fool(p1,p2,t))]$
+\item[l)] $\forall p1,p2 [Greek\_person(p1) \wedge Greek\_person(p2)] \Rightarrow [\exists l \; Speaks(p1,l) \wedge Speaks(p2,l)]$
+\end{enumerate}
+
+\end{enumerate}
+\end{document}
diff --git a/prog3/.prog3.py.swp b/prog3/.prog3.py.swp
index 506e21b..042f940 100644
Binary files a/prog3/.prog3.py.swp and b/prog3/.prog3.py.swp differ
diff --git a/prog3/notes b/prog3/notes
new file mode 100644
index 0000000..4561639
--- /dev/null
+++ b/prog3/notes
@@ -0,0 +1,18 @@
+rule 1
+rule 2
+naked triples
+most constrained
+
+grade each problem
+is his conjecture correct?
+average number of filled in values by rules
+backtracking w/ and wo/ naked triples
+
+Try each problem:
+ With rule 1 (Easy?)
+ Rule 1 and rule 2 applied together over and over (Medium?)
+ " " and naked triples, report unfilled squares before backtracking, and compare w/ difficulty (H & E?)
+ Backtracking.
+ Count assignments. How many problems was it helpful in, and how much?
+ Most-constrained v. random
+ Naked triples v. no naked triples
diff --git a/prog3/prog3.py b/prog3/prog3.py
index b465507..c853ddb 100644
--- a/prog3/prog3.py
+++ b/prog3/prog3.py
@@ -1,314 +1,331 @@
from os import system # For clearing the screen
from itertools import product # product() takes the cartesian product of two lists
from copy import deepcopy # deepcopy() returns a deepcopy of an object
class Board:
b = list()
+ most_constrained = bool()
+ nakes_triples = bool()
+ no_calls = int()
- def __init__(self, board):
+ def __init__(self, board, naked, mc):
self.b = board
+ self.naked_triples = naked
+ self.most_constrained = mc
+ no_calls = 0
def display(self):
#system('clear')
print ' a b c d e f g h i'
for i in range(3):
for j in range(3):
print '%s ' % (i*3+j+1),
for k in range(3):
for l in range(3):
print self.b[i*3+j][k*3+l],
if k != 2:
print '|',
print
if i != 2:
print '------------------------'
# Calculate the domain of cell with row r and column c, by subtracting
# already assigned values in the same row, column, and box.
def get_domain(self, r, c):
# If the cell is already assigned, return the value assigned as the
# only value in that cell's domain.
if self.b[r][c] != '-':
return [self.b[r][c]]
# Domain initially contains all digits 1-9
result = [str(i) for i in range(1,10)]
# Filter out values in the same row
result = [i for i in result if i not in [self.b[r][j] for j in range(9)]]
# Filter out values in the same column
result = [i for i in result if i not in [self.b[j][c] for j in range(9)]]
# Filter out values in the same box
box_rows = range(r/3*3,(r/3+1)*3)
box_cols = range(c/3*3,(c/3+1)*3)
result = [i for i in result if i not in [self.b[j][k] for j,k in product(box_rows,box_cols)]]
return result
def get_domains(self):
domains = []
for i in range(9):
domains.append([])
for j in range(9):
domain = self.get_domain(i,j)
if domain == []:
return False
else:
domains[i].append(domain)
return domains
- def apply_rule1(self,naked_triples):
+ def apply_rule1(self):
# Calculate the domains of empty cells using get_domain(),
# which applies the row, column, and box constraints. When a cell has
# only one value in its domain, assign the cell that value. If after
# an iteration no assignments occur, then this technique has done all
# it can do, and so return. If a cell ever has an empty domain, return
# failure.
keep_going = True
+ inferences = []
while(keep_going):
keep_going = False
domains = self.get_domains()
if domains == False:
- return False
- if naked_triples:
+ return [False] + inferences
+ if self.naked_triples:
domains = self.apply_naked_triples(domains)
for i in range(9):
for j in range(9):
if self.b[i][j] == '-':
if len(domains[i][j]) == 1:
self.b[i][j] = domains[i][j][0]
+ inferences.append([i,j])
keep_going = True
- return True
+ return [True] + inferences
- def apply_rule2(self,naked_triples):
+ def apply_rule2(self):
# Calculate the domain of all empty cells using get_domain(). If a
# value is only in the domain of one cell within a row, column, or
# box, assign that value to that cell. Return after no assignments
# are made, and return failure if an empty domain is found, as in
# apply_rule1().
# For every row, column, and box, see if there are values in the domain
# of one cell that are not in the domains of other cells in that row,
# column, or box.
keep_going = True
- while(keep_going):
- keep_going = False
-
- # Get the initial domain of every cell. Return failure if any are
- # empty.
- domains = self.get_domains()
- if domains == False:
- return False
+ inferences = []
+ # Get the initial domain of every cell. Return failure if any are
+ # empty.
+ domains = self.get_domains()
+ if domains == False:
+ return [False] + inferences
- if naked_triples:
- domains = self.apply_naked_triples(domains)
+ if self.naked_triples:
+ domains = self.apply_naked_triples(domains)
- for i in range(1,10):
- si = str(i)
- for j in range(9):
- # Check for single domain instance of i in rows
- row_doms = [domains[j][k] for k in range(9) if len(domains[j][k]) != 1]
- if row_doms == []:
- continue
- count = reduce(lambda x,y: x+y, row_doms).count(si)
- if count == 1:
- for k in range(9):
- if si in domains[j][k]:
- self.b[j][k] = si
- keep_going = True
- break
- # " " in columns
- col_doms = [domains[k][j] for k in range(9) if len(domains[k][j]) != 1]
- if col_doms == []:
- continue
- count = reduce(lambda x,y: x+y, col_doms).count(si)
- if count == 1:
- for k in range(9):
- if si in domains[k][j]:
- self.b[k][j] = si
- keep_going = True
- break
- for j,k in product(range(3),range(3)):
- # " " in boxes
- box_rows = range(j*3,(j+1)*3)
- box_cols = range(k*3,(k+1)*3)
- box_doms = [domains[l][m] for l,m in product(box_rows,box_cols) if len(domains[l][m]) != 1]
- if box_doms == []:
- continue
- count = reduce(lambda x,y: x+y, box_doms).count(si)
- if count == 1:
- for l,m in product(box_rows,box_cols):
- if si in domains[l][m]:
- self.b[l][m] = si
- keep_going = True
- break
- return True
+ for i in range(1,10):
+ si = str(i)
+ for j in range(9):
+ # Check for single domain instance of i in rows
+ row_doms = [domains[j][c] for c in range(9) if len(domains[j][c]) != 1]
+ if row_doms == []:
+ continue
+ count = reduce(lambda x,y: x+y, row_doms).count(si)
+ if count == 1:
+ for c in range(9):
+ if si in domains[j][c]:
+ self.b[j][c] = si
+ inferences.append([j,c])
+ keep_going = True
+ break
+ for j in range(9):
+ # " " in columns
+ col_doms = [domains[r][j] for r in range(9) if len(domains[r][j]) != 1]
+ if col_doms == []:
+ continue
+ count = reduce(lambda x,y: x+y, col_doms).count(si)
+ if count == 1:
+ for r in range(9):
+ if si in domains[r][j]:
+ self.b[r][j] = si
+ inferences.append([r,j])
+ keep_going = True
+ break
+ for j,k in product(range(3),range(3)):
+ # " " in boxes
+ box_rows = range(j*3,(j+1)*3)
+ box_cols = range(k*3,(k+1)*3)
+ box_doms = [domains[l][m] for l,m in product(box_rows,box_cols) if len(domains[l][m]) != 1]
+ if box_doms == []:
+ continue
+ count = reduce(lambda x,y: x+y, box_doms).count(si)
+ if count == 1:
+ for l,m in product(box_rows,box_cols):
+ if si in domains[l][m]:
+ self.b[l][m] = si
+ inferences.append([l,m])
+ keep_going = True
+ break
+ return [True] + inferences
def apply_naked_triples(self,domains):
# k=2
for i in range(1,9):
for j in range(i+1,10):
si = str(i)
sj = str(j)
# Check rows/columns
for k in range(9):
col_list = []
row_list = []
for l in range(9):
if domains[k][l] == [si,sj]:
col_list.append(l)
if domains[l][k] == [si,sj]:
row_list.append(l)
if len(col_list) == 2:
for m in range(9):
if si in domains[k][m] and m not in col_list:
domains[k][m].remove(si)
if sj in domains[k][m] and m not in col_list:
domains[k][m].remove(sj)
if len(row_list) == 2:
for m in range(9):
if si in domains[m][k] and m not in row_list:
domains[m][k].remove(si)
if sj in domains[m][k] and m not in row_list:
domains[m][k].remove(sj)
# Check boxes
for k,l in product(range(3),range(3)):
box_rows = range(k*3,(k+1)*3)
box_cols = range(l*3,(l+1)*3)
box_list = []
for m,n in product(box_rows,box_cols):
if domains[m][n] == [si,sj]:
box_list.append([m,n])
if len(box_list) == 2:
for m,n in product(box_rows,box_cols):
if si in domains[m][n] and [m,n] not in box_list:
domains[m][n].remove(si)
if sj in domains[m][n] and [m,n] not in box_list:
domains[m][n].remove(sj)
# k=3
for h in range(1,8):
for i in range(h+1,9):
for j in range(i+1,10):
sh = str(h)
si = str(i)
sj = str(j)
# Check rows/columns
for k in range(9):
col_list = []
row_list = []
for l in range(9):
if domains[k][l] in [[sh,si,sj], [sh,si], [sh,sj], [si,sj]]:
col_list.append(l)
if domains[l][k] in [[sh,si,sj], [sh,si], [sh,sj], [si,sj]]:
row_list.append(l)
if len(col_list) == 3:
for m in range(9):
if sh in domains[k][m] and m not in col_list:
domains[k][m].remove(sh)
if si in domains[k][m] and m not in col_list:
domains[k][m].remove(si)
if sj in domains[k][m] and m not in col_list:
domains[k][m].remove(sj)
if len(row_list) == 3:
for m in range(9):
if sh in domains[m][k] and m not in row_list:
domains[m][k].remove(sh)
if si in domains[m][k] and m not in row_list:
domains[m][k].remove(si)
if sj in domains[m][k] and m not in row_list:
domains[m][k].remove(sj)
# Check boxes
for k,l in product(range(3),range(3)):
box_rows = range(k*3,(k+1)*3)
box_cols = range(l*3,(l+1)*3)
box_list = []
for m,n in product(box_rows,box_cols):
if domains[m][n] in [[sh,si,sj], [sh,si], [sh,sj], [si,sj]]:
box_list.append([m,n])
if len(box_list) == 3:
for m,n in product(box_rows,box_cols):
if sh in domains[m][n] and [m,n] not in box_list:
domains[m][n].remove(sh)
if si in domains[m][n] and [m,n] not in box_list:
domains[m][n].remove(si)
if sj in domains[m][n] and [m,n] not in box_list:
domains[m][n].remove(sj)
return domains
- def backtrack(self,most_constrained):
+ def backtrack(self):
if self.is_solved():
return
- # Apply rules......
-
- sq = []
domains = self.get_domains()
+ if domains == False:
+ return
# Select a square to try
- if most_constrained:
+ sq = []
+ if self.most_constrained:
least_len = [10,-1,-1]
for i,j in product(range(9),range(9)):
leng = len(domains[i][j])
if leng < least_len[0] and self.b[i][j] == '-':
least_len = [leng,i,j]
if leng == 2:
break
sq = least_len[1],least_len[2]
else:
for i in range(9):
for j in range(9):
if self.b[i][j] == '-':
sq = i,j
# Try each value in sq's domain until one works
for val in domains[sq[0]][sq[1]]:
self.b[sq[0]][sq[1]] = val
- if self.get_domains() != False:
- self.backtrack(most_constrained)
+
+ inferences = [[sq[0],sq[1]]]
+ r1 = self.apply_rule1()
+ r2 = self.apply_rule2()
+ if len(r1) > 1:
+ inferences += r1[1:]
+ if len(r2) > 1:
+ inferences += r2[1:]
+
+ if r1[0] and r2[0]:
+ self.no_calls += 1
+ self.backtrack()
if self.is_solved():
return
- self.b[sq[0]][sq[1]] = '-'
+ for inf in inferences:
+ self.b[inf[0]][inf[1]] = '-'
def is_solved(self):
# If any square is not yet assigned a number, return false. Else return
# true.
for i in range(9):
for j in range(9):
if self.b[i][j] == '-':
return False
return True
# Read in the contents of the sudoku repository. Use some python voodoo to
# parse out all of the sudokus into a list, and parse out their corresponding
# difficulties.
repo = open('repository.txt','r').readlines()
difficulties = [repo[line_num].split()[1].lower() for line_num in range(len(repo)) if line_num % 11 == 0]
-repo = [[i for i in line.replace('0','-') if not i in (' ','\n')] for line in repo]
+repo = [[i for i in line.replace('0','-') if i in ([str(j) for j in range(1,10)] + ['-'])] for line in repo]
sudokus = [repo[i*11+1:i*11+10] for i in range(len(repo)/11)]
-'''
-sudoku = Board(sudokus[2])
-sudoku.backtrack(True)
-sudoku.display()
-'''
-
a = []
+c = []
for i in range(len(sudokus)):
- if i == 33:
- print 'Processing sudoku %d' % i
- sudoku = Board(sudokus[i])
- sudoku.backtrack(True)
- a += difficulties[i],sudoku.is_solved()
+ print 'Processing sudoku %d' % i
+ sudoku = Board(sudokus[i],naked=True,mc=True)
+ sudoku.backtrack()
+ a += [[sudoku.is_solved(),sudoku.no_calls]]
+ c += [sudoku]
print
-print len([i for i in a if i == False])
+print a
+print len([i for i in a if i[0] == False])
-#55/77 still unsolved after applying rule 1. 26/77 with naked triples
+#16/77 still unsolved after applying rule 1. 26/77 with naked triples
#54/77 still unsolved after applying rule 1, then rule 2. 26/77 with naked triples
#51/77 still unsolved after applying the two rules repeatedly. 23/77 with naked triples
diff --git a/prog4/.notes.txt.swp b/prog4/.notes.txt.swp
new file mode 100644
index 0000000..4dca52f
Binary files /dev/null and b/prog4/.notes.txt.swp differ
diff --git a/prog4/.prog4.py.swp b/prog4/.prog4.py.swp
new file mode 100644
index 0000000..77ae613
Binary files /dev/null and b/prog4/.prog4.py.swp differ
diff --git a/prog4/notes.txt b/prog4/notes.txt
new file mode 100644
index 0000000..dc43b4b
--- /dev/null
+++ b/prog4/notes.txt
@@ -0,0 +1,40 @@
+Expand knowledge base as agent moves through environment, w/ help of prover9
+get_action as shows on page 270. Modify alg so that agent only shoots if it has
+ sensed a blocking stench.
+informed search procedure
+ evaluation function / heuristic
+Should display the solution for a single problem, as well as the stats for the
+ solution of multiple problems
+
+Knowledge base:
+there is only one wumpus in an environment
+squares adjacent to a wumpus are smelly, keep in mind that it may be dead though
+squares adjacent to a pit are breezy
+a square is safe iff it contains no wumpus and no pit
+if wumpus_alive is false than there is no wumpus on any square
+the square that glitters contains gold
+once the shoot action occurs, have_arrow is false
+once the scream percept occurs, wumpus_alive is false
+if facing_north and turn_right, then facing_east
+ eight implicit combinations of facing direction and action
+the agent's location at some time is based on the last action taken, the last
+ location, and the bump percept
+
+Vocab:
+squares [x,y]
+unvisited([x,y])
+pit([x,y])
+breeze([x,y])
+stench([x,y])
+haveArrow()
+wumpusAlive()
+ok([x,y])
+at(Agent/Wumpus, square, time)
+adjacent([x,y],[a,b])
+
+Actions:
+forward
+turn(left) and turn(right)
+grab
+shoot
+climb
diff --git a/prog4/prog4.py b/prog4/prog4.py
new file mode 100644
index 0000000..d7a589d
--- /dev/null
+++ b/prog4/prog4.py
@@ -0,0 +1,311 @@
+from os import system
+from random import randint
+from itertools import product
+
+FILE_NAME = 'worlds.txt'
+
+class WumpusWorld:
+ world = list()
+
+ def __init__(self, w):
+ if w == []:
+ self.world = self.make_random_world()
+ else:
+ self.world = w
+
+ # Generate a random wumpus world
+ def make_random_world(self):
+ # Make a dictionary for each square, which will hold whether that
+ # square contains a pit, wumpus, breeze, stench, or gold.
+ world = [[{'p':False,'w':False,'b':False,'s':False,'g':False} for i in range(4)] for j in range(4)]
+
+ # Make a wumpus and some gold on unique squares.
+ e = []
+ while len(e) != 2:
+ sq = randint(1,15)
+ row = sq / 4
+ col = sq % 4
+ if [row,col] in e:
+ continue
+ e.append([row,col])
+
+ # Make some pits on unique squares
+ for sq in range(1,15):
+ row = sq / 4
+ col = sq % 4
+ if [row,col] in e:
+ continue
+ if randint(1,5) == 1:
+ e.append([row,col])
+
+ # Populate world with wumpus and stenches
+ world[e[0][0]][e[0][1]]['w'] = True
+ if e[0][0] > 0:
+ world[e[0][0] - 1][e[0][1]]['s'] = True
+ if e[0][0] < 3:
+ world[e[0][0] + 1][e[0][1]]['s'] = True
+ if e[0][1] > 0:
+ world[e[0][0]][e[0][1] - 1]['s'] = True
+ if e[0][1] < 3:
+ world[e[0][0]][e[0][1] + 1]['s'] = True
+
+ # Place gold
+ world[e[1][0]][e[1][1]]['g'] = True
+
+ # Populate world with pits and breezes
+ for i in range(2, len(e)):
+ world[e[i][0]][e[i][1]]['p'] = True
+ if e[i][0] > 0:
+ world[e[i][0] - 1][e[i][1]]['b'] = True
+ if e[i][0] < 3:
+ world[e[i][0] + 1][e[i][1]]['b'] = True
+ if e[i][1] > 0:
+ world[e[i][0]][e[i][1] - 1]['b'] = True
+ if e[i][1] < 3:
+ world[e[i][0]][e[i][1] + 1]['b'] = True
+
+ return world
+
+ def display(self, loc):
+ system('clear')
+ print 'A - Agent'
+ print 'P - Pit'
+ print 'W - Wumpus'
+ print 'B - Breeze'
+ print 'S - Stench'
+ print 'G - Gold'
+ print
+
+ w = self.world
+ rows = range(4)
+ rows.reverse()
+ for r in rows:
+ print ' _______ _______ _______ _______'
+ rtext = '|'
+ for c in range(4):
+ rtext += '%d,%d |' % (c+1,r+1)
+ print rtext
+
+ rtext = '|'
+ for c in range(4):
+ rtext += ' %s |' % {True:'A', False:' '}[loc == [r,c]]
+ print rtext
+
+ rtext = ''
+ for c in range(4):
+ s = w[r][c]
+ rtext += '| '
+ for l in ['p','w','b','s','g']:
+ if s[l]:
+ rtext += l.upper()
+ else:
+ rtext += ' '
+ rtext += ' '
+ rtext += '|'
+ print rtext
+
+ print '|_______|_______|_______|_______|'
+
+class HumanAgent:
+ def get_action(self, percept):
+ return raw_input('Enter next action: ')
+
+class ComputerAgent:
+ KB = []
+ t = 0
+ plan = []
+
+ # Initialize the agent by adding the atemporal physics of the wumpus world
+ # to the KB.
+ def __init__(self):
+ pass
+
+ # Return a list of facts that correspond to a given percept
+ def make_percept_sentence(self, percept):
+ facts = []
+ return facts
+
+ # Return a list of facts that correpond to a given action
+ def make_action_sentence(self, percept):
+ pass
+
+ # Give the theorem prover a query and the current KB, and see if the query
+ # is provably true
+ def ask(self, query):
+ result = bool()
+ return result
+
+ def tell(self, facts):
+ pass
+
+ # Ask the agent to provide the best action given its current KB and the
+ # current percept
+ def get_action(self, percept):
+ action = str()
+ return action
+
+ # Use A* to calculate a sequence of actions that will bring an agent from
+ # the given location to one of the goal locations
+ def plan_route(self, current, goals, allowed):
+ action_sequence = []
+ return action_sequence
+
+ # Use A* to calculate a sequence of actions
+ def plan_shot(self, current, possible_wumpus, safe):
+ action_sequence = []
+ return action_sequence
+
+class Simulation:
+ NORTH = 0
+ EAST = 1
+ SOUTH = 2
+ WEST = 3
+
+ ww = None
+ agent = None
+
+ loc = [0,0]
+ facing = NORTH
+
+ has_arrow = True
+
+ # Initialize the simulation by storing the wumpus world given, and then
+ # run the simulation
+ def __init__(self, ww, computer):
+ self.ww = ww
+ if computer:
+ self.agent = ComputerAgent()
+ else:
+ self.agent = HumanAgent()
+ self.run()
+
+ # Run the simulation by giving the agent percepts and asking for actions,
+ # until the agent dies or climbs out.
+ def run(self):
+ scream = False
+
+ self.ww.display(self.loc)
+ print
+ print 'Agent is facing %s' % {0:'north', 1:'east', 2:'south', 3:'west'}[self.facing]
+ print 'Press enter to continue...'
+ raw_input()
+
+ bump = False
+ while True:
+ # Construct a percept
+ percept = {}
+ percept['stench'] = self.ww.world[self.loc[0]][self.loc[1]]['s']
+ percept['breeze'] = self.ww.world[self.loc[0]][self.loc[1]]['b']
+ percept['glitter'] = self.ww.world[self.loc[0]][self.loc[1]]['g']
+ percept['scream'] = scream
+ percept['bump'] = bump
+ print 'Current percept: %s' % str(percept)
+
+ # Get an action based on current percept
+ action = self.agent.get_action(percept)
+
+ # Process action
+ scream = False
+ bump = False
+ if action == 'forward':
+ if self.facing == self.NORTH:
+ if self.loc[0] == 3:
+ bump = True
+ else:
+ self.loc[0] += 1
+ if self.facing == self.EAST:
+ if self.loc[1] == 3:
+ bump = True
+ else:
+ self.loc[1] += 1
+ if self.facing == self.SOUTH:
+ if self.loc[0] == 0:
+ bump = True
+ else:
+ self.loc[0] -= 1
+ if self.facing == self.WEST:
+ if self.loc[1] == 0:
+ bump = True
+ else:
+ self.loc[1] -= 1
+ agent_sq = self.ww.world[self.loc[0]][self.loc[1]]
+ if agent_sq['w']:
+ self.ww.display(self.loc)
+ print '\nYou were killed by the wumpus\n'
+ return
+ if agent_sq['p']:
+ self.ww.display(self.loc)
+ print '\nYou fell to your death down a pit\n'
+ return
+
+ elif action == 'turn_left':
+ self.facing = (self.facing - 1) % 4
+ elif action == 'turn_right':
+ self.facing = (self.facing + 1) % 4
+ elif action == 'grab':
+ if self.ww.world[self.loc[0]][self.loc[1]]['g']:
+ self.ww.world[self.loc[0]][self.loc[1]]['g'] = False
+ elif action == 'shoot':
+ dir = {self.NORTH:(self.loc[0]+1,4), self.EAST:(self.loc[1]+1,4), self.SOUTH:(0,self.loc[0]), self.WEST:(0,self.loc[1])}[self.facing]
+ if self.has_arrow:
+ self.has_arrow = False
+ for i in range(*dir):
+ if self.facing % 2 == 0:
+ if self.ww.world[i][self.loc[1]]['w']:
+ self.ww.world[i][self.loc[1]]['w'] = False
+ scream = True
+ else:
+ if self.ww.world[self.loc[0]][i]['w']:
+ self.ww.world[self.loc[0]][i]['w'] = False
+ scream = True
+ elif action == 'climb':
+ if self.loc == [0,0]:
+ return
+
+ self.ww.display(self.loc)
+ print
+ print 'Last action: %s' % action
+ print 'Agent is facing %s' % {0:'north', 1:'east', 2:'south', 3:'west'}[self.facing]
+ print 'Press enter to continue...'
+ raw_input()
+
+# Generate 100 random wumpus worlds and write them to a file
+def generate_worlds():
+ fstream = open(FILE_NAME, 'w')
+ for i in range(100):
+ w = WumpusWorld([])
+ fstream.write('%d\n' % i)
+ w.world.reverse()
+ for row in w.world:
+ for s in row:
+ fstream.write('|')
+ for l in ['p','w','b','s','g']:
+ if s[l]:
+ fstream.write(l.upper())
+ else:
+ fstream.write(' ')
+ fstream.write('\n')
+ fstream.write('\n')
+ fstream.close()
+
+# Read pre-generated worlds from file
+def read_worlds():
+ lines = open(FILE_NAME, 'r').readlines()
+ worlds = []
+ for w in range(100):
+ worlds.append([])
+ for r in range(4):
+ worlds[w].append([])
+ line = lines[w*6+r+1]
+ for c in range(4):
+ worlds[w][r].append({})
+ for l in range(5):
+ if line[c*6+1+l] == ' ':
+ worlds[w][r][c][['p','w','b','s','g'][l]] = False
+ else:
+ worlds[w][r][c][['p','w','b','s','g'][l]] = True
+ worlds[w].reverse()
+ worlds[w] = WumpusWorld(worlds[w])
+ return worlds
+
+Simulation(read_worlds()[0],False)
diff --git a/prog4/prover9 b/prog4/prover9
new file mode 100755
index 0000000..0377634
Binary files /dev/null and b/prog4/prover9 differ
diff --git a/prog4/test b/prog4/test
new file mode 100644
index 0000000..1e58f21
--- /dev/null
+++ b/prog4/test
@@ -0,0 +1,9 @@
+formulas(assumptions). % synonym for formulas(sos).
+ man(x) -> mortal(x). % open formula with free variable x
+ man(george).
+end_of_list.
+
+formulas(goals). % to be negated and placed in the sos list
+ mortal(george).
+end_of_list.
+
diff --git a/prog4/test.out b/prog4/test.out
new file mode 100644
index 0000000..1791806
--- /dev/null
+++ b/prog4/test.out
@@ -0,0 +1,120 @@
+============================== Prover9 ===============================
+Prover9 (32) version 2009-11A, November 2009.
+Process 3405 was started by andermic on andermic-laptop,
+Sun Nov 21 16:32:17 2010
+The command was "./prover9 -f test".
+============================== end of head ===========================
+
+============================== INPUT =================================
+
+% Reading from file test
+
+
+formulas(assumptions).
+man(x) -> mortal(x).
+man(george).
+end_of_list.
+
+formulas(goals).
+mortal(george).
+end_of_list.
+
+============================== end of input ==========================
+
+============================== PROCESS NON-CLAUSAL FORMULAS ==========
+
+% Formulas that are not ordinary clauses:
+1 man(x) -> mortal(x) # label(non_clause). [assumption].
+2 mortal(george) # label(non_clause) # label(goal). [goal].
+
+============================== end of process non-clausal formulas ===
+
+============================== PROCESS INITIAL CLAUSES ===============
+
+% Clauses before input processing:
+
+formulas(usable).
+end_of_list.
+
+formulas(sos).
+-man(x) | mortal(x). [clausify(1)].
+man(george). [assumption].
+-mortal(george). [deny(2)].
+end_of_list.
+
+formulas(demodulators).
+end_of_list.
+
+============================== PREDICATE ELIMINATION =================
+
+Eliminating man/1
+3 man(george). [assumption].
+4 -man(x) | mortal(x). [clausify(1)].
+Derived: mortal(george). [resolve(3,a,4,a)].
+
+Eliminating mortal/1
+5 mortal(george). [resolve(3,a,4,a)].
+6 -mortal(george). [deny(2)].
+Derived: $F. [resolve(5,a,6,a)].
+
+============================== end predicate elimination =============
+
+Auto_denials: (no changes).
+
+Term ordering decisions:
+Predicate symbol precedence: predicate_order([ ]).
+Function symbol precedence: function_order([ ]).
+After inverse_order: (no changes).
+Unfolding symbols: (none).
+
+Auto_inference settings:
+ % set(neg_binary_resolution). % (HNE depth_diff=0)
+ % clear(ordered_res). % (HNE depth_diff=0)
+ % set(ur_resolution). % (HNE depth_diff=0)
+ % set(ur_resolution) -> set(pos_ur_resolution).
+ % set(ur_resolution) -> set(neg_ur_resolution).
+
+Auto_process settings: (no changes).
+
+
+============================== PROOF =================================
+
+% Proof 1 at 0.01 (+ 0.01) seconds.
+% Length of proof is 7.
+% Level of proof is 3.
+% Maximum clause weight is 0.000.
+% Given clauses 0.
+
+1 man(x) -> mortal(x) # label(non_clause). [assumption].
+2 mortal(george) # label(non_clause) # label(goal). [goal].
+3 man(george). [assumption].
+4 -man(x) | mortal(x). [clausify(1)].
+5 mortal(george). [resolve(3,a,4,a)].
+6 -mortal(george). [deny(2)].
+7 $F. [resolve(5,a,6,a)].
+
+============================== end of proof ==========================
+
+============================== STATISTICS ============================
+
+Given=0. Generated=1. Kept=0. proofs=1.
+Usable=0. Sos=0. Demods=0. Limbo=0, Disabled=5. Hints=0.
+Kept_by_rule=0, Deleted_by_rule=0.
+Forward_subsumed=0. Back_subsumed=0.
+Sos_limit_deleted=0. Sos_displaced=0. Sos_removed=0.
+New_demodulators=0 (0 lex), Back_demodulated=0. Back_unit_deleted=0.
+Demod_attempts=0. Demod_rewrites=0.
+Res_instance_prunes=0. Para_instance_prunes=0. Basic_paramod_prunes=0.
+Nonunit_fsub_feature_tests=0. Nonunit_bsub_feature_tests=0.
+Megabytes=0.01.
+User_CPU=0.01, System_CPU=0.01, Wall_clock=0.
+
+============================== end of statistics =====================
+
+============================== end of search =========================
+
+THEOREM PROVED
+
+Exiting with 1 proof.
+
+Process 3405 exit (max_proofs) Sun Nov 21 16:32:17 2010
diff --git a/prog4/worlds.txt b/prog4/worlds.txt
new file mode 100644
index 0000000..ce21bfd
--- /dev/null
+++ b/prog4/worlds.txt
@@ -0,0 +1,600 @@
+0
+| B | G| S | W
+|P | B | | BS
+| B | | B |P
+| | B |P | B
+
+1
+| WB | S | |
+|P S | B G| |
+| B |P | B |
+| | B | |
+
+2
+| B |P | B |
+|P | B | |
+| B | | S | B G
+| | S | WB |P S
+
+3
+| | B |P | B
+| B | | B |
+|P | B | G| S
+| B |P | BS | W
+
+4
+| S | | |
+| W | S | |
+| S | | |
+| | | | G
+
+5
+|P | B | |
+| B | | S |
+| | SG| W | S
+| | | S |
+
+6
+| S | | |
+| W | BSG| |
+| BS |P B | B |
+| B |P B |P B | B
+
+7
+|P B |P B |P B | B
+| B | B | BS |
+| | S | W | S
+| | G| S |
+
+8
+| WB |P S | B | G
+| S | B | B |
+| | B |P | B
+| | | B |
+
+9
+| B | B | |
+|P B |P BS | B |
+| BS | WB | BS |
+| | BSG|P | B
+
+10
+| | S | |
+| S | W | S |
+| | S | B G|
+| | B |P | B
+
+11
+| B | | |
+|P | B | |
+| B | S | | G
+| S | W | S |
+
+12
+| B |P | B |
+| | B | B G|
+| | B |P | BS
+| | | BS | W
+
+13
+| | B | |
+| B |P | B |
+| | B G| | S
+| | | S | W
+
+14
+| B | B G| |
+|P BS |P B | B |
+| WB |P BS |P B | B
+| S | B |P B | B
+
+15
+| | B |P | BS
+| | | BS | W
+| | | | BSG
+| | | B |P
+
+16
+| | | S | WB
+| B | G| B |P S
+|P | B | | B
+| B |P | B |
+
+17
+| | B |P | BS
+| | | BSG| WB
+| | | B |P S
+| | | | B
+
+18
+| | | |
+| S | | G|
+| W | S | |
+| S | | |
+
+19
+| B G| | B | S
+|P B | B |P S | WB
+|P B | B | B |P S
+| B | | | B
+
+20
+| | | B | B
+| | BS |P B |P B
+| S | W | BSG|P B
+| | BS |P | B
+
+21
+| B | | |
+|P | B | G|
+| B | | | S
+| | | S | W
+
+22
+| B |P | B G|
+| B | B | |
+|P | B | | S
+| B | | S | W
+
+23
+| B | B | S | WB
+|P B |P B | B |P S
+|P B | B | B | B G
+| B | B |P B |P B
+
+24
+| | B |P | B
+| S | B | B |P
+| WB |P S | B | B G
+| S | B | |
+
+25
+| | | |
+| G| S | |
+| S | W | S |
+| | S | |
+
+26
+| | B |P | BSG
+| | | BS | W
+| | B | | S
+| B |P | B |
+
+27
+| G| B |P | B
+| B | | BS | B
+|P | BS | WB |P S
+| B | | S | B
+
+28
+| | S | |
+| S | W | BS | G
+| | BS |P | B
+| | | B |
+
+29
+| | S | | B
+| BS | W | BS |P
+|P | BS | B G| B
+| B | B |P | B
+
+30
+| | | |
+| | | B | B
+| | BS |P B |P B
+| S | W | BS | B G
+
+31
+|P | B G| | S
+| B | | BS | W
+| | B |P | BS
+| B |P | B |
+
+32
+| G| | |
+| B | | | S
+|P | B | S | W
+| B | | | S
+
+33
+| B |P B |P B | B
+| | B | BS |
+| B |P S | WB | S
+| | B G| S |
+
+34
+| | S | W | S
+| | | BS | B
+| G| B |P B |P B
+| | | B | B
+
+35
+| BS |P | B |
+| W | BS | |
+| BS |P | B G|
+| | B | |
+
+36
+| | | B | B
+| G| B |P B |P B
+| B |P | B | BS
+| | B | S | W
+
+37
+| W | BS |P | B G
+| BS | | B |P
+|P | B |P B | B
+| B | B |P B | B
+
+38
+| B |P | B |
+|P S | B | |
+| WB | S | |
+| S | G| |
+
+39
+| B |P | BS | W
+|P | B G| | S
+| B | | B |
+| | B |P | B
+
+40
+|P | BS | B |
+| BS | WB |P S | B G
+| | BS | B |
+| B |P | B |
+
+41
+|P | B | |
+| B | G| |
+| | | | S
+| | | S | W
+
+42
+| | | | S
+| | | S | WB
+| | G| B |P BS
+| | | B |P B
+
+43
+| | B | B |
+| B |P B |P B | B
+|P | B | BS | G
+| B | S | W | S
+
+44
+|P S | B | |
+| WB | BS | B |
+| BSG|P B |P B | B
+| | B | B |
+
+45
+| | | | G
+| | | |
+| | S | | B
+| S | W | BS |P
+
+46
+| | B | |
+| B |P | BS |
+| | BS | W | S
+| B |P | BS | G
+
+47
+| B | S | |
+|P S | WB | BS | G
+| B | BS |P | B
+| B |P | B |
+
+48
+| S | W | SG|
+| | S | |
+| | B | |
+| B |P | B |
+
+49
+| | G| |
+| | | | S
+| | | BS | WB
+| | B |P B |P BS
+
+50
+| | | S |
+| | S | W | S
+| | | BS |
+| | B G|P | B
+
+51
+| B |P | B | B
+| B | B | B |P S
+|P B |P B |P BS | WB
+| B |P B |P B | BSG
+
+52
+| B | | S | W
+|P B | B | B | S
+|P B | B |P | B
+| B |P | B G|
+
+53
+| | B | |
+| B |P S | B G| B
+| S | WB | BS |P
+| | S | | B
+
+54
+| S | B |P | B
+| W | BS | B |
+| BS |P B | B |
+| B |P B | B | G
+
+55
+| B |P | B | S
+| | B | SG| WB
+| | B | B |P S
+| B |P | B | B
+
+56
+|P | BS | W | S
+| B |P | BS | B
+| G| B |P B |P B
+| | | B | B
+
+57
+|P | B |P | B
+| B | SG| B |
+| S | W | S |
+| | S | |
+
+58
+| | B |P | B
+| B |P | B |
+| | B | S | G
+| | S | W | S
+
+59
+| G| B | B |
+| BS |P B |P B | B
+| W | BS | B |
+| BS |P B |P B | B
+
+60
+| | S | | B
+| S | W | BS |P B
+| | S | B |P B
+| | | | B G
+
+61
+|P B |P B | BS |
+| B | BSG| W | S
+| | B | S |
+| B |P | B |
+
+62
+| B |P BS |P B | B
+| S | WB | BS |
+| | SG| |
+| | | |
+
+63
+| | B |P B | B
+| | BS |P B | B
+| S | W | BS |
+| | S | G|
+
+64
+|P B |P B | B | S
+| B | B | BS | W
+| | B |P B | BS
+| | B |P B | B G
+
+65
+| | | B | G
+| S | B |P | B
+| W | S | B |P
+| S | | | B
+
+66
+| | | S |
+| B G| BS | W | S
+|P B |P B | BS | B
+| B |P B |P B |P B
+
+67
+| | | S |
+| | SG| WB | S
+| | B |P S | B
+| | | B |
+
+68
+| B | | |
+|P | BS | G|
+| BS | W | S | B
+| | S | B |P
+
+69
+| | | S | W
+| | | B | BS
+| G| B |P B |P B
+| B |P | B |P B
+
+70
+| B |P | BS | B
+| B | BSG| WB |P BS
+|P | B | BS |P B
+| B | | B |P B
+
+71
+| W | BS | G|
+| BS |P | B |
+| | B | |
+| | | |
+
+72
+| | | |
+| | | | S
+| | | BS | W
+| | B G|P | BS
+
+73
+|P | B | |
+| B | | |
+| G| | S |
+| | S | W | S
+
+74
+| | | |
+| S | | |
+| W | S | | B
+| S | G| B |P
+
+75
+| | | |
+| | S | B | G
+| S | WB |P S | B
+| | S | B |
+
+76
+|P B |P B |P B | B
+| B | B G| B |
+|P | B |P S | B
+| B | S | WB | S
+
+77
+| S | WB | S | B
+| B |P S | B |P
+| | B | | B G
+| | | |
+
+78
+| | | G|
+| | B | B |
+| B |P B |P BS | B
+| | BS | WB | S
+
+79
+|P | B | BSG| WB
+| B |P B |P B |P BS
+| | B |P B | B
+| B |P | B |P
+
+80
+| G| B | |
+| B |P | B | B
+|P | B | BS |P
+| B | S | W | BS
+
+81
+| B | B | B |
+|P BS |P B |P B | B
+| WB | BS | B | G
+| S | | |
+
+82
+| W | S | B | B
+| BS | B |P B |P B
+|P | B | B | B
+| B | | | G
+
+83
+| B |P | BS | W
+| | B | | S
+| B |P | B | G
+| | B |P | B
+
+84
+| G| B | S |
+| B |P S | WB | S
+| | B |P S | B
+| | | B |
+
+85
+|P B | B | G| S
+|P B |P B | BS | W
+| B | B |P | BS
+| | | B |P
+
+86
+| S | W | S |
+| | S | | B
+| | | B |P
+| | G| | B
+
+87
+| BS |P B | B | B
+| WB |P BS | B |P
+| BS |P B | B G| B
+| | B | |
+
+88
+| B |P | B |
+| S | B | B G|
+| W | BS |P B | B
+| S | B |P B | B
+
+89
+|P | B | S | W
+| B |P | B G| S
+| | B |P B | B
+| | B |P B | B
+
+90
+| BS |P | B |
+| W | BS | |
+| S | | | G
+| | | |
+
+91
+| BS |P | B |
+| W | BS | B |
+| S | B |P | B G
+| | | B |
+
+92
+| | B |P | B
+| S | | B | G
+| W | BS |P | B
+| S | | B |
+
+93
+| | S | B G|
+| S | WB |P S | B
+| | S | B |P
+| | | | B
+
+94
+| | B | |
+| B |P | BS | B
+| G| BS | WB |P S
+| | | S | B
+
+95
+| | | |
+| G| | B |
+| | B |P S | B
+| | S | WB |P S
+
+96
+| | | |
+| | | | S
+| | G| S | W
+| | | | S
+
+97
+|P | BS | W | BS
+| B | | BS |P
+| | | | B
+| | G| |
+
+98
+|P | B | |
+| B | | | S
+| G| | S | W
+| | | | S
+
+99
+| G| | S |
+| | S | WB | S
+| | B |P S | B
+| B |P | B |
+
|
andermic/CS531
|
37d5e7bbe62f1d3188fb13b28dbd61f1a390d68d
|
Almost done w/ prog3
|
diff --git a/prog3/.prog3.py.swp b/prog3/.prog3.py.swp
index 8597481..506e21b 100644
Binary files a/prog3/.prog3.py.swp and b/prog3/.prog3.py.swp differ
diff --git a/prog3/prog3.py b/prog3/prog3.py
index 4806312..b465507 100644
--- a/prog3/prog3.py
+++ b/prog3/prog3.py
@@ -1,292 +1,314 @@
-from os import system #For clearing the screen
-from itertools import product #Product takes the cartesian product of two lists
-from copy import deepcopy
+from os import system # For clearing the screen
+from itertools import product # product() takes the cartesian product of two lists
+from copy import deepcopy # deepcopy() returns a deepcopy of an object
class Board:
b = list()
def __init__(self, board):
self.b = board
def display(self):
- system('clear')
+ #system('clear')
print ' a b c d e f g h i'
for i in range(3):
for j in range(3):
print '%s ' % (i*3+j+1),
for k in range(3):
for l in range(3):
print self.b[i*3+j][k*3+l],
if k != 2:
print '|',
print
if i != 2:
print '------------------------'
# Calculate the domain of cell with row r and column c, by subtracting
# already assigned values in the same row, column, and box.
def get_domain(self, r, c):
# If the cell is already assigned, return the value assigned as the
# only value in that cell's domain.
if self.b[r][c] != '-':
return [self.b[r][c]]
# Domain initially contains all digits 1-9
result = [str(i) for i in range(1,10)]
# Filter out values in the same row
result = [i for i in result if i not in [self.b[r][j] for j in range(9)]]
# Filter out values in the same column
result = [i for i in result if i not in [self.b[j][c] for j in range(9)]]
# Filter out values in the same box
box_rows = range(r/3*3,(r/3+1)*3)
box_cols = range(c/3*3,(c/3+1)*3)
result = [i for i in result if i not in [self.b[j][k] for j,k in product(box_rows,box_cols)]]
return result
def get_domains(self):
domains = []
for i in range(9):
domains.append([])
for j in range(9):
domain = self.get_domain(i,j)
if domain == []:
return False
else:
domains[i].append(domain)
return domains
def apply_rule1(self,naked_triples):
# Calculate the domains of empty cells using get_domain(),
# which applies the row, column, and box constraints. When a cell has
# only one value in its domain, assign the cell that value. If after
# an iteration no assignments occur, then this technique has done all
# it can do, and so return. If a cell ever has an empty domain, return
# failure.
keep_going = True
while(keep_going):
keep_going = False
domains = self.get_domains()
+ if domains == False:
+ return False
if naked_triples:
domains = self.apply_naked_triples(domains)
for i in range(9):
for j in range(9):
if self.b[i][j] == '-':
if len(domains[i][j]) == 1:
self.b[i][j] = domains[i][j][0]
keep_going = True
return True
def apply_rule2(self,naked_triples):
# Calculate the domain of all empty cells using get_domain(). If a
# value is only in the domain of one cell within a row, column, or
# box, assign that value to that cell. Return after no assignments
# are made, and return failure if an empty domain is found, as in
# apply_rule1().
# For every row, column, and box, see if there are values in the domain
# of one cell that are not in the domains of other cells in that row,
# column, or box.
keep_going = True
while(keep_going):
keep_going = False
# Get the initial domain of every cell. Return failure if any are
# empty.
domains = self.get_domains()
if domains == False:
return False
if naked_triples:
domains = self.apply_naked_triples(domains)
for i in range(1,10):
si = str(i)
for j in range(9):
# Check for single domain instance of i in rows
row_doms = [domains[j][k] for k in range(9) if len(domains[j][k]) != 1]
if row_doms == []:
continue
count = reduce(lambda x,y: x+y, row_doms).count(si)
if count == 1:
for k in range(9):
if si in domains[j][k]:
self.b[j][k] = si
keep_going = True
break
# " " in columns
col_doms = [domains[k][j] for k in range(9) if len(domains[k][j]) != 1]
if col_doms == []:
continue
count = reduce(lambda x,y: x+y, col_doms).count(si)
if count == 1:
for k in range(9):
if si in domains[k][j]:
self.b[k][j] = si
keep_going = True
break
for j,k in product(range(3),range(3)):
# " " in boxes
box_rows = range(j*3,(j+1)*3)
box_cols = range(k*3,(k+1)*3)
- '''
- print box_rows
- print box_cols
- print [domains[l][m] for l,m in product(box_rows,box_cols) if len(domains[l][m]) != 1]
- print
- '''
box_doms = [domains[l][m] for l,m in product(box_rows,box_cols) if len(domains[l][m]) != 1]
if box_doms == []:
continue
count = reduce(lambda x,y: x+y, box_doms).count(si)
if count == 1:
for l,m in product(box_rows,box_cols):
if si in domains[l][m]:
self.b[l][m] = si
keep_going = True
break
return True
def apply_naked_triples(self,domains):
# k=2
for i in range(1,9):
for j in range(i+1,10):
+ si = str(i)
+ sj = str(j)
# Check rows/columns
for k in range(9):
col_list = []
row_list = []
for l in range(9):
- if i in domains[k][l] and j in domains[k][l]:
+ if domains[k][l] == [si,sj]:
col_list.append(l)
- if i in domains[l][k] and j in domains[l][k]:
+ if domains[l][k] == [si,sj]:
row_list.append(l)
if len(col_list) == 2:
for m in range(9):
- if i in domains[k][m] and m not in col_list:
- print 'Removal'
- domains[k][m].remove(i)
- if j in domains[k][m] and m not in col_list:
- print 'Removal'
- domains[k][m].remove(j)
+ if si in domains[k][m] and m not in col_list:
+ domains[k][m].remove(si)
+ if sj in domains[k][m] and m not in col_list:
+ domains[k][m].remove(sj)
if len(row_list) == 2:
for m in range(9):
- if i in domains[m][k] and m not in row_list:
- print 'Removal'
- domains[m][k].remove(i)
- if j in domains[m][k] and m not in row_list:
- print 'Removal'
- domains[m][k].remove(j)
+ if si in domains[m][k] and m not in row_list:
+ domains[m][k].remove(si)
+ if sj in domains[m][k] and m not in row_list:
+ domains[m][k].remove(sj)
# Check boxes
for k,l in product(range(3),range(3)):
box_rows = range(k*3,(k+1)*3)
box_cols = range(l*3,(l+1)*3)
box_list = []
for m,n in product(box_rows,box_cols):
- if i in domains[m][n] and j in domains[m][n]:
+ if domains[m][n] == [si,sj]:
box_list.append([m,n])
if len(box_list) == 2:
for m,n in product(box_rows,box_cols):
- if i in domains[m][n] and [m,n] not in box_list:
- print 'Removal'
- domains[m][n].remove(i)
- if j in domains[m][n] and [m,n] not in box_list:
- print 'Removal'
- domains[m][n].remove(j)
+ if si in domains[m][n] and [m,n] not in box_list:
+ domains[m][n].remove(si)
+ if sj in domains[m][n] and [m,n] not in box_list:
+ domains[m][n].remove(sj)
# k=3
for h in range(1,8):
for i in range(h+1,9):
for j in range(i+1,10):
+ sh = str(h)
+ si = str(i)
+ sj = str(j)
+
# Check rows/columns
for k in range(9):
col_list = []
row_list = []
for l in range(9):
- if h in domains[k][l] and i in domains[k][l] and j in domains[k][l]:
+ if domains[k][l] in [[sh,si,sj], [sh,si], [sh,sj], [si,sj]]:
col_list.append(l)
- if h in domains[k][l] and i in domains[l][k] and j in domains[l][k]:
+ if domains[l][k] in [[sh,si,sj], [sh,si], [sh,sj], [si,sj]]:
row_list.append(l)
if len(col_list) == 3:
for m in range(9):
- if h in domains[k][m] and m not in col_list:
- print 'Removal'
- domains[k][m].remove(h)
- if i in domains[k][m] and m not in col_list:
- print 'Removal'
- domains[k][m].remove(i)
- if j in domains[k][m] and m not in col_list:
- print 'Removal'
- domains[k][m].remove(j)
+ if sh in domains[k][m] and m not in col_list:
+ domains[k][m].remove(sh)
+ if si in domains[k][m] and m not in col_list:
+ domains[k][m].remove(si)
+ if sj in domains[k][m] and m not in col_list:
+ domains[k][m].remove(sj)
if len(row_list) == 3:
for m in range(9):
- if h in domains[m][k] and m not in row_list:
- print 'Removal'
- domains[m][k].remove(h)
- if i in domains[m][k] and m not in row_list:
- print 'Removal'
- domains[m][k].remove(i)
- if j in domains[m][k] and m not in row_list:
- print 'Removal'
- domains[m][k].remove(j)
+ if sh in domains[m][k] and m not in row_list:
+ domains[m][k].remove(sh)
+ if si in domains[m][k] and m not in row_list:
+ domains[m][k].remove(si)
+ if sj in domains[m][k] and m not in row_list:
+ domains[m][k].remove(sj)
# Check boxes
for k,l in product(range(3),range(3)):
box_rows = range(k*3,(k+1)*3)
box_cols = range(l*3,(l+1)*3)
box_list = []
for m,n in product(box_rows,box_cols):
- if h in domains[m][n] and i in domains[m][n] and j in domains[m][n]:
+ if domains[m][n] in [[sh,si,sj], [sh,si], [sh,sj], [si,sj]]:
box_list.append([m,n])
if len(box_list) == 3:
for m,n in product(box_rows,box_cols):
- if h in domains[m][n] and [m,n] not in box_list:
- print 'Removal'
- domains[m][n].remove(h)
- if i in domains[m][n] and [m,n] not in box_list:
- print 'Removal'
- domains[m][n].remove(i)
- if j in domains[m][n] and [m,n] not in box_list:
- print 'Removal'
- domains[m][n].remove(j)
+ if sh in domains[m][n] and [m,n] not in box_list:
+ domains[m][n].remove(sh)
+ if si in domains[m][n] and [m,n] not in box_list:
+ domains[m][n].remove(si)
+ if sj in domains[m][n] and [m,n] not in box_list:
+ domains[m][n].remove(sj)
return domains
+ def backtrack(self,most_constrained):
+ if self.is_solved():
+ return
+
+ # Apply rules......
+
+ sq = []
+ domains = self.get_domains()
+
+ # Select a square to try
+ if most_constrained:
+ least_len = [10,-1,-1]
+ for i,j in product(range(9),range(9)):
+ leng = len(domains[i][j])
+ if leng < least_len[0] and self.b[i][j] == '-':
+ least_len = [leng,i,j]
+ if leng == 2:
+ break
+ sq = least_len[1],least_len[2]
+ else:
+ for i in range(9):
+ for j in range(9):
+ if self.b[i][j] == '-':
+ sq = i,j
+
+ # Try each value in sq's domain until one works
+ for val in domains[sq[0]][sq[1]]:
+ self.b[sq[0]][sq[1]] = val
+ if self.get_domains() != False:
+ self.backtrack(most_constrained)
+ if self.is_solved():
+ return
+ self.b[sq[0]][sq[1]] = '-'
+
def is_solved(self):
# If any square is not yet assigned a number, return false. Else return
# true.
for i in range(9):
for j in range(9):
if self.b[i][j] == '-':
return False
return True
# Read in the contents of the sudoku repository. Use some python voodoo to
# parse out all of the sudokus into a list, and parse out their corresponding
# difficulties.
repo = open('repository.txt','r').readlines()
difficulties = [repo[line_num].split()[1].lower() for line_num in range(len(repo)) if line_num % 11 == 0]
repo = [[i for i in line.replace('0','-') if not i in (' ','\n')] for line in repo]
sudokus = [repo[i*11+1:i*11+10] for i in range(len(repo)/11)]
'''
-sudoku = Board(sudokus[0])
-sudoku.apply_rule2(True)
+sudoku = Board(sudokus[2])
+sudoku.backtrack(True)
sudoku.display()
'''
a = []
for i in range(len(sudokus)):
- print 'Processing sudoku %d' % i
- sudoku = Board(sudokus[i])
- sudoku.apply_rule1(True)
- sudoku.apply_rule2(True)
- a += difficulties[i],sudoku.is_solved()
+ if i == 33:
+ print 'Processing sudoku %d' % i
+ sudoku = Board(sudokus[i])
+ sudoku.backtrack(True)
+ a += difficulties[i],sudoku.is_solved()
print
print len([i for i in a if i == False])
-#55/77 still unsolved after applying rule 1
-#54/77 still unsolved after applying rule 1, then rule 2
-#51/77 still unsolved after applying the two rules repeatedly
+#55/77 still unsolved after applying rule 1. 26/77 with naked triples
+#54/77 still unsolved after applying rule 1, then rule 2. 26/77 with naked triples
+#51/77 still unsolved after applying the two rules repeatedly. 23/77 with naked triples
+
|
andermic/CS531
|
62963d6e175e877abfac96a39d4fb0f3d712f64c
|
working on prog3
|
diff --git a/prog3/.prog3.py.swp b/prog3/.prog3.py.swp
index c770d25..8597481 100644
Binary files a/prog3/.prog3.py.swp and b/prog3/.prog3.py.swp differ
diff --git a/prog3/prog3.py b/prog3/prog3.py
index 06dfd0d..4806312 100644
--- a/prog3/prog3.py
+++ b/prog3/prog3.py
@@ -1,45 +1,292 @@
-import os
+from os import system #For clearing the screen
+from itertools import product #Product takes the cartesian product of two lists
+from copy import deepcopy
class Board:
b = list()
def __init__(self, board):
self.b = board
def display(self):
+ system('clear')
print ' a b c d e f g h i'
for i in range(3):
for j in range(3):
print '%s ' % (i*3+j+1),
for k in range(3):
for l in range(3):
print self.b[i*3+j][k*3+l],
if k != 2:
print '|',
print
if i != 2:
print '------------------------'
+ # Calculate the domain of cell with row r and column c, by subtracting
+ # already assigned values in the same row, column, and box.
def get_domain(self, r, c):
+ # If the cell is already assigned, return the value assigned as the
+ # only value in that cell's domain.
+ if self.b[r][c] != '-':
+ return [self.b[r][c]]
+
+ # Domain initially contains all digits 1-9
result = [str(i) for i in range(1,10)]
- result = [i for i in result if i not in [self.b[j][c] for j in range(0,9)]]
- result = [i for i in result if i not in [self.b[r][j] for j in range(0,9)]]
+
+ # Filter out values in the same row
+ result = [i for i in result if i not in [self.b[r][j] for j in range(9)]]
+
+ # Filter out values in the same column
+ result = [i for i in result if i not in [self.b[j][c] for j in range(9)]]
+
+ # Filter out values in the same box
+ box_rows = range(r/3*3,(r/3+1)*3)
+ box_cols = range(c/3*3,(c/3+1)*3)
+ result = [i for i in result if i not in [self.b[j][k] for j,k in product(box_rows,box_cols)]]
+
return result
- def apply_rule1(self):
- pass
+ def get_domains(self):
+ domains = []
+ for i in range(9):
+ domains.append([])
+ for j in range(9):
+ domain = self.get_domain(i,j)
+ if domain == []:
+ return False
+ else:
+ domains[i].append(domain)
+ return domains
+
+ def apply_rule1(self,naked_triples):
+ # Calculate the domains of empty cells using get_domain(),
+ # which applies the row, column, and box constraints. When a cell has
+ # only one value in its domain, assign the cell that value. If after
+ # an iteration no assignments occur, then this technique has done all
+ # it can do, and so return. If a cell ever has an empty domain, return
+ # failure.
+ keep_going = True
+ while(keep_going):
+ keep_going = False
+ domains = self.get_domains()
+ if naked_triples:
+ domains = self.apply_naked_triples(domains)
+ for i in range(9):
+ for j in range(9):
+ if self.b[i][j] == '-':
+ if len(domains[i][j]) == 1:
+ self.b[i][j] = domains[i][j][0]
+ keep_going = True
+ return True
+
+ def apply_rule2(self,naked_triples):
+ # Calculate the domain of all empty cells using get_domain(). If a
+ # value is only in the domain of one cell within a row, column, or
+ # box, assign that value to that cell. Return after no assignments
+ # are made, and return failure if an empty domain is found, as in
+ # apply_rule1().
+
+ # For every row, column, and box, see if there are values in the domain
+ # of one cell that are not in the domains of other cells in that row,
+ # column, or box.
+ keep_going = True
+ while(keep_going):
+ keep_going = False
- def apply_rule2(self):
- pass
+ # Get the initial domain of every cell. Return failure if any are
+ # empty.
+ domains = self.get_domains()
+ if domains == False:
+ return False
- def apply_naked_triples(self):
- pass
-
+ if naked_triples:
+ domains = self.apply_naked_triples(domains)
+ for i in range(1,10):
+ si = str(i)
+ for j in range(9):
+ # Check for single domain instance of i in rows
+ row_doms = [domains[j][k] for k in range(9) if len(domains[j][k]) != 1]
+ if row_doms == []:
+ continue
+ count = reduce(lambda x,y: x+y, row_doms).count(si)
+ if count == 1:
+ for k in range(9):
+ if si in domains[j][k]:
+ self.b[j][k] = si
+ keep_going = True
+ break
+ # " " in columns
+ col_doms = [domains[k][j] for k in range(9) if len(domains[k][j]) != 1]
+ if col_doms == []:
+ continue
+ count = reduce(lambda x,y: x+y, col_doms).count(si)
+ if count == 1:
+ for k in range(9):
+ if si in domains[k][j]:
+ self.b[k][j] = si
+ keep_going = True
+ break
+ for j,k in product(range(3),range(3)):
+ # " " in boxes
+ box_rows = range(j*3,(j+1)*3)
+ box_cols = range(k*3,(k+1)*3)
+ '''
+ print box_rows
+ print box_cols
+ print [domains[l][m] for l,m in product(box_rows,box_cols) if len(domains[l][m]) != 1]
+ print
+ '''
+ box_doms = [domains[l][m] for l,m in product(box_rows,box_cols) if len(domains[l][m]) != 1]
+ if box_doms == []:
+ continue
+ count = reduce(lambda x,y: x+y, box_doms).count(si)
+ if count == 1:
+ for l,m in product(box_rows,box_cols):
+ if si in domains[l][m]:
+ self.b[l][m] = si
+ keep_going = True
+ break
+ return True
+
+ def apply_naked_triples(self,domains):
+ # k=2
+ for i in range(1,9):
+ for j in range(i+1,10):
+ # Check rows/columns
+ for k in range(9):
+ col_list = []
+ row_list = []
+ for l in range(9):
+ if i in domains[k][l] and j in domains[k][l]:
+ col_list.append(l)
+ if i in domains[l][k] and j in domains[l][k]:
+ row_list.append(l)
+ if len(col_list) == 2:
+ for m in range(9):
+ if i in domains[k][m] and m not in col_list:
+ print 'Removal'
+ domains[k][m].remove(i)
+ if j in domains[k][m] and m not in col_list:
+ print 'Removal'
+ domains[k][m].remove(j)
+ if len(row_list) == 2:
+ for m in range(9):
+ if i in domains[m][k] and m not in row_list:
+ print 'Removal'
+ domains[m][k].remove(i)
+ if j in domains[m][k] and m not in row_list:
+ print 'Removal'
+ domains[m][k].remove(j)
+
+ # Check boxes
+ for k,l in product(range(3),range(3)):
+ box_rows = range(k*3,(k+1)*3)
+ box_cols = range(l*3,(l+1)*3)
+ box_list = []
+ for m,n in product(box_rows,box_cols):
+ if i in domains[m][n] and j in domains[m][n]:
+ box_list.append([m,n])
+ if len(box_list) == 2:
+ for m,n in product(box_rows,box_cols):
+ if i in domains[m][n] and [m,n] not in box_list:
+ print 'Removal'
+ domains[m][n].remove(i)
+ if j in domains[m][n] and [m,n] not in box_list:
+ print 'Removal'
+ domains[m][n].remove(j)
+
+ # k=3
+ for h in range(1,8):
+ for i in range(h+1,9):
+ for j in range(i+1,10):
+ # Check rows/columns
+ for k in range(9):
+ col_list = []
+ row_list = []
+ for l in range(9):
+ if h in domains[k][l] and i in domains[k][l] and j in domains[k][l]:
+ col_list.append(l)
+ if h in domains[k][l] and i in domains[l][k] and j in domains[l][k]:
+ row_list.append(l)
+ if len(col_list) == 3:
+ for m in range(9):
+ if h in domains[k][m] and m not in col_list:
+ print 'Removal'
+ domains[k][m].remove(h)
+ if i in domains[k][m] and m not in col_list:
+ print 'Removal'
+ domains[k][m].remove(i)
+ if j in domains[k][m] and m not in col_list:
+ print 'Removal'
+ domains[k][m].remove(j)
+ if len(row_list) == 3:
+ for m in range(9):
+ if h in domains[m][k] and m not in row_list:
+ print 'Removal'
+ domains[m][k].remove(h)
+ if i in domains[m][k] and m not in row_list:
+ print 'Removal'
+ domains[m][k].remove(i)
+ if j in domains[m][k] and m not in row_list:
+ print 'Removal'
+ domains[m][k].remove(j)
+ # Check boxes
+ for k,l in product(range(3),range(3)):
+ box_rows = range(k*3,(k+1)*3)
+ box_cols = range(l*3,(l+1)*3)
+ box_list = []
+ for m,n in product(box_rows,box_cols):
+ if h in domains[m][n] and i in domains[m][n] and j in domains[m][n]:
+ box_list.append([m,n])
+ if len(box_list) == 3:
+ for m,n in product(box_rows,box_cols):
+ if h in domains[m][n] and [m,n] not in box_list:
+ print 'Removal'
+ domains[m][n].remove(h)
+ if i in domains[m][n] and [m,n] not in box_list:
+ print 'Removal'
+ domains[m][n].remove(i)
+ if j in domains[m][n] and [m,n] not in box_list:
+ print 'Removal'
+ domains[m][n].remove(j)
+
+ return domains
+
+ def is_solved(self):
+ # If any square is not yet assigned a number, return false. Else return
+ # true.
+ for i in range(9):
+ for j in range(9):
+ if self.b[i][j] == '-':
+ return False
+ return True
+
+# Read in the contents of the sudoku repository. Use some python voodoo to
+# parse out all of the sudokus into a list, and parse out their corresponding
+# difficulties.
repo = open('repository.txt','r').readlines()
difficulties = [repo[line_num].split()[1].lower() for line_num in range(len(repo)) if line_num % 11 == 0]
repo = [[i for i in line.replace('0','-') if not i in (' ','\n')] for line in repo]
sudokus = [repo[i*11+1:i*11+10] for i in range(len(repo)/11)]
+
+'''
sudoku = Board(sudokus[0])
+sudoku.apply_rule2(True)
sudoku.display()
-print sudoku.get_domain(0,0)
+'''
+
+a = []
+for i in range(len(sudokus)):
+ print 'Processing sudoku %d' % i
+ sudoku = Board(sudokus[i])
+ sudoku.apply_rule1(True)
+ sudoku.apply_rule2(True)
+ a += difficulties[i],sudoku.is_solved()
+print
+print len([i for i in a if i == False])
+
+#55/77 still unsolved after applying rule 1
+#54/77 still unsolved after applying rule 1, then rule 2
+#51/77 still unsolved after applying the two rules repeatedly
|
andermic/CS531
|
e9866bacd483ad73c959c711d4a678d32b71376a
|
working on prog3
|
diff --git a/hw4/.hw4.tex.swp b/prog3/.prog3.py.swp
similarity index 64%
rename from hw4/.hw4.tex.swp
rename to prog3/.prog3.py.swp
index 4c887db..c770d25 100644
Binary files a/hw4/.hw4.tex.swp and b/prog3/.prog3.py.swp differ
diff --git a/prog3/prog3.py b/prog3/prog3.py
new file mode 100644
index 0000000..06dfd0d
--- /dev/null
+++ b/prog3/prog3.py
@@ -0,0 +1,45 @@
+import os
+
+class Board:
+ b = list()
+
+ def __init__(self, board):
+ self.b = board
+
+ def display(self):
+ print ' a b c d e f g h i'
+ for i in range(3):
+ for j in range(3):
+ print '%s ' % (i*3+j+1),
+ for k in range(3):
+ for l in range(3):
+ print self.b[i*3+j][k*3+l],
+ if k != 2:
+ print '|',
+ print
+ if i != 2:
+ print '------------------------'
+
+ def get_domain(self, r, c):
+ result = [str(i) for i in range(1,10)]
+ result = [i for i in result if i not in [self.b[j][c] for j in range(0,9)]]
+ result = [i for i in result if i not in [self.b[r][j] for j in range(0,9)]]
+ return result
+
+ def apply_rule1(self):
+ pass
+
+ def apply_rule2(self):
+ pass
+
+ def apply_naked_triples(self):
+ pass
+
+
+repo = open('repository.txt','r').readlines()
+difficulties = [repo[line_num].split()[1].lower() for line_num in range(len(repo)) if line_num % 11 == 0]
+repo = [[i for i in line.replace('0','-') if not i in (' ','\n')] for line in repo]
+sudokus = [repo[i*11+1:i*11+10] for i in range(len(repo)/11)]
+sudoku = Board(sudokus[0])
+sudoku.display()
+print sudoku.get_domain(0,0)
diff --git a/prog3/prog3.pyc b/prog3/prog3.pyc
new file mode 100644
index 0000000..4945ba8
Binary files /dev/null and b/prog3/prog3.pyc differ
diff --git a/prog3/repository.txt b/prog3/repository.txt
new file mode 100644
index 0000000..59eb669
--- /dev/null
+++ b/prog3/repository.txt
@@ -0,0 +1,847 @@
+1 easy (tadepalli)
+240 300 000
+000 520 407
+000 046 008
+610 700 084
+009 060 500
+730 005 061
+100 470 000
+302 051 000
+000 002 019
+
+2 medium (tadepalli)
+003 010 008
+000 400 030
+870 003 020
+010 009 605
+300 867 002
+906 500 040
+020 900 074
+090 006 000
+500 070 100
+
+3 hard (tadepalli)
+170 000 006
+006 090 040
+300 070 000
+000 900 030
+094 020 870
+030 005 000
+000 060 001
+080 010 500
+500 000 082
+
+4 evil (tadepalli)
+000 006 009
+090 300 108
+076 000 402
+000 800 005
+000 502 000
+900 003 000
+409 000 830
+605 004 090
+700 100 000
+
+5 easy (ventura/silva)
+002 507 310
+080 000 060
+000 003 208
+004 302 081
+801 090 703
+730 804 500
+409 200 000
+060 000 050
+013 906 800
+
+6 easy (ventura/silva)
+012 800 060
+900 326 741
+000 070 200
+070 080 000
+503 102 804
+000 030 010
+009 050 000
+154 297 003
+030 008 490
+
+7 easy (ventura/silva)
+060 007 000
+508 006 027
+207 800 030
+192 000 300
+085 000 960
+006 000 278
+020 004 506
+470 600 102
+000 100 040
+
+8 medium (ventura/silva)
+020 004 000
+003 000 204
+140 080 503
+030 802 000
+200 000 006
+000 409 050
+402 070 081
+807 000 600
+000 600 070
+
+9 Evil (Wei Wu/Wei Zhang)
+400 003 106
+006 150 007
+000 000 000
+020 308 591
+009 000 300
+315 209 060
+000 000 000
+500 036 700
+904 500 008
+
+10 medium (ventura/silva)
+800 300 600
+503 890 400
+060 070 030
+008 740 000
+010 000 070
+000 039 100
+050 080 090
+004 062 801
+009 003 006
+
+11 hard (ventura/silva)
+002 090 600
+609 000 000
+480 006 000
+008 402 090
+300 000 007
+070 309 100
+000 600 051
+000 000 204
+007 080 300
+
+12 hard (ventura/silva)
+490 003 800
+605 020 000
+000 007 600
+500 800 000
+083 601 790
+000 009 008
+002 900 000
+000 080 305
+004 300 089
+
+13 hard (ventura/silva)
+100 852 000
+620 700 000
+003 000 200
+016 020 000
+800 000 001
+000 080 740
+001 000 600
+000 009 028
+000 648 005
+
+14 evil (ventura/silva)
+200 006 050
+300 090 002
+001 000 000
+560 200 400
+000 603 000
+007 005 028
+000 000 800
+700 010 003
+040 800 009
+
+15 evil (ventura/silva)
+040 500 000
+500 010 080
+001 800 400
+087 000 300
+010 203 060
+004 000 750
+002 007 600
+050 060 001
+000 002 030
+
+16 Evil (Wei Wu/Wei Zhang)
+501 300 002
+600 041 500
+000 000 000
+174 903 080
+003 000 700
+050 708 413
+000 000 000
+006 530 004
+900 004 207
+
+17 easy (lynn)
+250 700 006
+000 065 201
+630 100 540
+109 500 600
+500 000 003
+006 009 708
+063 001 087
+902 870 000
+700 006 012
+
+18 easy (lynn)
+501 037 090
+090 000 006
+008 409 001
+050 600 087
+206 090 503
+980 001 040
+600 803 400
+800 000 060
+070 920 108
+
+19 easy (brewster)
+030 190 000
+400 563 001
+002 004 093
+305 470 000
+708 000 905
+000 058 402
+970 800 300
+500 237 009
+000 016 050
+
+20 easy (brewster)
+004 300 890
+020 000 017
+010 427 003
+007 050 030
+401 000 605
+080 040 700
+800 569 070
+560 000 040
+072 004 900
+
+21 medium (lynn)
+050 061 400
+060 000 802
+000 087 006
+134 000 000
+200 000 004
+000 000 731
+800 420 000
+501 000 040
+009 810 060
+
+22 medium (lynn)
+080 010 570
+000 300 080
+100 058 023
+200 040 005
+010 509 060
+600 070 008
+530 280 004
+020 004 000
+041 090 030
+
+23 medium (brewster)
+206 070 003
+050 000 000
+900 023 000
+003 010 700
+581 030 426
+002 080 500
+000 850 007
+000 000 010
+100 040 905
+
+24 medium (brewster)
+003 060 904
+000 000 070
+000 390 100
+600 080 003
+294 030 758
+700 050 009
+006 075 000
+080 000 000
+107 020 800
+
+25 Evil (Wei Wu/Wei Zhang)
+900 002 105
+005 140 006
+000 000 000
+030 208 471
+007 000 200
+214 307 050
+000 000 000
+400 025 600
+709 400 008
+
+26 hard (lynn)
+000 001 650
+000 527 900
+500 000 003
+000 050 096
+009 000 700
+140 070 000
+600 000 009
+002 746 000
+057 800 000
+
+27 evil (brewster)
+400 070 003
+032 160 000
+000 050 080
+009 000 000
+207 090 301
+000 000 200
+070 020 000
+000 013 840
+900 080 005
+
+28 evil (brewster)
+010 000 080
+800 035 040
+004 720 000
+209 500 000
+000 040 000
+000 006 305
+000 054 700
+090 380 001
+050 000 060
+
+29 Easy (hillier)
+045 000 600
+910 605 007
+067 180 000
+700 000 450
+000 573 000
+081 000 009
+000 048 720
+800 301 064
+002 000 190
+
+30 Easy (hillier)
+600 850 300
+008 007 900
+040 910 085
+030 009 008
+520 030 067
+700 600 030
+860 042 090
+005 300 200
+002 096 003
+
+31 Medium (hillier)
+000 500 300
+020 040 010
+600 100 072
+000 305 604
+800 020 001
+403 801 000
+260 009 003
+070 050 060
+001 007 000
+
+32 Hard (hillier)
+400 008 000
+002 050 030
+500 260 000
+804 000 020
+021 080 640
+060 000 807
+000 093 006
+080 040 900
+000 500 002
+
+33 Hard (hillier)
+060 200 003
+000 008 200
+370 100 080
+006 000 720
+400 000 008
+093 000 600
+010 002 045
+008 300 000
+900 006 010
+
+34 Evil (hillier)
+006 000 470
+200 700 080
+000 620 900
+000 409 208
+000 000 000
+908 203 000
+003 052 000
+060 001 003
+049 000 100
+
+35 Medium (Kyle)
+000 000 620
+106 230 040
+900 600 001
+200 400 803
+090 000 010
+708 009 004
+600 005 008
+020 048 905
+045 000 000
+
+36 Medium (Kyle)
+400 300 000
+018 509 020
+090 400 803
+000 700 206
+072 000 540
+609 008 000
+904 007 080
+020 806 170
+000 005 002
+
+37 Hard (Kyle)
+003 900 100
+007 003 500
+000 025 070
+000 000 040
+070 348 020
+010 000 000
+040 730 000
+001 800 600
+005 006 300
+
+38 Hard (Kyle)
+403 009 000
+050 030 400
+006 020 030
+700 080 100
+030 705 060
+005 010 007
+020 090 600
+001 070 040
+000 500 809
+
+39 Evil (Kyle)
+206 401 030
+013 000 007
+000 003 000
+005 090 000
+308 000 105
+000 060 200
+000 800 000
+900 000 510
+070 609 302
+
+40 Evil (Kyle)
+000 302 090
+001 000 020
+203 000 058
+000 500 400
+010 000 080
+007 009 000
+480 000 705
+050 000 900
+070 601 000
+
+41 easy (Kyle)
+045 803 190
+070 609 020
+000 070 000
+300 906 702
+009 030 800
+406 702 009
+000 040 000
+080 107 030
+097 308 510
+
+42 easy (Kyle)
+000 065 030
+570 091 060
+020 340 008
+600 000 900
+019 628 470
+008 000 006
+700 082 050
+030 750 049
+060 910 000
+
+43 easy (Judah)
+010 006 900
+900 130 028
+800 520 106
+025 370 000
+000 000 000
+000 052 710
+703 065 001
+190 047 005
+008 900 040
+
+44 easy (Judah)
+600 000 020
+590 120 468
+004 800 000
+980 002 350
+010 609 080
+045 300 076
+000 003 700
+462 071 035
+030 000 009
+
+45 medium (Judah)
+005 300 407
+003 002 000
+100 040 080
+320 100 700
+600 924 005
+008 003 021
+060 080 009
+000 700 600
+904 006 500
+
+46 medium (Judah)
+070 050 290
+050 000 600
+306 801 000
+809 000 710
+600 000 004
+037 000 806
+000 503 109
+003 000 040
+061 090 070
+
+47 hard (Judah)
+000 060 830
+000 500 004
+503 200 060
+040 020 000
+200 931 006
+000 080 010
+050 002 407
+800 009 000
+012 070 000
+
+48 evil (Judah)
+000 000 001
+793 001 002
+120 009 000
+004 092 000
+070 000 060
+000 810 400
+000 500 043
+800 100 576
+300 000 000
+
+49 Easy (Chaitanya)
+006 300 080
+000 490 316
+301 800 740
+003 000 004
+687 000 295
+400 000 600
+058 003 901
+139 028 000
+060 007 800
+
+50 Easy (Chaitanya)
+004 900 017
+670 800 000
+509 030 004
+300 740 100
+068 000 790
+001 068 005
+100 090 306
+000 006 081
+240 001 500
+
+51 Evil (Chaitanya)
+081 260 500
+000 900 008
+000 700 200
+200 000 030
+040 000 080
+050 000 007
+004 008 000
+600 009 000
+009 014 360
+
+52 Evil (Chaitanya)
+800 093 600
+930 020 000
+006 100 000
+009 000 082
+020 000 010
+740 000 900
+000 001 400
+000 080 061
+007 340 008
+
+53 Hard (Chaitanya)
+005 908 070
+700 050 000
+400 006 200
+903 000 020
+020 090 040
+010 000 509
+002 700 008
+000 030 006
+090 601 700
+
+54 Medium (Chaitanya)
+000 600 000
+720 010 008
+590 870 000
+005 000 040
+130 486 059
+040 000 200
+000 064 032
+200 050 016
+000 009 000
+
+55 easy (mcdougal)
+007 062 001
+000 000 905
+028 410 030
+830 004 579
+000 000 000
+972 300 014
+050 047 260
+703 000 000
+200 650 100
+
+56 medium (mcdougal)
+000 160 400
+300 000 007
+006 000 200
+008 570 004
+609 324 108
+700 019 300
+003 000 600
+800 000 009
+005 092 000
+
+57 medium (mcdougal)
+000 030 100
+030 608 905
+000 071 002
+020 580 400
+040 703 020
+006 049 030
+800 160 000
+103 802 060
+004 090 000
+
+58 hard (mcdougal)
+200 040 083
+000 005 060
+001 098 000
+130 000 800
+060 030 040
+009 000 057
+000 680 700
+020 900 000
+810 070 009
+
+59 hard (mcdougal)
+000 400 098
+600 000 070
+300 080 600
+501 040 000
+030 795 080
+000 010 205
+007 050 002
+050 000 009
+240 006 000
+
+60 evil (mcdougal)
+008 070 100
+000 000 020
+500 400 800
+090 008 504
+000 104 000
+803 500 060
+007 003 009
+030 000 000
+001 020 600
+
+61 Easy (knudson)
+000 106 000
+109 348 020
+076 000 800
+502 069 103
+900 000 002
+807 230 904
+001 000 290
+090 783 406
+000 901 000
+
+62 Easy (knudson)
+200 300 001
+081 002 060
+639 004 000
+805 070 004
+002 010 500
+700 040 806
+000 500 628
+090 800 140
+500 001 003
+
+63 Medium (knudson)
+700 000 900
+000 980 030
+043 056 700
+500 100 870
+600 000 001
+071 005 003
+002 530 680
+010 024 000
+006 000 002
+
+64 Medium (knudson)
+003 051 080
+084 200 500
+000 070 400
+008 007 002
+070 000 030
+500 100 700
+001 060 000
+007 003 860
+040 820 900
+
+65 Hard (knudson)
+407 080 000
+000 900 810
+010 064 700
+000 008 203
+040 000 070
+602 300 000
+005 710 060
+086 005 000
+000 030 109
+
+66 Hard (knudson)
+000 000 000
+420 000 035
+000 071 600
+040 080 502
+002 010 700
+806 020 090
+001 360 000
+350 000 026
+000 000 000
+
+67 Easy (Wei Wu/Wei Zhang)
+068 900 305
+010 060 004
+402 073 000
+270 100 000
+009 406 200
+000 007 063
+000 310 908
+300 020 070
+104 008 630
+
+68 Easy (Wei Wu/Wei Zhang)
+018 900 206
+050 010 004
+407 032 000
+730 500 000
+009 401 700
+000 003 012
+000 250 908
+200 070 030
+504 008 120
+
+69 Easy (Wei Wu/Wei Zhang)
+201 005 360
+800 060 040
+000 170 908
+000 004 079
+009 608 500
+160 700 000
+305 041 000
+070 090 001
+016 300 804
+
+70 Easy (Wei Wu/Wei Zhang)
+013 025 090
+000 096 300
+009 000 002
+036 004 078
+980 702 031
+120 600 450
+300 000 700
+005 240 000
+060 370 920
+
+71 Medium (Wei Wu/Wei Zhang)
+010 830 200
+800 960 000
+530 000 900
+000 000 473
+600 000 009
+394 000 000
+002 000 086
+000 087 002
+005 023 090
+
+72 Medium (Wei Wu/Wei Zhang)
+900 000 000
+037 000 040
+000 142 090
+002 400 009
+800 050 003
+600 001 400
+070 298 000
+080 000 750
+000 000 002
+
+73 Medium (Wei Wu/Wei Zhang)
+400 081 000
+060 000 130
+050 300 000
+007 200 400
+001 060 300
+004 003 200
+000 004 050
+075 000 080
+000 970 001
+
+74 Medium (Wei Wu/Wei Zhang)
+300 000 000
+061 000 080
+000 287 030
+007 800 003
+900 040 006
+500 002 800
+010 739 000
+090 000 140
+000 000 007
+
+75 Hard (Wei Wu/Wei Zhang)
+306 000 000
+000 005 003
+002 004 608
+540 600 000
+008 090 700
+000 002 036
+104 200 900
+800 700 000
+000 000 807
+
+76 Hard (Wei Wu/Wei Zhang)
+801 000 000
+000 008 001
+007 005 903
+260 500 000
+008 070 100
+000 002 094
+102 900 500
+600 400 000
+000 000 206
+
+77 Hard (Wei Wu/Wei Zhang)
+700 300 150
+000 200 000
+604 050 200
+000 600 480
+000 090 000
+032 004 000
+006 080 905
+000 007 000
+075 006 008
+
|
andermic/CS531
|
3f0664362b4ef103d4dea6f6efb66125fdf73291
|
Homework 4
|
diff --git a/hw4/.hw4.tex.swp b/hw4/.hw4.tex.swp
new file mode 100644
index 0000000..4c887db
Binary files /dev/null and b/hw4/.hw4.tex.swp differ
diff --git a/hw4/hw4.aux b/hw4/hw4.aux
new file mode 100644
index 0000000..f23e546
--- /dev/null
+++ b/hw4/hw4.aux
@@ -0,0 +1 @@
+\relax
diff --git a/hw4/hw4.log b/hw4/hw4.log
new file mode 100644
index 0000000..fa4bdc4
--- /dev/null
+++ b/hw4/hw4.log
@@ -0,0 +1,165 @@
+This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) (format=pdflatex 2010.10.11) 28 OCT 2010 03:24
+entering extended mode
+ %&-line parsing enabled.
+**hw4.tex
+(./hw4.tex
+LaTeX2e <2005/12/01>
+Babel <v3.8h> and hyphenation patterns for english, usenglishmax, dumylang, noh
+yphenation, loaded.
+(/usr/share/texmf-texlive/tex/latex/base/article.cls
+Document Class: article 2005/09/16 v1.4f Standard LaTeX document class
+(/usr/share/texmf-texlive/tex/latex/base/size10.clo
+File: size10.clo 2005/09/16 v1.4f Standard LaTeX file (size option)
+)
+\c@part=\count79
+\c@section=\count80
+\c@subsection=\count81
+\c@subsubsection=\count82
+\c@paragraph=\count83
+\c@subparagraph=\count84
+\c@figure=\count85
+\c@table=\count86
+\abovecaptionskip=\skip41
+\belowcaptionskip=\skip42
+\bibindent=\dimen102
+)
+(/usr/share/texmf-texlive/tex/latex/graphics/graphicx.sty
+Package: graphicx 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texmf-texlive/tex/latex/graphics/keyval.sty
+Package: keyval 1999/03/16 v1.13 key=value parser (DPC)
+\KV@toks@=\toks14
+)
+(/usr/share/texmf-texlive/tex/latex/graphics/graphics.sty
+Package: graphics 2006/02/20 v1.0o Standard LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texmf-texlive/tex/latex/graphics/trig.sty
+Package: trig 1999/03/16 v1.09 sin cos tan (DPC)
+)
+(/etc/texmf/tex/latex/config/graphics.cfg
+File: graphics.cfg 2007/01/18 v1.5 graphics configuration of teTeX/TeXLive
+)
+Package graphics Info: Driver file: pdftex.def on input line 90.
+
+(/usr/share/texmf-texlive/tex/latex/pdftex-def/pdftex.def
+File: pdftex.def 2007/01/08 v0.04d Graphics/color for pdfTeX
+\Gread@gobject=\count87
+))
+\Gin@req@height=\dimen103
+\Gin@req@width=\dimen104
+)
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsmath.sty
+Package: amsmath 2000/07/18 v2.13 AMS math features
+\@mathmargin=\skip43
+
+For additional information on amsmath, use the `?' option.
+(/usr/share/texmf-texlive/tex/latex/amsmath/amstext.sty
+Package: amstext 2000/06/29 v2.01
+
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsgen.sty
+File: amsgen.sty 1999/11/30 v2.0
+\@emptytoks=\toks15
+\ex@=\dimen105
+))
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsbsy.sty
+Package: amsbsy 1999/11/29 v1.2d
+\pmbraise@=\dimen106
+)
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsopn.sty
+Package: amsopn 1999/12/14 v2.01 operator names
+)
+\inf@bad=\count88
+LaTeX Info: Redefining \frac on input line 211.
+\uproot@=\count89
+\leftroot@=\count90
+LaTeX Info: Redefining \overline on input line 307.
+\classnum@=\count91
+\DOTSCASE@=\count92
+LaTeX Info: Redefining \ldots on input line 379.
+LaTeX Info: Redefining \dots on input line 382.
+LaTeX Info: Redefining \cdots on input line 467.
+\Mathstrutbox@=\box26
+\strutbox@=\box27
+\big@size=\dimen107
+LaTeX Font Info: Redeclaring font encoding OML on input line 567.
+LaTeX Font Info: Redeclaring font encoding OMS on input line 568.
+\macc@depth=\count93
+\c@MaxMatrixCols=\count94
+\dotsspace@=\muskip10
+\c@parentequation=\count95
+\dspbrk@lvl=\count96
+\tag@help=\toks16
+\row@=\count97
+\column@=\count98
+\maxfields@=\count99
+\andhelp@=\toks17
+\eqnshift@=\dimen108
+\alignsep@=\dimen109
+\tagshift@=\dimen110
+\tagwidth@=\dimen111
+\totwidth@=\dimen112
+\lineht@=\dimen113
+\@envbody=\toks18
+\multlinegap=\skip44
+\multlinetaggap=\skip45
+\mathdisplay@stack=\toks19
+LaTeX Info: Redefining \[ on input line 2666.
+LaTeX Info: Redefining \] on input line 2667.
+)
+No file hw4.aux.
+\openout1 = `hw4.aux'.
+
+LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 7.
+LaTeX Font Info: ... okay on input line 7.
+LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 7.
+LaTeX Font Info: ... okay on input line 7.
+LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 7.
+LaTeX Font Info: ... okay on input line 7.
+LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 7.
+LaTeX Font Info: ... okay on input line 7.
+LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 7.
+LaTeX Font Info: ... okay on input line 7.
+LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 7.
+LaTeX Font Info: ... okay on input line 7.
+
+Underfull \hbox (badness 10000) in paragraph at lines 19--23
+
+ []
+
+[1
+
+{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}]
+Overfull \hbox (0.1775pt too wide) detected at line 93
+\OML/cmm/m/it/10 D[] \OT1/cmr/m/n/10 = \OMS/cmsy/m/n/10 f\OT1/cmr/m/n/10 [1\OML
+/cmm/m/it/10 ; \OT1/cmr/m/n/10 1]\OML/cmm/m/it/10 ; \OT1/cmr/m/n/10 [1\OML/cmm/
+m/it/10 ; \OT1/cmr/m/n/10 2]\OML/cmm/m/it/10 ; [] ; \OT1/cmr/m/n/10 [1\OML/cmm/
+m/it/10 ; n\OT1/cmr/m/n/10 ]\OML/cmm/m/it/10 ; \OT1/cmr/m/n/10 [2\OML/cmm/m/it/
+10 ; \OT1/cmr/m/n/10 1]\OML/cmm/m/it/10 ; \OT1/cmr/m/n/10 [2\OML/cmm/m/it/10 ;
+\OT1/cmr/m/n/10 2]\OML/cmm/m/it/10 ; [] ; \OT1/cmr/m/n/10 [2\OML/cmm/m/it/10 ;
+n\OT1/cmr/m/n/10 ]\OML/cmm/m/it/10 ; [] ; \OT1/cmr/m/n/10 [\OML/cmm/m/it/10 n;
+n \OMS/cmsy/m/n/10 ^^@ \OT1/cmr/m/n/10 1]\OML/cmm/m/it/10 ; \OT1/cmr/m/n/10 [\O
+ML/cmm/m/it/10 n; n\OT1/cmr/m/n/10 ]\OMS/cmsy/m/n/10 g
+ []
+
+[2] (./hw4.aux) )
+Here is how much of TeX's memory you used:
+ 1151 strings out of 95086
+ 13224 string characters out of 1183254
+ 65906 words of memory out of 1500000
+ 4371 multiletter control sequences out of 10000+50000
+ 4402 words of font info for 17 fonts, out of 1200000 for 2000
+ 28 hyphenation exceptions out of 8191
+ 27i,4n,21p,216b,182s stack positions out of 5000i,500n,6000p,200000b,5000s
+</usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmbx10.pfb></
+usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmex10.pfb></usr/share/texmf-tex
+live/fonts/type1/bluesky/cm/cmmi10.pfb></usr/share/texmf-texlive/fonts/type1/bl
+uesky/cm/cmmi7.pfb></usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmr10.pfb><
+/usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmr7.pfb></usr/share/texmf-texl
+ive/fonts/type1/bluesky/cm/cmsy10.pfb></usr/share/texmf-texlive/fonts/type1/blu
+esky/cm/cmsy7.pfb>
+Output written on hw4.pdf (2 pages, 45712 bytes).
+PDF statistics:
+ 41 PDF objects out of 1000 (max. 8388607)
+ 0 named destinations out of 1000 (max. 131072)
+ 1 words of extra memory for PDF output out of 10000 (max. 10000000)
+
diff --git a/hw4/hw4.pdf b/hw4/hw4.pdf
new file mode 100644
index 0000000..96b3251
Binary files /dev/null and b/hw4/hw4.pdf differ
diff --git a/hw4/hw4.tex b/hw4/hw4.tex
new file mode 100644
index 0000000..bc44a49
--- /dev/null
+++ b/hw4/hw4.tex
@@ -0,0 +1,113 @@
+\documentclass{article}
+\usepackage[pdftex]{graphicx}
+\usepackage{amsmath}
+\pagestyle{empty}
+\author{Michael Anderson}
+\title{Homework Set 4}
+\begin{document}
+\begin{enumerate}
+\item[\textbf{5.8}]
+
+\begin{enumerate}
+\item[b)]
+If MAX has a choice between a ? node or a 1 node, it will choose the 1 node,
+and vice versa for MIN with -1 nodes. This is because the payoff is bounded by
+the constraints of the game to \\ $1\ge$ payoff $\ge -1$. Players need not
+consider nodes of unknown value when know they can travel to a sibling that has
+the best value possible.
+\item[c)]
+The minimax algorithm would fail in this game because of the cycles that are
+created by repeated states. This would create loops of recursive calls in the
+algorithm that never reach a base case and therefore would continue
+indefinitely. \\
+
+MAX-VALUE and MIN-VALUE could pass all ancestor states to their
+children with each recursive call. Then a base case could be added to both: if
+the current state is not a terminal state but it is in the ancestor list,
+return 0. In this particular example this change is effective, because the only
+cases in which a node has to choose between an unknown path and a known one is
+when the known path leads to a victory. In other games the known path(s) may
+lead to a defeat or a negative outcome, which would case the player to choose
+the unknown path, possibly creating a cycle.
+\item[d)]
+The optimum strategy for both players is to travel toward their destination at
+every move. If a player does and the other player does not, the first player
+will reach a state where it has less moves to its destination than the second.
+When both players move toward each other, they will meet in the middle at some
+point. If n = 3, then state 2,3 will be reached with B to move and B will win
+by moving to 1,3. If n = 4, then state 2,3 will be reached with A to move and A
+will win by moving to state 1,3. All games with odd values of n will be winning
+for B because the game can be visualized as an n = 3 game with an equal number
+of squares added to either side of the point where the two players meet, and B
+because B was winning where n = 3, it will reach its destination faster than A
+because it takes each player the same amount of time to traverse an equal number
+of squares. The same argument can be made to justify a win for A when n is
+even.
+\end{enumerate}
+\newpage
+
+\item[\textbf{5.10}]
+\begin{enumerate}
+\item[a)]
+In each node in the tree, each square could be either marked with an X, marked
+with an O, or not yet marked. So there could be at most $3^N$ nodes.
+\item[b)]
+The tree has at least as many nodes as it has leaves. Each leaf would be a
+cat's game with all squares marked as either X or O. So there must be at least
+$2^N$ nodes.
+\item[c)]
+The evaluation function used in 5.9 is plausible because $X_2$ and $O_2$ are
+quite a bit more important than $X_1$ and $O_1$. In particular, it seems
+plausible that $X_{n+1}$ should be weighted with 3 times as much importance as
+$X_n$, and similarly for O. For generalized tic-tac-toe, redefine $X_n(s)$ as
+the number of winning positions containing exactly $n$ X's and no O's within
+state $s$, and vice versa for $O_n$. The evaluation function then becomes:
+\[
+Eval(s) = \sum_{i=1}^n (3^{i-1}X_i(s) - 3^{i-1}O_i(s))
+\]
+\item[d)]
+\[
+1s = 3^N \frac{100N instr}{2 \times 10^9 instr/s} \Longrightarrow N \approx 13
+\]
+\[
+60s = 3^N \frac{100N instr}{2 \times 10^9 instr/s} \Longrightarrow N \approx 16
+\]
+\[
+3600s = 3^N \frac{100N instr}{2 \times 10^9 instr/s} \Longrightarrow N \approx 20
+\]
+
+\end{enumerate}
+
+\item[\textbf{6.2}]
+\begin{enumerate}
+\item[a)]
+Let $X = \{N_1,N_2, \ldots ,N_k\}$, the set of all knights (N is the
+abbreviation for knight in chess notation).
+\item[b)]
+Each knight can be assigned one of the squares on the chessboard. Formally, D
+is the cartesian product of the set of natural numbers $\le$ the width of
+the chessboard, for each knight. I.e.
+\[
+D_i = \{[1,1],[1,2], \ldots ,[1,n],[2,1],
+[2,2], \ldots ,[2,n], \ldots ,[n,n-1],[n,n]\}
+\]
+\item[c)]
+Each knight is constrained to only take squares that cannot be attacked by any
+other knight already assigned a square. More formally, this is a large set of
+binary constraints such as
+\[
+\langle (N_1,N_2), (N_{1,row} \ne N_{2,row} + 1) or
+(N_{1,column} \ne N_{2,column} + 2) \rangle
+\]
+\item[d)]
+This could be formulated as a local search problem by making all knights
+unassigned to squares in the initial state. An action would be to assign a
+knight to a square, which would lead to a new state. The objective function
+would simply count the number of assigned knights. The more knights assigned,
+the better. States that are not arc-consistent would be failures and not
+expanded further.
+\end{enumerate}
+
+
+\end{enumerate}
+\end{document}
diff --git a/prog2/.prog2.cpp.swp b/prog2/.prog2.cpp.swp
deleted file mode 100644
index db142f2..0000000
Binary files a/prog2/.prog2.cpp.swp and /dev/null differ
diff --git a/prog2/a.out b/prog2/a.out
index df51b6c..1958c48 100755
Binary files a/prog2/a.out and b/prog2/a.out differ
diff --git a/prog2/prog2.cpp b/prog2/prog2.cpp
index 7f53333..918b294 100644
--- a/prog2/prog2.cpp
+++ b/prog2/prog2.cpp
@@ -1,210 +1,223 @@
/*
For algorithms A* and RBFS
For each heuristic function h,
For at least 4 different sizes (number of disks)
For each of the 20 problems p,
Solve p using h or until NMAX nodes are expanded.
Record the solution length if successful, the number of nodes
expanded, and the total CPU time spent on evaluating
the heuristic and on solving the whole problem.
*/
#include <iostream>
#include <vector>
#include <stack>
#include <cstdlib>
#include <algorithm>
using namespace std;
const bool A_STAR = true;
const bool RBFS = false;
const bool ADMISSIBLE = true;
const bool NONADMISSIBLE = false;
const int M = 3;
const int NODEMAX = 1000000;
-void display(vector< string > p) {
- int max_plates = 0;
- int i;
- for(i = 0; i < p.size(); ++i) {
- if(p[i].size() > max_plates)
- max_plates = p[i].size();
- }
- for(i = max_plates - 1; i >= 0; --i) {
- for(int ii = 0; ii < p.size(); ++ii) {
- if(p[ii].size() > i) {
- for(int iii = atoi(&p[ii][p[ii].size()-1]); iii > 0; --iii)
- cout << '-';
- p[ii].erase(p[ii].size()-1, 1);
- }
- cout << "\t\t";
- }
- cout << '\n';
- }
+void display(vector< string > p, bool fancy) {
+ if(fancy) {
+ int max_plates = 0;
+ int i;
+ for(i = 0; i < p.size(); ++i) {
+ if(p[i].size() > max_plates)
+ max_plates = p[i].size();
+ }
+ for(i = max_plates - 1; i >= 0; --i) {
+ for(int ii = 0; ii < p.size(); ++ii) {
+ if(p[ii].size() > i) {
+ for(int iii = atoi(&p[ii][p[ii].size()-1]); iii > 0; --iii)
+ cout << '-';
+ p[ii].erase(p[ii].size()-1, 1);
+ }
+ cout << "\t\t";
+ }
+ cout << endl;
+ }
+ }
+ else {
+ for(int i = 0; i < p.size(); ++i) {
+ cout << p[i] << endl;
+ }
+ cout << endl;
+ }
}
class Node {
public:
Node* parent;
vector<string> state;
int g;
int f;
Node() {}
Node(Node* p, int m, string initial, int gcost, bool heuristic) {
parent = p;
state.resize(m);
state[0] = initial;
g = gcost;
f = g + evaluate(heuristic);
}
bool operator<(Node &other) {
return f > other.f;
}
//TODO
int evaluate(bool heuristic) {
if(heuristic == ADMISSIBLE) {
return 1;
}
else if(heuristic == NONADMISSIBLE) {
return 1;
}
}
};
class Search {
int n;
bool heur;
int expanded;
public:
Node astar(Node root) {
vector<Node> frontier;
vector< vector<string> > explored;
frontier.push_back(root);
Node cur;
char c;
vector<string> child;
bool is_in_frontier_explored;
while(1) {
if(frontier.empty()) {
Node temp(NULL,0,"",0,0);
return temp;
}
pop_heap(frontier.begin(), frontier.end());
cur = frontier[frontier.size()-1];
frontier.pop_back();
//DEBUG BEGIN
+ expanded++;
system("clear");
- display(cur.state);
- cout << endl << "Press enter to continue";
+ display(cur.state, true);
+ cout << " Nodes expanded: " << expanded << endl;
char blah;
cin >> blah;
//DEBUG END
- if(goaltest(cur))
- cout << endl << "SOLUTION FOUND"; //DEBUG
+ if(goaltest(cur)) {
+ cout << endl << "SOLUTION FOUND" << endl << "Press enter to continue";
+ char blah;
+ cin >> blah;
return cur;
+ }
explored.push_back(cur.state);
for(int i = 0; i < cur.state.size(); ++i) {
for(int ii = 0; ii < cur.state.size(); ++ii) {
if( (i != ii) && (!cur.state[i].empty()) ) {
Node child;
for(int iii = 0; iii < cur.state.size(); ++iii) {
child.state.push_back(cur.state[iii]);
}
child.parent = &cur;
child.g = cur.g + 1;
child.f = child.evaluate(heur) + child.g;
c = child.state[i][child.state[i].size()-1];
child.state[i].erase(child.state[i].size()-1,1);
child.state[ii].push_back(c);
is_in_frontier_explored = false;
- for(int i = 0; i < frontier.size(); ++i) {
- if(equal(child.state.begin(),child.state.end(),frontier[i].state.begin())) {
+ for(int iii = 0; iii < frontier.size(); ++iii) {
+ if(equal(child.state.begin(),child.state.end(),frontier[iii].state.begin())) {
is_in_frontier_explored = true;
- if(child.f < frontier[i].f) {
- frontier[i] = child;
+ if(child.f < frontier[iii].f) {
+ frontier[iii] = child;
}
}
}
for(int iii = 0; iii < explored.size(); ++iii) {
if(equal(child.state.begin(),child.state.end(),explored[iii].begin())) {
is_in_frontier_explored = true;
break;
}
}
if(!is_in_frontier_explored) {
frontier.push_back(child);
}
}
}
}
}
}
Node rbfs(Node node) {
}
Search(string initial, bool search, bool heuristic) {
expanded = 0;
n = initial.size();
heur = heuristic;
Node* root = new Node(NULL, M, initial, 0, heuristic);
Node solution;
if(search == A_STAR)
- solution = astar(*root);
+ solution = astar(*root);
else if(search == RBFS)
solution = rbfs(*root);
if(solution.state.empty()) {
cout << endl << "FAILURE" << endl;
}
else {
stack<Node*> solution_path;
Node* cur = &solution;
while(cur != NULL) {
+ system("clear");
+ display(cur->state, true);
+ char blah;
+ cin >> blah;
solution_path.push(cur);
cur = cur->parent;
}
while(!solution_path.empty()) {
//DEBUG BEGIN
system("clear");
- display(solution_path.top()->state);
+ //display(solution_path.top()->state, true);
solution_path.pop();
cout << endl << "Press enter to continue";
char blah;
cin >> blah;
//DEBUG END
}
}
}
-
- bool goaltest(Node node) {
+ bool goaltest(Node node) {
if(node.state[0].size() == n) {
for(int i = 0; i < n; ++i) {
- if(atoi(&node.state[0][i]) != n-i) return false;
+ if(node.state[0][i]-48 != n-i) {
+ return false;
+ }
}
return true;
}
return false;
}
};
-struct SearchTree {
- Node* root;
-};
-
int main() {
- string test = "123";
+ string test = "12";
Search* a = new Search(test, A_STAR, ADMISSIBLE);
}
diff --git a/prog2/prog2_description.html b/prog2/prog2_description.html
new file mode 100644
index 0000000..28a6c0e
--- /dev/null
+++ b/prog2/prog2_description.html
@@ -0,0 +1,131 @@
+<title>CS531 Programming Assignment 2</title>
+<center>
+<h1>CS531 Program 2 (Due October 26, 2010)</h1>
+<h1> Towers of Corvallis </h1>
+</center>
+
+
+<p>
+If you had attended Prof. Cull's talk yesterday, you know all
+about the Towers of Hanoi. The nice thing about the Towers of
+Hanoi is that it does not need search to solve it. In this assignment
+you will be solving a more difficult(!) puzzle called Towers of Corvallis.
+Towers of Corvallis consist of m pegs and n disks. We fix m=3. Unlike
+in Towers of Hanoi, here any disk can go on any other. The goal simply
+is to get from an initial position to a goal position in the smallest
+number of steps. Remember you can only remove the top disk
+from the peg at any time and place it on the top of the disks on
+another peg!
+
+<p>
+Suppose m=3 and n=10. Let us number the disks 0-9 so that we
+can denote a state with 3 numbers or lists or arrays or whatever.
+For example, (0123456789,-,-) is a state and (012,3456,789) is
+another state, etc. The leftmost digit in the number is at the top.
+Let us fix the goal (final) state to be
+(9876543210,_,_) if there are 10 disks (and similarly for n disks).
+Also fix the initial state to be some configuration of disks,
+all of which are on the first peg. Call the three pegs A,B, and C.
+
+<p>
+You will write a search program to solve this puzzle using A* and RBFS.
+You will also design and implement one admissible heuristic for this
+problem and one non-admissible heuristic.
+
+<p>
+You may use any programming language, but it must be modularized
+as much as possible. The code must be developed completely by
+your team.
+
+<p> NMAX is the maximum number of nodes you have the time to search.
+ Set this so that the search takes less that 10 minutes with your
+ least informed heuristic and slowest algorithm on the hardest
+ problems on your computer.
+
+</ul>
+<pre>
+ For the two algorithms A* and RBFS
+ For each heuristic function h,
+ For at least 4 different sizes (number of disks)
+ For each of the 20 problems p,
+ Solve p using h or until NMAX nodes are expanded.
+ Record the solution length if successful, the number of nodes
+ expanded, and the total CPU time spent on evaluating
+ the heuristic and on solving the whole problem.
+</pre>
+
+A list of several problems with numbers of disks
+<a href="perms-4.txt"> 4 </A>,
+<a href="perms-5.txt"> 5 </A>,
+<a href="perms-6.txt"> 6 </A>,
+<a href="perms-7.txt"> 7 </A>,
+<a href="perms-8.txt"> 8 </A>,
+<a href="perms-9.txt"> 9 </A>,
+<a href="perms-10.txt"> 10 </A>,
+are available. Only the starting state is described
+for each problem and all the disks are assumed to be on peg A.
+The final state for all problems is the same. It is to get all
+disks to peg A in the order 9876543210. The top disk is the leftmost.
+As described in the pseudocode, you should at least try 4 different
+sizes (number of disks) of problems.
+
+<p>
+Plot the number of nodes searched against the problem size (number of disks)
+for the two algorithms and the two heuristics. Plot similar graphs
+for CPU time vs number of disks.
+
+<p>
+Show in a table, the average solution lengths found
+by the different heuristics for each problem size (number of disks),
+heuristic, and search algorithm.
+
+<p>
+For the report, let us follow the same format you used for the first
+programming assignment. Your report should look like a
+research paper with abstract, introduction (a summary of the goals and
+results), pseudocode of the algorithms, experimental setup, result tables
+and plots, and the discussion. You should include answers to following
+questions in your discussion of results. Please feel free to add any other
+important observations.
+
+<ol>
+<li> Show an example solution sequence for each algorithm for the largest
+size you tested in the following format:
+<pre>
+[0123,_,_], [123,0,_], [23,0,1], [23,_,01] ...
+</pre>
+
+<li> Is there a clear preference ordering among the heuristics you
+ tested considering the number of nodes searched and the total
+ CPU time taken to solve the problems for the two algorithms?
+<li>
+ Can a small sacrifice in optimality give a large reduction
+ in the number of nodes expanded? What about CPU time?
+<li>
+ How did you come up with your heuristic evaluation functions?
+
+<li> How do the two algorithms compare in the amount of search
+ involved and the cpu-time?
+
+<li> Do you think that either of these algorithms scale to even larger
+ problems? What is the largest problem you could solve with the best
+ algorithm+heuristic combination? Report the wall-clock time,
+ CPU-time, and the number of nodes searched.
+
+<li> Is there any tradeoff between how good a heuristic is in cutting
+ down the number of nodes and how long it took to compute? Can you
+ quantify it?
+
+<li> Is there anything else you found that is of interest?
+</ol>
+
+<b> Important Note: </b> It is very important for this assignment
+to write efficient code.
+
+<p> Submit the source code using the <A href="http://engr.oregonstate.edu/teach">
+ENGR assignment submission system</A>. Click "Login to ENGR". Login,
+and click the "Submit an Assignment" button.
+
+Submit the report in the class on Oct, 26. </H2>
+<hr>
+
|
andermic/CS531
|
642a09a78acd21b7b71a3d48add410ed621fc2bd
|
Added a folder for hw1. Added hw3. Working on prog2
|
diff --git a/hw1.doc b/hw1/hw1.doc
similarity index 100%
rename from hw1.doc
rename to hw1/hw1.doc
diff --git a/hw3/hw3.aux b/hw3/hw3.aux
new file mode 100644
index 0000000..f23e546
--- /dev/null
+++ b/hw3/hw3.aux
@@ -0,0 +1 @@
+\relax
diff --git a/hw3/hw3.log b/hw3/hw3.log
new file mode 100644
index 0000000..886b52e
--- /dev/null
+++ b/hw3/hw3.log
@@ -0,0 +1,155 @@
+This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) (format=pdflatex 2010.10.11) 21 OCT 2010 08:18
+entering extended mode
+ %&-line parsing enabled.
+**hw3.tex
+(./hw3.tex
+LaTeX2e <2005/12/01>
+Babel <v3.8h> and hyphenation patterns for english, usenglishmax, dumylang, noh
+yphenation, loaded.
+(/usr/share/texmf-texlive/tex/latex/base/article.cls
+Document Class: article 2005/09/16 v1.4f Standard LaTeX document class
+(/usr/share/texmf-texlive/tex/latex/base/size10.clo
+File: size10.clo 2005/09/16 v1.4f Standard LaTeX file (size option)
+)
+\c@part=\count79
+\c@section=\count80
+\c@subsection=\count81
+\c@subsubsection=\count82
+\c@paragraph=\count83
+\c@subparagraph=\count84
+\c@figure=\count85
+\c@table=\count86
+\abovecaptionskip=\skip41
+\belowcaptionskip=\skip42
+\bibindent=\dimen102
+)
+(/usr/share/texmf-texlive/tex/latex/graphics/graphicx.sty
+Package: graphicx 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texmf-texlive/tex/latex/graphics/keyval.sty
+Package: keyval 1999/03/16 v1.13 key=value parser (DPC)
+\KV@toks@=\toks14
+)
+(/usr/share/texmf-texlive/tex/latex/graphics/graphics.sty
+Package: graphics 2006/02/20 v1.0o Standard LaTeX Graphics (DPC,SPQR)
+
+(/usr/share/texmf-texlive/tex/latex/graphics/trig.sty
+Package: trig 1999/03/16 v1.09 sin cos tan (DPC)
+)
+(/etc/texmf/tex/latex/config/graphics.cfg
+File: graphics.cfg 2007/01/18 v1.5 graphics configuration of teTeX/TeXLive
+)
+Package graphics Info: Driver file: pdftex.def on input line 90.
+
+(/usr/share/texmf-texlive/tex/latex/pdftex-def/pdftex.def
+File: pdftex.def 2007/01/08 v0.04d Graphics/color for pdfTeX
+\Gread@gobject=\count87
+))
+\Gin@req@height=\dimen103
+\Gin@req@width=\dimen104
+)
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsmath.sty
+Package: amsmath 2000/07/18 v2.13 AMS math features
+\@mathmargin=\skip43
+
+For additional information on amsmath, use the `?' option.
+(/usr/share/texmf-texlive/tex/latex/amsmath/amstext.sty
+Package: amstext 2000/06/29 v2.01
+
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsgen.sty
+File: amsgen.sty 1999/11/30 v2.0
+\@emptytoks=\toks15
+\ex@=\dimen105
+))
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsbsy.sty
+Package: amsbsy 1999/11/29 v1.2d
+\pmbraise@=\dimen106
+)
+(/usr/share/texmf-texlive/tex/latex/amsmath/amsopn.sty
+Package: amsopn 1999/12/14 v2.01 operator names
+)
+\inf@bad=\count88
+LaTeX Info: Redefining \frac on input line 211.
+\uproot@=\count89
+\leftroot@=\count90
+LaTeX Info: Redefining \overline on input line 307.
+\classnum@=\count91
+\DOTSCASE@=\count92
+LaTeX Info: Redefining \ldots on input line 379.
+LaTeX Info: Redefining \dots on input line 382.
+LaTeX Info: Redefining \cdots on input line 467.
+\Mathstrutbox@=\box26
+\strutbox@=\box27
+\big@size=\dimen107
+LaTeX Font Info: Redeclaring font encoding OML on input line 567.
+LaTeX Font Info: Redeclaring font encoding OMS on input line 568.
+\macc@depth=\count93
+\c@MaxMatrixCols=\count94
+\dotsspace@=\muskip10
+\c@parentequation=\count95
+\dspbrk@lvl=\count96
+\tag@help=\toks16
+\row@=\count97
+\column@=\count98
+\maxfields@=\count99
+\andhelp@=\toks17
+\eqnshift@=\dimen108
+\alignsep@=\dimen109
+\tagshift@=\dimen110
+\tagwidth@=\dimen111
+\totwidth@=\dimen112
+\lineht@=\dimen113
+\@envbody=\toks18
+\multlinegap=\skip44
+\multlinetaggap=\skip45
+\mathdisplay@stack=\toks19
+LaTeX Info: Redefining \[ on input line 2666.
+LaTeX Info: Redefining \] on input line 2667.
+) (./hw3.aux)
+\openout1 = `hw3.aux'.
+
+LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 6.
+LaTeX Font Info: ... okay on input line 6.
+LaTeX Font Info: Try loading font information for OMS+cmr on input line 44.
+
+(/usr/share/texmf-texlive/tex/latex/base/omscmr.fd
+File: omscmr.fd 1999/05/25 v2.5h Standard LaTeX font definitions
+)
+LaTeX Font Info: Font shape `OMS/cmr/m/n' in size <10> not available
+(Font) Font shape `OMS/cmsy/m/n' tried instead on input line 44.
+ [1
+
+{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}] [2] [3] (./hw3.aux) )
+Here is how much of TeX's memory you used:
+ 1196 strings out of 95086
+ 13799 string characters out of 1183254
+ 65906 words of memory out of 1500000
+ 4400 multiletter control sequences out of 10000+50000
+ 8457 words of font info for 31 fonts, out of 1200000 for 2000
+ 28 hyphenation exceptions out of 8191
+ 27i,6n,21p,224b,241s stack positions out of 5000i,500n,6000p,200000b,5000s
+</usr
+/share/texmf-texlive/fonts/type1/bluesky/cm/cmbx10.pfb></usr/share/texmf-texliv
+e/fonts/type1/bluesky/cm/cmmi10.pfb></usr/share/texmf-texlive/fonts/type1/blues
+ky/cm/cmmi7.pfb></usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmr10.pfb></us
+r/share/texmf-texlive/fonts/type1/bluesky/cm/cmr12.pfb></usr/share/texmf-texliv
+e/fonts/type1/bluesky/cm/cmr17.pfb></usr/share/texmf-texlive/fonts/type1/bluesk
+y/cm/cmr7.pfb></usr/share/texmf-texlive/fonts/type1/bluesky/cm/cmsy10.pfb></usr
+/share/texmf-texlive/fonts/type1/bluesky/cm/cmsy7.pfb></usr/share/texmf-texlive
+/fonts/type1/bluesky/cm/cmti10.pfb>
+Output written on hw3.pdf (3 pages, 52292 bytes).
+PDF statistics:
+ 52 PDF objects out of 1000 (max. 8388607)
+ 0 named destinations out of 1000 (max. 131072)
+ 1 words of extra memory for PDF output out of 10000 (max. 10000000)
+
diff --git a/hw3/hw3.pdf b/hw3/hw3.pdf
new file mode 100644
index 0000000..d154312
Binary files /dev/null and b/hw3/hw3.pdf differ
diff --git a/hw3/hw3.tex b/hw3/hw3.tex
new file mode 100644
index 0000000..82c19b8
--- /dev/null
+++ b/hw3/hw3.tex
@@ -0,0 +1,129 @@
+\documentclass{article}
+\usepackage[pdftex]{graphicx}
+\usepackage{amsmath}
+\author{Michael Anderson}
+\title{Homework Set 3}
+\begin{document}
+\maketitle
+\center{CS531}
+\center{Prof. Tadepalli}\\
+\flushleft
+\begin{enumerate}
+\item[\textbf{4.2}]
+One way to formulate this problem is to begin with no tracks placed as the
+initial state. A state consists of the tracks so far placed, where they
+and connected to one another, and the amount of rotation in each connection.
+To transition from one state to the next, a track can be added
+to any tracks already in the current state. The branching factor is based on
+the number of tracks that can be added, and where each one can be attached,
+and the amount of rotation (up to 10 degrees) off center that the piece is
+placed with. The goal is reached when all of the pieces have been placed,
+and there are no overlapping pieces, or unconnected piece edges.
+
+This problem could be solved with simulated annealing by using a utility
+function $f$:
+\[
+ f(state) = p - u - o
+\]
+where p is the number of tracks so far placed, u is the number of unconnected
+edges, and o is the number of overlapping pieces.
+
+\item[\textbf{4.5}]
+The information that would need to be stored is already given, all of the
+states so far visited at any given point in the search would need to be stored
+in a list.
+
+If a state is found to already be visited, there are two cases that need to be
+handled, the already visited state led to a goal, or it failed. If it led to a
+goal, then label the subplan that comes out of that goal, and redirect the
+current state to that label to avoid redundancy. If the already visited state
+failed to reach a goal, then consider the current state failed as well and do
+not expand it.
+
+\item[\textbf{4.7}]
+Let \{ $s_1,s_2 \ldots s_{n-1}, s_n$ \}, denote the set of $n$ states contained
+within some belief state $b$. Then:
+\[
+ h(b) = min(h*(s_1), h*(s_2) \ldots h*(s_{n-1}),h*(s_n))
+\]
+In other words, make $h(b)$ the minimum of the optimal costs of solving any of
+the states within $b$. The admissibility of this heuristic is fairly straight-
+forward intuitively, there can be no solution from b that costs less than the
+lowest optimum cost from any of the states in $b$ to a goal state, so this
+$h(b)$ cannot be over-optimistic.\\
+
+This heuristic performs poorly in the vacuum cleaner example, because as far
+as the agent knows it may start in a goal state, and at any point it might be
+in a goal state (the floor may be completely clean). So $h(b)$ always equals 0.
+
+\item[\textbf{4.8}]
+\begin{enumerate}
+\item[a)]
+The proof is very simple. By definition, if an action sequence is a solution
+for a belief state b, then it is a solution for each of the states contained
+within b. By the definition of subset there are no states contained within any
+subset of b that are not contained within b itself. Therefore any action
+sequence that solves b must also solve all of the states within any subset
+of b, and therefore must solve any subset of b.
+
+The same cannot be said of supersets of b, because they may contain states that
+are not solvable by an action sequence that solves b. All that can be said is
+that an action sequence that solves b solves \emph{some} of the states in any
+superset of b, if $b \ne \emptyset$.
+\item[b)]
+The generic GRAPH-SEARCH algorithm expands leaf nodes if they are not already
+in the explored set or the frontier set. GRAPH-SEARCH should also consider
+whether a leaf node (a belief set) is a subset of a node already in the
+explored set (by iteration through the explored set and comparison), and if it
+is then instead of expanding it simply return that belief set's corresponding
+solution (or failure).
+\item[c)]
+When AND-OR-GRAPH-SEARCH is performed with belief states, before considering
+the actions that can be taken from a given belief state (which occurs in OR-
+SEARCH), check to see if the belief state is a subset of belief states that
+have already been explored. If it is, then end the search and simply return
+the plan corresponding to the already-explored superset.
+\end{enumerate}
+
+\item[\textbf{4.12}]
+\begin{enumerate}
+\item[a)]
+In the initial state the agent knows that there are no walls up or to the
+right of it, because it perceives it can legally make those moves. It is
+ignorant of where walls are located in the rest of the environment. Each
+belief state in the initial state would correspond to some combination of
+walls either occurring or not occuring in the remainder of the environment
+in between squares in the grid.
+
+There may be up to 2 full columns of 3 walls that partition
+the 3 columns of the grid, and there may be
+be up to 2 full rows of walls that partition the 3 rows of the grid. $2
+\times 3 + 2 \times 3 = 6 + 6 = 12$ walls. Since the agent has to consider that
+each of these walls could either exist or not exist, there are $2^{12} = 4096$
+possible configurations of the environment from the initial position.
+
+\item[b)]
+Since it is impossible to move down or left no matter what, there are
+only 2 walls remaining that could exist or not exist, giving $2^2 = 4$ unique
+percepts from the initial state.
+
+\item[c)]
+As shown in b), there are 4 possible percepts from the initial state. If the
+agent is completely walled in, then no action can be taken. The agent has 1
+possible action if there is one wall, and 2 possible actions if there are
+no walls. So there are $0 + 1 + 1 + 2 = 4$ branches from the initial node.
+
+If the agent now considers possible situations arising from its position at
+either (2,1) or (1,2), it sees that it may be able to go in any of 3
+directions. Two neighboring walls are possible from either square, giving
+$2^2 \times 2 = 8$ possible wall configurations. From either square if it is
+walled in it can only go back to (0,0). If there is one new neighboring wall
+then it can go in 2 directions, else it can go in 3 directions. So these
+4 leaves will expand to $4(1 + 2 \times 2 + 3) = 32$ new leaves at the 3rd
+level of the tree.
+
+
+\end{enumerate}
+
+\end{enumerate}
+\end{document}
diff --git a/prog2/.prog2.cpp.swp b/prog2/.prog2.cpp.swp
new file mode 100644
index 0000000..db142f2
Binary files /dev/null and b/prog2/.prog2.cpp.swp differ
diff --git a/prog2/a.out b/prog2/a.out
new file mode 100755
index 0000000..df51b6c
Binary files /dev/null and b/prog2/a.out differ
diff --git a/prog2/prog2.cpp b/prog2/prog2.cpp
new file mode 100644
index 0000000..7f53333
--- /dev/null
+++ b/prog2/prog2.cpp
@@ -0,0 +1,210 @@
+/*
+For algorithms A* and RBFS
+ For each heuristic function h,
+ For at least 4 different sizes (number of disks)
+ For each of the 20 problems p,
+ Solve p using h or until NMAX nodes are expanded.
+ Record the solution length if successful, the number of nodes
+ expanded, and the total CPU time spent on evaluating
+ the heuristic and on solving the whole problem.
+*/
+
+#include <iostream>
+#include <vector>
+#include <stack>
+#include <cstdlib>
+#include <algorithm>
+
+using namespace std;
+
+const bool A_STAR = true;
+const bool RBFS = false;
+const bool ADMISSIBLE = true;
+const bool NONADMISSIBLE = false;
+const int M = 3;
+const int NODEMAX = 1000000;
+
+void display(vector< string > p) {
+ int max_plates = 0;
+ int i;
+ for(i = 0; i < p.size(); ++i) {
+ if(p[i].size() > max_plates)
+ max_plates = p[i].size();
+ }
+ for(i = max_plates - 1; i >= 0; --i) {
+ for(int ii = 0; ii < p.size(); ++ii) {
+ if(p[ii].size() > i) {
+ for(int iii = atoi(&p[ii][p[ii].size()-1]); iii > 0; --iii)
+ cout << '-';
+ p[ii].erase(p[ii].size()-1, 1);
+ }
+ cout << "\t\t";
+ }
+ cout << '\n';
+ }
+}
+
+class Node {
+ public:
+ Node* parent;
+ vector<string> state;
+ int g;
+ int f;
+
+ Node() {}
+ Node(Node* p, int m, string initial, int gcost, bool heuristic) {
+ parent = p;
+ state.resize(m);
+ state[0] = initial;
+ g = gcost;
+ f = g + evaluate(heuristic);
+ }
+
+ bool operator<(Node &other) {
+ return f > other.f;
+ }
+
+ //TODO
+ int evaluate(bool heuristic) {
+ if(heuristic == ADMISSIBLE) {
+ return 1;
+ }
+ else if(heuristic == NONADMISSIBLE) {
+ return 1;
+ }
+ }
+};
+
+class Search {
+ int n;
+ bool heur;
+ int expanded;
+
+ public:
+ Node astar(Node root) {
+ vector<Node> frontier;
+ vector< vector<string> > explored;
+ frontier.push_back(root);
+ Node cur;
+ char c;
+ vector<string> child;
+ bool is_in_frontier_explored;
+ while(1) {
+ if(frontier.empty()) {
+ Node temp(NULL,0,"",0,0);
+ return temp;
+ }
+ pop_heap(frontier.begin(), frontier.end());
+ cur = frontier[frontier.size()-1];
+ frontier.pop_back();
+
+ //DEBUG BEGIN
+ system("clear");
+ display(cur.state);
+ cout << endl << "Press enter to continue";
+ char blah;
+ cin >> blah;
+ //DEBUG END
+
+ if(goaltest(cur))
+ cout << endl << "SOLUTION FOUND"; //DEBUG
+ return cur;
+ explored.push_back(cur.state);
+
+ for(int i = 0; i < cur.state.size(); ++i) {
+ for(int ii = 0; ii < cur.state.size(); ++ii) {
+ if( (i != ii) && (!cur.state[i].empty()) ) {
+ Node child;
+ for(int iii = 0; iii < cur.state.size(); ++iii) {
+ child.state.push_back(cur.state[iii]);
+ }
+ child.parent = &cur;
+ child.g = cur.g + 1;
+ child.f = child.evaluate(heur) + child.g;
+
+ c = child.state[i][child.state[i].size()-1];
+ child.state[i].erase(child.state[i].size()-1,1);
+ child.state[ii].push_back(c);
+
+ is_in_frontier_explored = false;
+ for(int i = 0; i < frontier.size(); ++i) {
+ if(equal(child.state.begin(),child.state.end(),frontier[i].state.begin())) {
+ is_in_frontier_explored = true;
+ if(child.f < frontier[i].f) {
+ frontier[i] = child;
+ }
+ }
+ }
+ for(int iii = 0; iii < explored.size(); ++iii) {
+ if(equal(child.state.begin(),child.state.end(),explored[iii].begin())) {
+ is_in_frontier_explored = true;
+ break;
+ }
+ }
+ if(!is_in_frontier_explored) {
+ frontier.push_back(child);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Node rbfs(Node node) {
+
+ }
+
+ Search(string initial, bool search, bool heuristic) {
+ expanded = 0;
+ n = initial.size();
+ heur = heuristic;
+ Node* root = new Node(NULL, M, initial, 0, heuristic);
+ Node solution;
+
+ if(search == A_STAR)
+ solution = astar(*root);
+ else if(search == RBFS)
+ solution = rbfs(*root);
+
+ if(solution.state.empty()) {
+ cout << endl << "FAILURE" << endl;
+ }
+ else {
+ stack<Node*> solution_path;
+ Node* cur = &solution;
+ while(cur != NULL) {
+ solution_path.push(cur);
+ cur = cur->parent;
+ }
+ while(!solution_path.empty()) {
+ //DEBUG BEGIN
+ system("clear");
+ display(solution_path.top()->state);
+ solution_path.pop();
+ cout << endl << "Press enter to continue";
+ char blah;
+ cin >> blah;
+ //DEBUG END
+ }
+ }
+ }
+
+ bool goaltest(Node node) {
+ if(node.state[0].size() == n) {
+ for(int i = 0; i < n; ++i) {
+ if(atoi(&node.state[0][i]) != n-i) return false;
+ }
+ return true;
+ }
+ return false;
+ }
+};
+
+struct SearchTree {
+ Node* root;
+};
+
+int main() {
+ string test = "123";
+ Search* a = new Search(test, A_STAR, ADMISSIBLE);
+}
|
andermic/CS531
|
42e0387df76f3402b9b37bb3b3524d6413fc433a
|
Added the description for project 1
|
diff --git a/prog1/prog1_description.html b/prog1/prog1_description.html
new file mode 100644
index 0000000..f3ecf01
--- /dev/null
+++ b/prog1/prog1_description.html
@@ -0,0 +1,90 @@
+<title> CS531 Programming Assignment 1 </title>
+<center>
+<H1> CS531 Programming Assignment 1 </H1>
+<H2> Vacuum-Cleaning Agents </H2>
+<H2> Due: Oct 12'th, 8:30 AM </H2>
+</center>
+<p> In this assignment you will design and implement 3 different
+vacuum-cleaning agents. You can do this and other programming
+assignments in teams of 2 students. You can use any programming language.
+</p>
+
+<p> The vacuum cleaner environment
+consists of n X m empty rectangular room, where each square has a p% chance
+of containing dirt. There are 3 percepts: a wall sensor = 1 if the machine
+has a wall right in the front and 0 otherwise, a dirt sensor = 1 if the
+square contains dirt, and a home sensor = 1 if the agent is home (the starting
+location). Five actions are available: go forward, turn right by 90 degrees,
+turn left by 90 degrees, suck
+up dirt, and turn off. The agent always starts in the bottom leftmost corner
+oriented upwards. It is evaluated by
+the total number of clean cells as a function of
+the number of actions taken. (Plot the number of clean cells
+vs. the number of actions taken).
+
+Design and implement three different agents and experiment with
+m=n=10 and p=100%. The three agents are listed as follows. In each case, the
+agent program should be organized as a list of if-then rules. The first rule
+whose condition evaluates to TRUE will ``fire,'' which means the corresponding
+action is executed. If the agent program is deterministic then there is only
+one action. If it is stochastic, then there are several actions, and
+each action will be chosen with some probability. For example,
+the rule "if wall then turn-left 0.5 turn-right 0.5" will choose turn-left
+and turn-right with equal probability if the wall sensor is ON.
+
+<ol>
+<li> A simple memoryless deterministic reflex agent.
+<li> A randomized reflex agent that can choose
+ actions randomly based on sensor readings.
+<li> A deterministic reflex agent with a small amount (2 to 3 bits) of memory.
+When executing each action, the agent simultanesouly sets or resets these
+bits according to how you specify. It checks all these bits while
+simultaneously sensing all the other percepts.
+</ol>
+
+For the random agent, repeat the experiment 50 times and plot the average
+performance over the 50 runs. For other agents, one run each would do.
+Write a brief report (3-5 pages). Your report should look like a
+research paper with abstract, introduction (a summary of the goals and
+results), formal description of the agents in some rule-like notation,
+experimental setup, results with 3 plots, and the discussion. You should
+include answers to the following questions in your papers. Please
+feel free to add any other important observations as well.
+
+<ol>
+<li> Describe the idea behind the design of each of your agents. Use diagrams
+and english as appropriate.
+
+<li> Describe all your agents as if-then rules.
+
+<li> What is the best possible performance achievable by any memory-less
+reflex agent in this domain? What prevents a memory-less
+reflex agent from doing very well in this task?
+
+<li> How well does the random agent perform? Do you think that this is
+the best possible performance achievable by any random agent? Why or
+why not? Give a table showing the number of
+actions it took to clean 90% of the room for each trial. What is the
+average of these numbers for the best 45 trials?
+What are the costs and benefits of randomness in agent design?
+
+<li> How does the memory-based deterministic agent perform compared
+to the random agent? Was it able to completely clean the room? Was it
+able to shut itself off after it is done? If it did, how many actions
+did it take to do this? Can the agent be improved any further with more
+memory than you used? Why or why not?
+
+<li> What did you learn from this experiment? Were you surprised
+by anything?
+</ol>
+
+<p> <b> Note: </b> You are not required to build any graphical user
+interface for this program. <br>
+
+<p> Submit the source code using the
+<A href="http://engr.oregonstate.edu/teach">
+ENGR assignment submission system</A>. Click "Login to ENGR". Login,
+and click the "Submit an Assignment" button.
+
+Submit the report (hard copy) in the class on the due date. </H2>
+<hr>
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
b30257dc13e8f9d0077f146634ed0b4c18c22599
|
A bit more on donations, not sure where this is at to be honest......
|
diff --git a/app/views/donations/new.html.haml b/app/views/donations/new.html.haml
index 7a731da..7041ddb 100644
--- a/app/views/donations/new.html.haml
+++ b/app/views/donations/new.html.haml
@@ -1,194 +1,194 @@
#search_results
= render :partial => 'actions/action', :locals => {:action => @action}
.donations
%h2 Donate Now
- form_for @donation do |f|
%p
I want to contribute: $
= f.text_field :amount, :size => 5, :maxlength => 10
= '.00 USD'
%span ($10 USD minimum)
%p{ :style => "margin-top:15px" }
%strong
Please share with this charity:
%table{ :style => "border-collapse:collapse;" }
%tr
%td
= f.radio_button :disclosure, 'ProvideAll'
%label{ :for => "donation_disclosure_provideall" }
My full contact information
%tr
%td
= f.radio_button :disclosure, 'ProvideNameAndEmailOnly'
%label{ :for => "donation_disclosure_providenameandemailonly" }
My name and email address only
%tr
%td
= f.radio_button :disclosure, 'Anonymous'
%label{ :for => "donation_disclosure_anonymous" }
None of my personal information (anonymous)
%br/
%p{ :style => "margin-left:0px;padding-left:0px" }
%strong
Billing Information
%p
= required_image
indicates required
%table{ :cellpadding => "3" }
%tr
%td{ :colspan => "2" }
%br/
%p
%em
Credit Card Billing Information
- - fields_for @donation.donor do |d|
+ - fields_for @donor do |d|
%tr
%td{ :align => "right" }
= required_image
First Name:
%td
= d.text_field :first_name, :size => 20, :maxlength => 25
%tr
%td{ :align => "right" }
= required_image
Last Name:
%td
= d.text_field :last_name, :size => 20, :maxlength => 25
%tr
%td{ :align => "right" }
= required_image
Address 1:
%td
= d.text_field :address1, :size => 30, :maxlength => 100
%tr
%td{ :align => "right" }
Address 2:
%td
= d.text_field :address2, :size => 30, :maxlength => 100
%tr
%td{ :align => "right" }
= required_image
City:
%td
= d.text_field :city, :size => 20, :maxlength => 30
%tr
%td{ :align => "right" }
= required_image
State:
%td
= d.select :state, states_for_select
%tr
%td{ :align => "right" }
= required_image
ZIP Code:
%td
= d.text_field :size => 10, :maxlength => 10
%tr
%td{ :align => "right" }
= required_image
Phone:
%td
%span
(
= d.text_field :phone_1, :size => 3, :maxlength => 3
%span
)
= d.text_field :phone_2, :size => 3, :maxlength => 3
= 'â'
= d.text_field :phone_3, :size => 4, :maxlength => 4
%tr
%td{ :align => "right" }
= required_image
E-mail Address:
%td
= d.text_field :email, :size => 30, :maxlength => 100
%tr
%td{ :align => "right" }
CC E-mail Address:
%td
= d.text_field :cc_email, :size => 30, :maxlength => 100
- fields_for @credit_card do |c|
%tr
Start Payment Method
%td{ :colspan => "2" }
%br/
%p
%em
Payment Method
%tr
%td{ :align => "right" }
= required_image
Name on Card:
%td
= c.text_field :name, :size => 25, :maxlength => 100, :autocomplete => 'off'
%tr
%td{ :align => "right" }
= required_image
Type of Card:
%td.tSmall
= c.select :type, card_types_for_select
%tr
%td{ :align => "right" }
= required_image
Card Number:
%td
= c.text_field :number, :size => 16, :maxlength => 16, :autocomplete => 'off'
%span
(No dashes or spaces)
%tr
%td{ :align => "right" }
= required_image
CSC/CVV2:
%td
= c.text_field :csc, :size => 6, :maxlength => 4, :autocomplete => 'off'
%tr
%td{ :nowrap => "", :align => "right" }
= required_image
Expiration Date:
%td
= c.date_select :expiry_date, :discard_day => true, :start_year => Time.now.year, :order => [:month, :year]
%br/
%p{ :style => "margin-left:0px;padding-left:0px" }
%strong
Choose a Fee Option
%table#theTemplate__ctl10_rblFeeOption{ :border => "0" }
%tr
%td
= f.radio_button :fee_option, 'add'
%label{ :for => "donation_disclosure_add" }
Add the 4.75% processing fee to my donation so that 100% of my donation goes to my charity(ies).
%tr
%td
= f.radio_button :fee_option, 'deduct'
%label{ :for => "donation_disclosure_deduct" }
Deduct the 4.75% processing fee from the donation amount forwarded to my charity(ies).
%br/
%p
%a{ :href => "nfg_step3.html" }
%img{ :src => "btn_donate_now.gif", :border => "0" }/
%p{ :style => "text-align:right;" }
%img{ :src => "powered_by_networkforgood.jpg", :height => "35", :alt => "Powered by NetworkforGood", :width => "160" }/
%a.action-url{ :href => "http://www.networkforgood.org/pca/Badge.aspx?BadgeId=111783" }
http://www.networkforgood.org/pca/Badge.aspx?BadgeId=111783
diff --git a/vendor/plugins/haml/init.rb b/vendor/plugins/haml/init.rb
index 142726c..d0c8798 100644
--- a/vendor/plugins/haml/init.rb
+++ b/vendor/plugins/haml/init.rb
@@ -1,2 +1,7 @@
-require 'haml'
+begin
+ require File.join(File.dirname(__FILE__), 'lib', 'haml') # From here
+rescue LoadError
+ require 'haml' # From gem
+end
+
Haml.init_rails(binding)
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
c65dfea320d7ec9f1d0ccf80e7cad68fb50328ce
|
Basic donations structure in place, and starting to get the view form working
|
diff --git a/app/controllers/donations_controller.rb b/app/controllers/donations_controller.rb
new file mode 100644
index 0000000..4647744
--- /dev/null
+++ b/app/controllers/donations_controller.rb
@@ -0,0 +1,45 @@
+class DonationsController < ApplicationController
+
+ # ssl_required :new, :create
+ # filter_parameter_logging :cardNumber
+
+ before_filter :load_action
+
+
+ def new
+ @donation = Donation.new
+ @donor = Donor.new
+ @credit_card = CreditCard.new
+ end
+
+ def create
+ # @donation = Donation.new(params[:donation])
+ # @donation.designation = current_project.name
+ # @donation.partnerTransactionIdentifier = "#{current_project.id}_#{current_user.id || ''}_#{Time.now.to_i}"
+ # @donation.designation = current_project.name
+ # @donation.npoEin = current_project.ein
+ # @donation.donorIpAddress = request.remote_ip
+ # if @donation.valid? && @donation.process
+ # @measurement = Measurement.create!(
+ # :user_id => current_user.id,
+ # :project_id => current_project.id,
+ # :metric_id => Metric.donation_metric.id,
+ # :quantity => @donation.amount
+ # )
+ # flash[:notice] = "The transaction was completed successfully. Thank you for your donation."
+ # redirect_to project_path(current_project)
+ # else
+ # flash[:error] = "There was an error while processing your donation: #{@donation.error_message}" if [email protected]_message.empty?
+ # render :action => 'new'
+ # end
+ end
+
+protected
+
+ def load_action
+ @action = Action.find(params[:social_action])
+ rescue ActiveRecord::RecordNotFound
+ redirect_to :back
+ end
+
+end
diff --git a/app/helpers/donations_helper.rb b/app/helpers/donations_helper.rb
new file mode 100644
index 0000000..69426d0
--- /dev/null
+++ b/app/helpers/donations_helper.rb
@@ -0,0 +1,84 @@
+module DonationsHelper
+ def required_image
+ image_tag 'required.gif', :height => 15, :hspace => 3, :align => "texttop", :alt => "required", :width => 5
+ end
+
+ def card_types_for_select
+ types = ActiveSupport::OrderedHash.new
+ types['Visa'] = 'Visa'
+ types['MasterCard'] = 'Mastercard'
+ types['American Express'] = 'Amex'
+ types['Discover'] = 'Discover'
+ types
+ end
+
+ def states_for_select
+ states = ActiveSupport::OrderedHash.new
+ states['Select State' ] = ''
+ states['------' ] = ''
+ states['Armed Forces of the Americas' ] = 'AA'
+ states['Armed Forces Europe' ] = 'AE'
+ states['Armed Forces Pacific' ] = 'AP'
+ states[ '-----' ] = ''
+ states['Alabama' ] = 'AL'
+ states['Alaska' ] = 'AK'
+ states['American Samoa' ] = 'AS'
+ states['Arizona' ] = 'AZ'
+ states['Arkansas' ] = 'AR'
+ states['California' ] = 'CA'
+ states['Colorado' ] = 'CO'
+ states['Connecticut' ] = 'CT'
+ states['Delaware' ] = 'DE'
+ states['District of Columbia' ] = 'DC'
+ states['Federated States of Micronesia'] = 'FM'
+ states['Florida' ] = 'FL'
+ states['Georgia' ] = 'GA'
+ states['Guam' ] = 'GU'
+ states['Hawaii' ] = 'HI'
+ states['Idaho' ] = 'ID'
+ states['Illinois' ] = 'IL'
+ states['Indiana' ] = 'IN'
+ states['Iowa' ] = 'IA'
+ states['Kansas' ] = 'KS'
+ states['Kentucky' ] = 'KY'
+ states['Louisiana' ] = 'LA'
+ states['Maine' ] = 'ME'
+ states['Marshall Islands' ] = 'MH'
+ states['Maryland' ] = 'MD'
+ states['Massachusetts' ] = 'MA'
+ states['Michigan' ] = 'MI'
+ states['Minnesota' ] = 'MN'
+ states['Mississippi' ] = 'MS'
+ states['Missouri' ] = 'MO'
+ states['Montana' ] = 'MT'
+ states['Nebraska' ] = 'NE'
+ states['Nevada' ] = 'NV'
+ states['New Hampshire' ] = 'NH'
+ states['New Jersey' ] = 'NJ'
+ states['New Mexico' ] = 'NM'
+ states['New York' ] = 'NY'
+ states['North Carolina' ] = 'NC'
+ states['North Dakota' ] = 'ND'
+ states['Northern Mariana Islands' ] = 'MP'
+ states['Ohio' ] = 'OH'
+ states['Oklahoma' ] = 'OK'
+ states['Oregon' ] = 'OR'
+ states['Palau' ] = 'PW'
+ states['Pennsylvania' ] = 'PA'
+ states['Puerto Rico' ] = 'PR'
+ states['Rhode Island' ] = 'RI'
+ states['South Carolina' ] = 'SC'
+ states['South Dakota' ] = 'SD'
+ states['Tennessee' ] = 'TN'
+ states['Texas' ] = 'TX'
+ states['Utah' ] = 'UT'
+ states['Vermont' ] = 'VT'
+ states['Virgin Islands' ] = 'VI'
+ states['Virginia' ] = 'VA'
+ states['Washington' ] = 'WA'
+ states['West Virginia' ] = 'WV'
+ states['Wisconsin' ] = 'WI'
+ states['Wyoming' ] = 'WY'
+ states
+ end
+end
diff --git a/app/models/action.rb b/app/models/action.rb
index 27d121e..a4c66cb 100644
--- a/app/models/action.rb
+++ b/app/models/action.rb
@@ -1,88 +1,89 @@
class Action < ActiveRecord::Base
include GeoKit::Geocoders
belongs_to :feed
belongs_to :site
+ has_many :donations
acts_as_taggable
acts_as_mappable :lat_column_name => :latitude, :lng_column_name => :longitude
before_save :look_for_tags, :look_for_location, :geocode_lookup, :denormalize
def update_from_feed_item(item)
puts " -- Action: #{item.title}"
self.title = item.title
self.url = item.link
self.description = description_for(item)
self.created_at = item.pubDate if item.pubDate
self.created_at = item.dc_date if item.dc_date
self.created_at = item.updated if item.updated
figure_out_address_from(item)
end
def description=(new_description)
write_attribute(:description, fix_quoted_html(new_description))
end
# Seems like Atom uses <content> not <description> ??
def description_for(item)
if item.description
item.description
elsif item.content
item.content
else
""
end
end
def self.per_page
10
end
protected
def fix_quoted_html(text)
text.gsub(/\</, '<').gsub(/\>/, '>')
end
def look_for_location
if feed.location_finder and self.description
match = self.description.match(feed.location_finder.to_s)
self.location = match[1] if match and match[1]
puts " Found Location: #{self.location}"
end
end
def look_for_tags
if feed.tag_finder and description
match = description.match(feed.tag_finder.to_s)
self.tag_list = match[1] if match and match[1]
puts " Found Tags: #{self.tag_list}"
end
end
def figure_out_address_from(item)
if item.geo_lat and item.geo_long
self.latitude = item.geo_lat
self.longitude = item.geo_long
end
end
def geocode_lookup
unless location.nil? or location.empty?
result = MultiGeocoder.geocode(location)
if result.success
self.latitude = result.lat
self.longitude = result.lng
puts " Geocoding Successful - #{result}"
end
end
end
def denormalize
self.site_id = self.feed.site_id
self.action_type = self.feed.action_type
end
end
diff --git a/app/models/credit_card.rb b/app/models/credit_card.rb
new file mode 100644
index 0000000..c0c4605
--- /dev/null
+++ b/app/models/credit_card.rb
@@ -0,0 +1,22 @@
+class CreditCard < ActiveRecord::Base
+ # Stuff to make this a database-less model
+ def self.columns() @columns ||= []; end
+ def self.column(name, sql_type = nil, default = nil, null = true)
+ columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
+ end
+
+ column :donation_id, :integer
+ column :type, :string
+ column :name, :string
+ column :number, :string
+ column :expiry_date, :integer
+ column :csc, :integer
+
+ validates_presence_of :type
+ validates_presence_of :name
+ validates_presence_of :number
+ validates_presence_of :expiry_month
+ validates_presence_of :expiry_year
+ validates_presence_of :csc
+
+end
diff --git a/app/models/donation.rb b/app/models/donation.rb
new file mode 100644
index 0000000..e730cd1
--- /dev/null
+++ b/app/models/donation.rb
@@ -0,0 +1,9 @@
+class Donation < ActiveRecord::Base
+ belongs_to :action
+ has_one :donor
+ has_one :credit_card
+
+ validates_presence_of :amount
+ validates_numericality_of :amount
+
+end
diff --git a/app/models/donor.rb b/app/models/donor.rb
new file mode 100644
index 0000000..427b2e6
--- /dev/null
+++ b/app/models/donor.rb
@@ -0,0 +1,17 @@
+class Donor < ActiveRecord::Base
+
+ belongs_to :donation
+
+ validates_presence_of :ip_address
+ validates_presence_of :first_name
+ validates_presence_of :last_name
+ validates_presence_of :email
+ validates_presence_of :address1
+ validates_presence_of :city
+ validates_presence_of :state
+ validates_presence_of :zip
+ validates_presence_of :phone
+
+ attr_accessor :phone_1, :phone_2, :phone_3
+
+end
diff --git a/app/views/actions/_action.html.haml b/app/views/actions/_action.html.haml
index a402ab9..0a2ddaa 100644
--- a/app/views/actions/_action.html.haml
+++ b/app/views/actions/_action.html.haml
@@ -1,29 +1,33 @@
%div[action]
= link_to action.title, action_path(action), :class => 'action-title', :rel => 'facebox'
.action-source
.action-byline= "Created on #{link_to action.site.name, action.site.url} by TODO"
.action-created= action.created_at.to_s(:default)
.action-type= "#{action.action_type} "
%span{:class => 'action-goal'}
%strong
Goal:
Coming Soon...
%br/
%span{:class => 'action-location'}
%strong
Location:
- unless action.location.nil? or action.location.empty?
= action.location
- else
Location unknown
%br/
%span{:class => 'action-tags'}
%strong
Tags:
= tag_list_for action
%br/
.action-description
= shorten_and_clean(action.description)
+ - if action.feed.donations?
+ .donations
+ = link_to image_tag('btn_donate_now.gif'), new_donation_path(:social_action => action.id)
+
= link_to action.url, action.url, :class => 'action-url'
diff --git a/app/views/donations/new.html.haml b/app/views/donations/new.html.haml
new file mode 100644
index 0000000..7a731da
--- /dev/null
+++ b/app/views/donations/new.html.haml
@@ -0,0 +1,194 @@
+#search_results
+ = render :partial => 'actions/action', :locals => {:action => @action}
+
+
+ .donations
+ %h2 Donate Now
+
+ - form_for @donation do |f|
+ %p
+ I want to contribute: $
+ = f.text_field :amount, :size => 5, :maxlength => 10
+ = '.00 USD'
+ %span ($10 USD minimum)
+
+ %p{ :style => "margin-top:15px" }
+ %strong
+ Please share with this charity:
+ %table{ :style => "border-collapse:collapse;" }
+ %tr
+ %td
+ = f.radio_button :disclosure, 'ProvideAll'
+ %label{ :for => "donation_disclosure_provideall" }
+ My full contact information
+ %tr
+ %td
+ = f.radio_button :disclosure, 'ProvideNameAndEmailOnly'
+ %label{ :for => "donation_disclosure_providenameandemailonly" }
+ My name and email address only
+ %tr
+ %td
+ = f.radio_button :disclosure, 'Anonymous'
+ %label{ :for => "donation_disclosure_anonymous" }
+ None of my personal information (anonymous)
+
+ %br/
+ %p{ :style => "margin-left:0px;padding-left:0px" }
+ %strong
+ Billing Information
+ %p
+ = required_image
+ indicates required
+
+
+ %table{ :cellpadding => "3" }
+ %tr
+ %td{ :colspan => "2" }
+ %br/
+ %p
+ %em
+ Credit Card Billing Information
+
+ - fields_for @donation.donor do |d|
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ First Name:
+ %td
+ = d.text_field :first_name, :size => 20, :maxlength => 25
+
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ Last Name:
+ %td
+ = d.text_field :last_name, :size => 20, :maxlength => 25
+
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ Address 1:
+ %td
+ = d.text_field :address1, :size => 30, :maxlength => 100
+
+ %tr
+ %td{ :align => "right" }
+ Address 2:
+ %td
+ = d.text_field :address2, :size => 30, :maxlength => 100
+
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ City:
+ %td
+ = d.text_field :city, :size => 20, :maxlength => 30
+
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ State:
+ %td
+ = d.select :state, states_for_select
+
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ ZIP Code:
+ %td
+ = d.text_field :size => 10, :maxlength => 10
+
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ Phone:
+ %td
+ %span
+ (
+ = d.text_field :phone_1, :size => 3, :maxlength => 3
+ %span
+ )
+ = d.text_field :phone_2, :size => 3, :maxlength => 3
+ = 'â'
+ = d.text_field :phone_3, :size => 4, :maxlength => 4
+
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ E-mail Address:
+ %td
+ = d.text_field :email, :size => 30, :maxlength => 100
+
+ %tr
+ %td{ :align => "right" }
+ CC E-mail Address:
+ %td
+ = d.text_field :cc_email, :size => 30, :maxlength => 100
+
+ - fields_for @credit_card do |c|
+ %tr
+ Start Payment Method
+ %td{ :colspan => "2" }
+ %br/
+ %p
+ %em
+ Payment Method
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ Name on Card:
+ %td
+ = c.text_field :name, :size => 25, :maxlength => 100, :autocomplete => 'off'
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ Type of Card:
+ %td.tSmall
+ = c.select :type, card_types_for_select
+
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ Card Number:
+ %td
+ = c.text_field :number, :size => 16, :maxlength => 16, :autocomplete => 'off'
+ %span
+ (No dashes or spaces)
+
+ %tr
+ %td{ :align => "right" }
+ = required_image
+ CSC/CVV2:
+ %td
+ = c.text_field :csc, :size => 6, :maxlength => 4, :autocomplete => 'off'
+
+ %tr
+ %td{ :nowrap => "", :align => "right" }
+ = required_image
+ Expiration Date:
+ %td
+ = c.date_select :expiry_date, :discard_day => true, :start_year => Time.now.year, :order => [:month, :year]
+
+ %br/
+ %p{ :style => "margin-left:0px;padding-left:0px" }
+ %strong
+ Choose a Fee Option
+ %table#theTemplate__ctl10_rblFeeOption{ :border => "0" }
+ %tr
+ %td
+ = f.radio_button :fee_option, 'add'
+ %label{ :for => "donation_disclosure_add" }
+ Add the 4.75% processing fee to my donation so that 100% of my donation goes to my charity(ies).
+ %tr
+ %td
+ = f.radio_button :fee_option, 'deduct'
+ %label{ :for => "donation_disclosure_deduct" }
+ Deduct the 4.75% processing fee from the donation amount forwarded to my charity(ies).
+ %br/
+ %p
+ %a{ :href => "nfg_step3.html" }
+ %img{ :src => "btn_donate_now.gif", :border => "0" }/
+ %p{ :style => "text-align:right;" }
+ %img{ :src => "powered_by_networkforgood.jpg", :height => "35", :alt => "Powered by NetworkforGood", :width => "160" }/
+ %a.action-url{ :href => "http://www.networkforgood.org/pca/Badge.aspx?BadgeId=111783" }
+ http://www.networkforgood.org/pca/Badge.aspx?BadgeId=111783
diff --git a/config/routes.rb b/config/routes.rb
index 13c3e7b..8c98693 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,38 +1,38 @@
ActionController::Routing::Routes.draw do |map|
- map.resources :actions, :tags, :map
+ map.resources :actions, :tags, :map, :donations
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
map.random '/random', :controller => 'actions', :action => 'random'
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.connect '', :controller => 'actions', :action => 'index'
end
diff --git a/db/migrate/016_create_donations.rb b/db/migrate/016_create_donations.rb
new file mode 100644
index 0000000..3d0ad7e
--- /dev/null
+++ b/db/migrate/016_create_donations.rb
@@ -0,0 +1,19 @@
+class CreateDonations < ActiveRecord::Migration
+ def self.up
+ create_table :donations do |t|
+ t.integer :action_id
+ t.string :ein
+ t.string :designation
+ t.string :dedication
+ t.string :disclosure
+ t.string :amount
+ t.string :identifier
+ t.string :fee_option
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :donations
+ end
+end
diff --git a/db/migrate/017_create_donors.rb b/db/migrate/017_create_donors.rb
new file mode 100644
index 0000000..f43c464
--- /dev/null
+++ b/db/migrate/017_create_donors.rb
@@ -0,0 +1,23 @@
+class CreateDonors < ActiveRecord::Migration
+ def self.up
+ create_table :donors do |t|
+ t.integer :donation_id
+ t.string :ip_address
+ t.string :first_name
+ t.string :last_name
+ t.string :email
+ t.string :cc_email
+ t.string :address1
+ t.string :address2
+ t.string :city
+ t.string :state
+ t.string :zip
+ t.string :phone
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :donors
+ end
+end
diff --git a/db/migrate/018_add_donations_to_feed.rb b/db/migrate/018_add_donations_to_feed.rb
new file mode 100644
index 0000000..0cd8477
--- /dev/null
+++ b/db/migrate/018_add_donations_to_feed.rb
@@ -0,0 +1,9 @@
+class AddDonationsToFeed < ActiveRecord::Migration
+ def self.up
+ add_column :feeds, :donations, :boolean, :default => false, :null => false
+ end
+
+ def self.down
+ remove_column :feeds, :donations
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index fc41d04..cda230b 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,61 +1,92 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of ActiveRecord to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 15) do
+ActiveRecord::Schema.define(:version => 18) do
create_table "actions", :force => true do |t|
t.text "description"
t.string "url"
t.text "title"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "feed_id"
t.decimal "latitude", :precision => 15, :scale => 10
t.decimal "longitude", :precision => 15, :scale => 10
t.string "location"
t.integer "site_id"
t.string "action_type"
end
+ create_table "donations", :force => true do |t|
+ t.integer "action_id"
+ t.string "ein"
+ t.string "designation"
+ t.string "dedication"
+ t.string "disclosure"
+ t.string "amount"
+ t.string "identifier"
+ t.string "fee_option"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "donors", :force => true do |t|
+ t.integer "donation_id"
+ t.string "ip_address"
+ t.string "first_name"
+ t.string "last_name"
+ t.string "email"
+ t.string "cc_email"
+ t.string "address1"
+ t.string "address2"
+ t.string "city"
+ t.string "state"
+ t.string "zip"
+ t.string "phone"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
create_table "feeds", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "last_accessed"
t.datetime "created_at"
t.datetime "updated_at"
t.string "tag_finder"
t.integer "site_id"
t.string "location_finder"
t.string "action_type"
+ t.boolean "donations", :default => false, :null => false
end
create_table "sites", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type"], :name => "index_taggings_on_taggable_id_and_taggable_type"
create_table "tags", :force => true do |t|
t.string "name"
end
end
diff --git a/public/images/btn_donate_now.gif b/public/images/btn_donate_now.gif
new file mode 100644
index 0000000..79ec25b
Binary files /dev/null and b/public/images/btn_donate_now.gif differ
diff --git a/public/images/required.gif b/public/images/required.gif
new file mode 100644
index 0000000..8a4a880
Binary files /dev/null and b/public/images/required.gif differ
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index 03337d6..97a1624 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,175 +1,183 @@
body
:font-family Arial, Helvetica, sans-serif
a
:color #3366cc
:text-decoration none
h2
:margin 0px 0px 5px 0px
p
:margin 3px
:margin-top 5px
// Block Elements
#search_results, #tag_cloud, #facebox, #notice
:width 710px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 0px 10px
// Search box
#search_box
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:background-color #e9f3f1
:padding 10px 10px 30px 10px
table
td
:padding-right 5px
:padding-top 10px
.first
td
:padding-top 0
.platform_select
:width 170px
:float left
:margin-top 10px
// Results Elements
.action
:width 700px
:margin-bottom 30px
.action-title
:margin-top 5px
:margin-bottom 5px
:font-size 160%
:display block
.action-source
:width 250px
:float right
/:margin-left 25px
:text-align right
.action-goal
.action-location
.action-tags
.action-url
:margin-top 10px
:display block
:color #ff6600
.action-url a
.action-url a:hover
.action-byline
.action-byline a
:font-weight bold
.action-byline a:hover
.action-created
.action-type
:font-style italic
.action-description
:clear both
:margin-top 5px
+
+.donations
+ :margin-top 15px
+ :border 1px dashed #3366cc
+ :padding 10px
+ img
+ :border 0px
+
// Pagination
.pagination
:padding 3px
:margin 3px
.pagination a
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:text-decoration none
:color #3366cc
.pagination a:hover, .pagination a:active
:border 1px solid #3366cc
:color #000
.pagination span.current
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:font-weight bold
:background-color #3366cc
:color #FFF
.pagination span.disabled
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #eee
:color #ddd
// Map
#gmap
:height 400px
:width 710px
:margin-top 20px
.map-action
:font-size 12px
:width 200px
:border 1px red
:font-family Arial, Helvetica, sans-serif
.title
.location
:font-size 80%
.byline
:font-size 80%
.created
:font-size 80%
// Tags
.tag1
:font-size 1.0em
.tag2
:font-size 1.2em
.tag3
:font-size 1.4em
.tag4
:font-size 1.6em
// Facebox Popup
#facebox
.action-title
:color #3366cc
.description
:height 200px
:overflow auto
:clear both
// Header
#header
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 20px 10px
// Footer
#footer
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 20px 10px
diff --git a/spec/controllers/donations_controller_spec.rb b/spec/controllers/donations_controller_spec.rb
new file mode 100644
index 0000000..4231252
--- /dev/null
+++ b/spec/controllers/donations_controller_spec.rb
@@ -0,0 +1,10 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe DonationsController do
+
+ #Delete this example and add some real ones
+ it "should use DonationsController" do
+ controller.should be_an_instance_of(DonationsController)
+ end
+
+end
diff --git a/spec/fixtures/credit_cards.yml b/spec/fixtures/credit_cards.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/spec/fixtures/credit_cards.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/spec/fixtures/donations.yml b/spec/fixtures/donations.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/spec/fixtures/donations.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/spec/fixtures/donors.yml b/spec/fixtures/donors.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/spec/fixtures/donors.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index 6777e04..7e62fec 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,196 +1,219 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
action_type: Group Fundraiser
+ donations: false
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
action_type: Pledged Action
-
+ donations: false
+
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Group Fundraiser
+ donations: false
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Affinity Group
+ donations: false
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Pledged Action
+ donations: false
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Group Fundraiser
+ donations: false
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
action_type: Group Fundraiser
+ donations: false
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
location_finder:
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
action_type: Petition
+ donations: false
+
the_point:
name: ThePoint
url: http://www.thepoint.com/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: the_point
action_type: Pledged Action
+ donations: false
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
+ donations: false
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
+ donations: false
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
action_type: Group Fundraiser
+ donations: false
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
action_type: Group Fundraiser
+ donations: false
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
action_type: Group Fundraiser
+ donations: false
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
action_type: Micro-credit Loan
+ donations: false
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/data/BadgePromotionFeed.aspx?source=SIXDEG&cmpgn=SCB&type=RecentBadge
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
action_type: Group Fundraiser
+ donations: true
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
action_type: Group Fundraiser
+ donations: false
zazengo:
name: Latest Zazengo Projects
url: http://www.zazengo.com/projects.rss
tag_finder: "<span class=\"issues\">([\w\s,]+)</span>"
location_finder: "<span class=\"street-address\">([\w\s,]+)</span>"
last_accessed: <%= 1.day.ago %>
site: zazengo
action_type: Affinity Group
+ donations: false
helpalot:
name: Helpalot
url: http://www.helpalot.org/en/feed/projects/
tag_finder:
location_finder: "<br /><br />\n([\w\s,]+)\n<br />"
last_accessed: <%= 1.day.ago %>
site: helpalot
action_type: Affinity Group
+ donations: false
donorschoose:
name: DonorsChoose
url: http://www.donorschoose.org/common/rss_feed.html?zone=0&schoolType=0&partiallyFunded=true&teacherType=0&y=22&x=20
tag_finder:
location_finder: "<br />([\w\s,]+)<br />Level:"
last_accessed: <%= 1.day.ago %>
site: donorschoose
action_type: Group Fundraiser
+ donations: false
pincgiving:
name: PincGiving
url: http://www.pincgiving.com/feed/campaign
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pincgiving
action_type: Group Fundraiser
+ donations: false
microgiving:
name: MicroGiving
url: http://www.microgiving.com/feed-requested.php
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: microgiving
- action_type: Group Fundraiser
\ No newline at end of file
+ action_type: Group Fundraiser
+ donations: false
diff --git a/spec/helpers/donations_helper_spec.rb b/spec/helpers/donations_helper_spec.rb
new file mode 100644
index 0000000..26fff8a
--- /dev/null
+++ b/spec/helpers/donations_helper_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe DonationsHelper do
+
+ #Delete this example and add some real ones or delete this file
+ it "should include the DonationsHelper" do
+ included_modules = self.metaclass.send :included_modules
+ included_modules.should include(DonationsHelper)
+ end
+
+end
diff --git a/spec/models/credit_card_spec.rb b/spec/models/credit_card_spec.rb
new file mode 100644
index 0000000..a457808
--- /dev/null
+++ b/spec/models/credit_card_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe CreditCard do
+ before(:each) do
+ @credit_card = CreditCard.new
+ end
+
+ it "should be valid" do
+ @credit_card.should be_valid
+ end
+end
diff --git a/spec/models/donation_spec.rb b/spec/models/donation_spec.rb
new file mode 100644
index 0000000..16f6e50
--- /dev/null
+++ b/spec/models/donation_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe Donation do
+ before(:each) do
+ @donation = Donation.new
+ end
+
+ it "should be valid" do
+ @donation.should be_valid
+ end
+end
diff --git a/spec/models/donor_spec.rb b/spec/models/donor_spec.rb
new file mode 100644
index 0000000..c0c1cf3
--- /dev/null
+++ b/spec/models/donor_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe Donor do
+ before(:each) do
+ @donor = Donor.new
+ end
+
+ it "should be valid" do
+ @donor.should be_valid
+ end
+end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
eb631e16b9a8b7416c560e31749215df2d4f8fcc
|
Adding a file i missed a couple commits ago
|
diff --git a/app/views/actions/index.rss.builder b/app/views/actions/index.rss.builder
new file mode 100644
index 0000000..1d4a6d7
--- /dev/null
+++ b/app/views/actions/index.rss.builder
@@ -0,0 +1,29 @@
+xml.instruct! :xml, :version => "1.0"
+xml.rss :version => "2.0" do
+ xml.channel do
+ xml.title "Social Actions: Results for #{@search.to_s}"
+ xml.description "Results for #{@search.to_s} on http://mashup.socialactions.com"
+ xml.link feed_url
+
+ @actions.each do |action|
+ xml.item do
+ xml.title action.title
+ xml.category action.action_type
+ xml.description shorten_and_clean(action.description)
+ xml.pubDate action.created_at.strftime("%Y-%m-%dT%H:%M:%SZ")
+ xml.link action_url(action)
+ xml.guid action_url(action)
+ end
+ end
+
+ if @actions.empty?
+ xml.item do
+ xml.title 'There are no matching actions at this time.'
+ xml.description "type" => "html" do
+ xml.text! 'There are no matching actions at this time.'
+ end
+ end
+ end
+
+ end
+end
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
a5ae91aa19be17c2c1c731864f61c0b1e9e8420d
|
Adjustment to a feed URL
|
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index 75f7eca..6777e04 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,196 +1,196 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
action_type: Group Fundraiser
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
action_type: Pledged Action
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Group Fundraiser
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Affinity Group
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Pledged Action
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Group Fundraiser
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
action_type: Group Fundraiser
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
location_finder:
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
action_type: Petition
the_point:
name: ThePoint
url: http://www.thepoint.com/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: the_point
action_type: Pledged Action
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
action_type: Group Fundraiser
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
action_type: Group Fundraiser
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
action_type: Group Fundraiser
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
action_type: Micro-credit Loan
six_degrees:
name: SixDegrees
- url: http://www.networkforgood.org/pca/badgefeed.aspx
+ url: http://www.networkforgood.org/data/BadgePromotionFeed.aspx?source=SIXDEG&cmpgn=SCB&type=RecentBadge
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
action_type: Group Fundraiser
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
action_type: Group Fundraiser
zazengo:
name: Latest Zazengo Projects
url: http://www.zazengo.com/projects.rss
tag_finder: "<span class=\"issues\">([\w\s,]+)</span>"
location_finder: "<span class=\"street-address\">([\w\s,]+)</span>"
last_accessed: <%= 1.day.ago %>
site: zazengo
action_type: Affinity Group
helpalot:
name: Helpalot
url: http://www.helpalot.org/en/feed/projects/
tag_finder:
location_finder: "<br /><br />\n([\w\s,]+)\n<br />"
last_accessed: <%= 1.day.ago %>
site: helpalot
action_type: Affinity Group
donorschoose:
name: DonorsChoose
url: http://www.donorschoose.org/common/rss_feed.html?zone=0&schoolType=0&partiallyFunded=true&teacherType=0&y=22&x=20
tag_finder:
location_finder: "<br />([\w\s,]+)<br />Level:"
last_accessed: <%= 1.day.ago %>
site: donorschoose
action_type: Group Fundraiser
pincgiving:
name: PincGiving
url: http://www.pincgiving.com/feed/campaign
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pincgiving
action_type: Group Fundraiser
microgiving:
name: MicroGiving
url: http://www.microgiving.com/feed-requested.php
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: microgiving
action_type: Group Fundraiser
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
73dc53baa0233f6c49611c529aee2fc2fde5478f
|
First cut at getting RSS feeds of a search result. I should really be testing this (I know!!), but I am ad hoc testing right now
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index 18a5b9f..f649f17 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,31 +1,33 @@
class ActionsController < ApplicationController
def index
@search = Search.new(search_params)
@actions = @search.results(params[:page])
respond_to do |format|
format.html
- format.xml
+ format.xml { render :xml => @actions }
+ format.js { render :json => @actions }
+ format.rss { render :layout => false }
end
end
def random
@search = Search.new(search_params.merge(:kind => 'random'))
@actions = @search.results(params[:page])
if @actions.empty?
redirect_to(:back)
else
redirect_to(@actions.first.url)
end
end
def show
@action = Action.find(params[:id])
respond_to do |format|
format.html { render :layout => false}
format.xml
end
end
end
diff --git a/app/controllers/application.rb b/app/controllers/application.rb
index a87ce6a..54a2c87 100644
--- a/app/controllers/application.rb
+++ b/app/controllers/application.rb
@@ -1,15 +1,23 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery # :secret => '1a6bbb367383c24380852761da6c194f'
def search_params
- params.slice(:keywords, :action_type, :created, :sites, :kind, :ip_address)
+ params[:sites] = params[:sites].split(',') if (params[:sites].is_a? String)
+ params.slice(:keywords, :action_type, :created, :sites, :kind, :ip_address).delete_if{|k,v| v.nil? || v.empty?}
end
helper_method :search_params
+
+ def search_params_readable
+ params = search_params
+ params[:sites] = params[:sites].join(',') if (params[:sites] and params[:sites].is_a? Hash)
+ params
+ end
+ helper_method :search_params_readable
end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index f962d0f..29c0331 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,45 +1,49 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def map_loader
if [email protected]? && @gmap.onload
{:onload => @gmap.onload_func_name + '()', :onunload => 'GUnload'}
else
{}
end
end
def options_for_action_type_select
[
['All actions', "all"],
['Affinity Group'],
['Group Fundraiser'],
['Micro-credit Loan'],
['Petition'],
['Pledged Action']
]
end
def options_for_created_select
[
['Any Time', nil],
['Last 30 days', 30],
['Last 14 days',14],
['Last week', 7],
['Yesterday', 2],
['Today', 1]
]
end
def tag_list_for(action)
action.tags.collect do |tag|
link_to tag.name, tag_path(tag)
end.join(', ')
end
def shorten_and_clean(text)
output = strip_tags(text).to(200).split(' ')
output.pop
output.join(' ') + '...'
end
+ def feed_url
+ formatted_actions_url(:rss, search_params_readable).gsub('&', '&')
+ end
+
end
diff --git a/app/models/search.rb b/app/models/search.rb
index 4b9bec1..84d8ef8 100644
--- a/app/models/search.rb
+++ b/app/models/search.rb
@@ -1,114 +1,122 @@
class Search < ActiveRecord::BaseWithoutTable
column :keywords, :string
column :action_type, :string
column :created, :integer
attr_accessor :sites, :kind, :ip_address
validates_inclusion_of :created, :in => %w{ 30 14 7 2 1 }
def results(page)
if kind == 'map'
Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => build_conditions)
else
Action.paginate(:all, :page => page, :order => build_order, :conditions => build_conditions)
end
end
+
+ def to_s
+ output = []
+ output << "Keywords: #{keywords}" if keywords?
+ output << "Created: #{created}" if created?
+ output << "Action Type: #{action_type}" if action_type?
+ output.join(', ')
+ end
def build_conditions
reset_conditions
add_keywords
add_action_type
add_sites
add_created
add_mapping
conditions.join(' AND ')
end
def build_order
kind == 'random' ? 'RAND()' : 'created_at DESC'
end
def sites
@sites ||= []
end
def has_site?(site)
return true if sites.empty?
sites.include?(site.id.to_s)
end
def reset_conditions
@conditions = []
end
def conditions
@conditions ||= []
end
def add_keywords
unless keywords.nil? or keywords.empty?
keyword_conditions = []
keywords.split(' ').each do |keyword|
keyword_conditions << sanitize(["(description LIKE ? OR title LIKE ?)", "%#{keyword}%", "%#{keyword}%"])
end
conditions << "(" + keyword_conditions.join(' OR ') + ")"
end
end
def add_action_type
unless action_type.nil? or action_type == 'all'
conditions << "action_type = '#{action_type}'"
end
end
def add_sites
unless sites.nil? or sites.empty?
conditions << sanitize(["site_id IN (?)", sites])
end
end
def add_created
unless created.nil?
conditions << sanitize(["actions.created_at > ?", created.days.ago])
end
end
def add_mapping
if kind == 'map'
conditions << 'latitude IS NOT NULL and longitude IS NOT NULL'
end
end
def sanitize(arg)
ActiveRecord::Base.send(:sanitize_sql, arg)
end
def current_latitude
current_location.lat || 21.98
end
def current_longitude
current_location.lng || -10.00
end
def current_location
# debugger
@current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
end
def current_ip
ip_address == '127.0.0.1' ? '67.162.124.13' : ip_address
end
# def get_current_location
# location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
# unless location.lat.nil? and location.lng.nil?
# return location.lat, location.lng
# else
# return 41.98, -87.90 # Chicago, an estimate
# end
# end
end
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 51224ea..bc8f133 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,19 +1,20 @@
!!! 1.0
%html{"xmlns"=>"http://www.w3.org/1999/xhtml", "xml:lang"=>"en"}
%head
%meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}/
%title A Mashup of 29+ Social Action Platforms
+ %link{ :rel => 'alternate', :type => 'application/atom+xml', :title => "Social Actions: Results for #{@search.to_s}", :href => feed_url }
= stylesheet_link_tag 'main', 'facebox'
= javascript_include_tag 'jquery', 'facebox', 'application'
= yield :map_headers
%body{ map_loader }
- if params[:controller] == 'actions' and params[:action] == 'index' and search_params.nil?
= render :partial => 'layouts/main_header'
- else
= render :partial => 'layouts/header'
= yield
= render :partial => 'layouts/footer'
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
7181a4d1ed5c154b671ec4c5f57d29936173081d
|
Adjusting the search parameters to be cleaner.
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index c937095..18a5b9f 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,31 +1,31 @@
class ActionsController < ApplicationController
def index
- @search = Search.new(params[:search])
+ @search = Search.new(search_params)
@actions = @search.results(params[:page])
respond_to do |format|
format.html
format.xml
end
end
def random
- @search = Search.new(params[:search].merge(:kind => 'random'))
+ @search = Search.new(search_params.merge(:kind => 'random'))
@actions = @search.results(params[:page])
if @actions.empty?
redirect_to(:back)
else
redirect_to(@actions.first.url)
end
end
def show
@action = Action.find(params[:id])
respond_to do |format|
format.html { render :layout => false}
format.xml
end
end
end
diff --git a/app/controllers/application.rb b/app/controllers/application.rb
index ee1635d..a87ce6a 100644
--- a/app/controllers/application.rb
+++ b/app/controllers/application.rb
@@ -1,10 +1,15 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery # :secret => '1a6bbb367383c24380852761da6c194f'
+
+ def search_params
+ params.slice(:keywords, :action_type, :created, :sites, :kind, :ip_address)
+ end
+ helper_method :search_params
end
diff --git a/app/controllers/map_controller.rb b/app/controllers/map_controller.rb
index 94a85a4..09d6ca6 100644
--- a/app/controllers/map_controller.rb
+++ b/app/controllers/map_controller.rb
@@ -1,58 +1,58 @@
class MapController < ApplicationController
include ActionView::Helpers::JavaScriptHelper
def index
- @search = Search.new(params[:search])
+ @search = Search.new(search_params)
@search.kind = 'map'
@search.ip_address = request.remote_ip
@actions = @search.results(params[:page])
setup_map
@actions.each do |action|
# now for the lat and lng of the marker we want to add.
marker_lat = action.latitude
marker_lng = action.longitude
@gmap.use_marker_code('createWithIconAndHtml', :with_args => [:point, :html, :icon_image])
incident_point = Mappa::GLatLng.new(:lat => marker_lat, :lng => marker_lng)
@gmap.add_marker(:point => incident_point, :create_with => 'createWithIconAndHtml', :html => "'#{escape_javascript(small_map_view_of(action))}'", :icon_image => "'/images/marker.png'")
end
end
protected
def setup_map
@gmap = Mappa::GMap.new()
@gmap.api_key = 'ABQIAAAAkGYfBpkZ5yYF_f9sthqC5BTJQa0g3IQ9GZqIMmInSLzwtGDKaBRu7u3V_uePSTUgmfHvnGnehFX3-A'
# set the longitude and latitiude of the centre point of our map
@gmap.lat, @gmap.lng = @search.current_latitude, @search.current_longitude
# set the zoom level of our map. This number is in the range of 1-18. 1 is lowest zoom and 18 is highest
# we've picked a nice middling 12.
@gmap.zoom = 2
@gmap.add_control(:control => 'small')
@gmap.add_control(:control => 'type')
@gmap.add_control(:control => 'overview')
end
def small_map_view_of(action)
%{
<div class="map-action">
<div class="title">
<a href="#{action.url}" target="_blank">#{action.title}</a>
</div>
<div class="location">
<b>Location:</b> #{action.location}
</div>
<div class="byline">
<b>Created on:</b> <a href="#{action.site.url}" target="_blank">#{action.site.name}</a>
</div>
<div class="created">
<b>Created at:</b> #{action.created_at.to_s(:default)}
</div>
</div>
}
end
end
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb
index 63a5bfc..f9a4c5e 100644
--- a/app/controllers/tags_controller.rb
+++ b/app/controllers/tags_controller.rb
@@ -1,22 +1,22 @@
class TagsController < ApplicationController
before_filter :load_tags, :load_search
def index
end
def show
@tag = Tag.find_by_name(params[:id])
@actions = Action.paginate(:all, :page => params[:page], :include => 'taggings', :conditions => ['taggings.tag_id = ?', @tag.id], :order => 'actions.created_at DESC')
end
private
def load_tags
@tags = Action.tag_counts(:order => 'tags.name', :at_least => 2)
# :order - A piece of SQL to order by. Eg 'tags.count desc' or 'taggings.created_at desc'
end
def load_search
- @search = Search.new(params[:search])
+ @search = Search.new(search_params)
end
end
diff --git a/app/views/actions/_search_form.html.haml b/app/views/actions/_search_form.html.haml
index 19afb9d..310b960 100644
--- a/app/views/actions/_search_form.html.haml
+++ b/app/views/actions/_search_form.html.haml
@@ -1,33 +1,34 @@
#search_box
%h2 Find an Action
- form_for @search, :url => actions_path, :html => {:method => :get} do |f|
%table{ :border=>"0", :cellpadding=>"0", :cellspacing=>"0" }
%tr.first
%td Search Term:
- %td= f.text_field :keywords, :size => 22
+ %td= text_field_tag :keywords, @search.keywords, :size => 22
+
%td
= submit_tag 'Search'
= submit_tag 'Google Map', :onclick => "$('#new_search').attr('action', '#{map_index_path}')"
= submit_tag 'Tag Cloud', :onclick => "$('#new_search').attr('action', '#{tags_path}')"
= submit_tag 'Random', :onclick => "$('#new_search').attr('action', '#{random_path}')"
%tr
%td Type of Action:
- %td= f.select :action_type, options_for_action_type_select
+ %td= select_tag :action_type, options_for_select(options_for_action_type_select, @search.action_type)
%td
Created:
- = f.select :created, options_for_created_select
+ = select_tag :created, options_for_select(options_for_created_select, @search.created)
- Site.find(:all, :order => :name).each_slice(5) do |sites|
.platform_select
- sites.each do |site|
- = check_box_tag 'search[sites][]', site.id, @search.has_site?(site)
+ = check_box_tag 'sites[]', site.id, @search.has_site?(site)
= site.name
%br/
%br{:clear => 'all'}/
\ No newline at end of file
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 901f022..51224ea 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,19 +1,19 @@
!!! 1.0
%html{"xmlns"=>"http://www.w3.org/1999/xhtml", "xml:lang"=>"en"}
%head
%meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}/
%title A Mashup of 29+ Social Action Platforms
= stylesheet_link_tag 'main', 'facebox'
= javascript_include_tag 'jquery', 'facebox', 'application'
= yield :map_headers
%body{ map_loader }
- - if params[:controller] == 'actions' and params[:action] == 'index' and params[:search].nil?
+ - if params[:controller] == 'actions' and params[:action] == 'index' and search_params.nil?
= render :partial => 'layouts/main_header'
- else
= render :partial => 'layouts/header'
= yield
= render :partial => 'layouts/footer'
\ No newline at end of file
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index 3d86e5a..75f7eca 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,196 +1,196 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
action_type: Group Fundraiser
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
action_type: Pledged Action
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Group Fundraiser
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Affinity Group
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Pledged Action
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Group Fundraiser
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
action_type: Group Fundraiser
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
location_finder:
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
action_type: Petition
the_point:
name: ThePoint
url: http://www.thepoint.com/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: the_point
action_type: Pledged Action
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
action_type: Group Fundraiser
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
action_type: Group Fundraiser
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
action_type: Group Fundraiser
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
action_type: Micro-credit Loan
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/pca/badgefeed.aspx
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
action_type: Group Fundraiser
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
action_type: Group Fundraiser
zazengo:
name: Latest Zazengo Projects
url: http://www.zazengo.com/projects.rss
tag_finder: "<span class=\"issues\">([\w\s,]+)</span>"
location_finder: "<span class=\"street-address\">([\w\s,]+)</span>"
last_accessed: <%= 1.day.ago %>
site: zazengo
action_type: Affinity Group
helpalot:
name: Helpalot
url: http://www.helpalot.org/en/feed/projects/
tag_finder:
location_finder: "<br /><br />\n([\w\s,]+)\n<br />"
last_accessed: <%= 1.day.ago %>
site: helpalot
action_type: Affinity Group
donorschoose:
name: DonorsChoose
url: http://www.donorschoose.org/common/rss_feed.html?zone=0&schoolType=0&partiallyFunded=true&teacherType=0&y=22&x=20
tag_finder:
location_finder: "<br />([\w\s,]+)<br />Level:"
last_accessed: <%= 1.day.ago %>
site: donorschoose
action_type: Group Fundraiser
pincgiving:
name: PincGiving
url: http://www.pincgiving.com/feed/campaign
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pincgiving
action_type: Group Fundraiser
microgiving:
name: MicroGiving
url: http://www.microgiving.com/feed-requested.php
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: microgiving
- action_type: Group Fundraiser
\ No newline at end of file
+ action_type: Group Fundraiser
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
1282454c95eed13f388c7eb8ef01c24b77f5f98a
|
Adding in 2 new feeds and sites, MicroGiving, and PincGiving
|
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index e2d11f4..3d86e5a 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,178 +1,196 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
action_type: Group Fundraiser
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
action_type: Pledged Action
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Group Fundraiser
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Affinity Group
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Pledged Action
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Group Fundraiser
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
action_type: Group Fundraiser
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
location_finder:
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
action_type: Petition
the_point:
name: ThePoint
url: http://www.thepoint.com/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: the_point
action_type: Pledged Action
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
action_type: Group Fundraiser
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
action_type: Group Fundraiser
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
action_type: Group Fundraiser
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
action_type: Micro-credit Loan
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/pca/badgefeed.aspx
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
action_type: Group Fundraiser
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
action_type: Group Fundraiser
zazengo:
name: Latest Zazengo Projects
url: http://www.zazengo.com/projects.rss
tag_finder: "<span class=\"issues\">([\w\s,]+)</span>"
location_finder: "<span class=\"street-address\">([\w\s,]+)</span>"
last_accessed: <%= 1.day.ago %>
site: zazengo
action_type: Affinity Group
helpalot:
name: Helpalot
url: http://www.helpalot.org/en/feed/projects/
tag_finder:
location_finder: "<br /><br />\n([\w\s,]+)\n<br />"
last_accessed: <%= 1.day.ago %>
site: helpalot
action_type: Affinity Group
donorschoose:
name: DonorsChoose
url: http://www.donorschoose.org/common/rss_feed.html?zone=0&schoolType=0&partiallyFunded=true&teacherType=0&y=22&x=20
tag_finder:
location_finder: "<br />([\w\s,]+)<br />Level:"
last_accessed: <%= 1.day.ago %>
site: donorschoose
action_type: Group Fundraiser
+
+pincgiving:
+ name: PincGiving
+ url: http://www.pincgiving.com/feed/campaign
+ tag_finder:
+ location_finder:
+ last_accessed: <%= 1.day.ago %>
+ site: pincgiving
+ action_type: Group Fundraiser
+
+microgiving:
+ name: MicroGiving
+ url: http://www.microgiving.com/feed-requested.php
+ tag_finder:
+ location_finder:
+ last_accessed: <%= 1.day.ago %>
+ site: microgiving
+ action_type: Group Fundraiser
\ No newline at end of file
diff --git a/spec/fixtures/sites.yml b/spec/fixtures/sites.yml
index 4ad76c1..6c5d0ee 100644
--- a/spec/fixtures/sites.yml
+++ b/spec/fixtures/sites.yml
@@ -1,67 +1,75 @@
global_giving:
name: GlobalGiving
url: http://www.globalgiving.com
pledge_bank:
name: PledgeBank
url: http://www.pledgebank.com
change_org:
name: Change.org
url: http://www.change.org
razoo:
name: Razoo
url: http://beta.razoo.com
democracy_in_action:
name: DemocracyinAction
url: http://www.democracyinaction.org
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com
the_point:
name: ThePoint
url: http://www.thepoint.com
give_meaning:
name: GiveMeaning
url: http://www.givemeaning.com
changing_the_present:
name: ChangingthePresent
url: http://www.changingthepresent.com
fundable:
name: Fundable
url: http://www.fundable.org
bring_light:
name: BringLight
url: http://www.bringlight.com
kiva:
name: Kiva
url: http://www.kiva.org
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org
first_giving:
name: Firstgiving
url: http://www.firstgiving.com
zazengo:
name: Zazengo
url: http://www.zazengo.com
helpalot:
name: Helpalot
url: http://www.helpalot.com
donorschoose:
name: DonorsChoose
- url: http://www.donorschoose.org
\ No newline at end of file
+ url: http://www.donorschoose.org
+
+pincgiving:
+ name: PincGiving
+ url: http://www.pincgiving.com
+
+microgiving:
+ name: MicroGiving
+ url: http://www.microgiving.com
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
2a619a1d036a6c14480998fc9fbd43d0a858f7ef
|
Rescuing failing feeds on parse so it doesn't take down the whole parser
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index dd8f6e8..7d96864 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,26 +1,33 @@
require 'rubygems'
require 'simple-rss'
require 'open-uri'
class Feed < ActiveRecord::Base
belongs_to :site
has_many :actions
def parse
feed.items.each do |item|
action = actions.find_or_create_by_url(item.link)
action.update_from_feed_item(item)
action.save!
end
end
def feed
@rss ||= SimpleRSS.parse(open(url))
end
class << self
def parse_all
- find(:all).each { |feed| puts "Parsing #{feed.name}"; feed.parse }
+ find(:all).each do |feed|
+ puts "Parsing #{feed.name}"
+ begin
+ feed.parse
+ rescue
+ puts "ERROR on feed #{feed.name}"
+ end
+ end
end
end
end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
3482c279f56c9e9db77924f1e4ce5d21dfaa55bc
|
Adjusting display on search form of the sites
|
diff --git a/app/views/actions/_search_form.html.haml b/app/views/actions/_search_form.html.haml
index e8e58dd..19afb9d 100644
--- a/app/views/actions/_search_form.html.haml
+++ b/app/views/actions/_search_form.html.haml
@@ -1,33 +1,33 @@
#search_box
%h2 Find an Action
- form_for @search, :url => actions_path, :html => {:method => :get} do |f|
%table{ :border=>"0", :cellpadding=>"0", :cellspacing=>"0" }
%tr.first
%td Search Term:
%td= f.text_field :keywords, :size => 22
%td
= submit_tag 'Search'
= submit_tag 'Google Map', :onclick => "$('#new_search').attr('action', '#{map_index_path}')"
= submit_tag 'Tag Cloud', :onclick => "$('#new_search').attr('action', '#{tags_path}')"
= submit_tag 'Random', :onclick => "$('#new_search').attr('action', '#{random_path}')"
%tr
%td Type of Action:
%td= f.select :action_type, options_for_action_type_select
%td
Created:
= f.select :created, options_for_created_select
- - Site.find(:all, :order => :name).each_slice(4) do |sites|
+ - Site.find(:all, :order => :name).each_slice(5) do |sites|
.platform_select
- sites.each do |site|
= check_box_tag 'search[sites][]', site.id, @search.has_site?(site)
= site.name
%br/
%br{:clear => 'all'}/
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
39c64757edb27705e845a78d171e7d73194314d2
|
Adding The Point feed
|
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index d6bcb8d..e2d11f4 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,179 +1,178 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
action_type: Group Fundraiser
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
action_type: Pledged Action
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Group Fundraiser
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Affinity Group
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Pledged Action
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Group Fundraiser
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
action_type: Group Fundraiser
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
location_finder:
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
action_type: Petition
-# https is causing failing right now
-# the_point:
-# name: ThePoint
-# url: http://www.thepoint.com/rss
-# tag_finder:
-# location_finder:
-# last_accessed: <%= 1.day.ago %>
-# site: the_point
- # action_type: Pledged Action
+the_point:
+ name: ThePoint
+ url: http://www.thepoint.com/rss
+ tag_finder:
+ location_finder:
+ last_accessed: <%= 1.day.ago %>
+ site: the_point
+ action_type: Pledged Action
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
action_type: Group Fundraiser
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
action_type: Group Fundraiser
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
action_type: Group Fundraiser
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
action_type: Micro-credit Loan
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/pca/badgefeed.aspx
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
action_type: Group Fundraiser
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
action_type: Group Fundraiser
zazengo:
name: Latest Zazengo Projects
url: http://www.zazengo.com/projects.rss
tag_finder: "<span class=\"issues\">([\w\s,]+)</span>"
location_finder: "<span class=\"street-address\">([\w\s,]+)</span>"
last_accessed: <%= 1.day.ago %>
site: zazengo
action_type: Affinity Group
helpalot:
name: Helpalot
url: http://www.helpalot.org/en/feed/projects/
tag_finder:
location_finder: "<br /><br />\n([\w\s,]+)\n<br />"
last_accessed: <%= 1.day.ago %>
site: helpalot
action_type: Affinity Group
donorschoose:
name: DonorsChoose
url: http://www.donorschoose.org/common/rss_feed.html?zone=0&schoolType=0&partiallyFunded=true&teacherType=0&y=22&x=20
tag_finder:
location_finder: "<br />([\w\s,]+)<br />Level:"
last_accessed: <%= 1.day.ago %>
site: donorschoose
action_type: Group Fundraiser
diff --git a/spec/fixtures/sites.yml b/spec/fixtures/sites.yml
index fa0fcf5..4ad76c1 100644
--- a/spec/fixtures/sites.yml
+++ b/spec/fixtures/sites.yml
@@ -1,70 +1,67 @@
global_giving:
name: GlobalGiving
url: http://www.globalgiving.com
pledge_bank:
name: PledgeBank
url: http://www.pledgebank.com
change_org:
name: Change.org
url: http://www.change.org
razoo:
name: Razoo
url: http://beta.razoo.com
democracy_in_action:
name: DemocracyinAction
url: http://www.democracyinaction.org
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com
-# https is causing failing right now
-# the_point:
-# name: ThePoint
-# url: http://www.thepoint.com/rss
-#
-# last_accessed: <%= 1.day.ago %>
+the_point:
+ name: ThePoint
+ url: http://www.thepoint.com
give_meaning:
name: GiveMeaning
url: http://www.givemeaning.com
changing_the_present:
name: ChangingthePresent
url: http://www.changingthepresent.com
fundable:
name: Fundable
url: http://www.fundable.org
bring_light:
name: BringLight
url: http://www.bringlight.com
kiva:
name: Kiva
url: http://www.kiva.org
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org
first_giving:
name: Firstgiving
url: http://www.firstgiving.com
zazengo:
name: Zazengo
url: http://www.zazengo.com
helpalot:
name: Helpalot
url: http://www.helpalot.com
donorschoose:
name: DonorsChoose
url: http://www.donorschoose.org
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
da99a233e2378fea5e972135bdea7584856feb0b
|
Adding donorsChoose feed with location parsing
|
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index 77d924d..d6bcb8d 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,170 +1,179 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
action_type: Group Fundraiser
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
action_type: Pledged Action
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Group Fundraiser
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Affinity Group
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Pledged Action
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Group Fundraiser
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
action_type: Group Fundraiser
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
location_finder:
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
action_type: Petition
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
# tag_finder:
# location_finder:
# last_accessed: <%= 1.day.ago %>
# site: the_point
# action_type: Pledged Action
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
action_type: Group Fundraiser
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
action_type: Group Fundraiser
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
action_type: Group Fundraiser
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
action_type: Micro-credit Loan
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/pca/badgefeed.aspx
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
action_type: Group Fundraiser
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
action_type: Group Fundraiser
zazengo:
name: Latest Zazengo Projects
url: http://www.zazengo.com/projects.rss
tag_finder: "<span class=\"issues\">([\w\s,]+)</span>"
location_finder: "<span class=\"street-address\">([\w\s,]+)</span>"
last_accessed: <%= 1.day.ago %>
site: zazengo
action_type: Affinity Group
helpalot:
name: Helpalot
url: http://www.helpalot.org/en/feed/projects/
tag_finder:
location_finder: "<br /><br />\n([\w\s,]+)\n<br />"
last_accessed: <%= 1.day.ago %>
site: helpalot
action_type: Affinity Group
+
+donorschoose:
+ name: DonorsChoose
+ url: http://www.donorschoose.org/common/rss_feed.html?zone=0&schoolType=0&partiallyFunded=true&teacherType=0&y=22&x=20
+ tag_finder:
+ location_finder: "<br />([\w\s,]+)<br />Level:"
+ last_accessed: <%= 1.day.ago %>
+ site: donorschoose
+ action_type: Group Fundraiser
diff --git a/spec/fixtures/sites.yml b/spec/fixtures/sites.yml
index 0fd1848..fa0fcf5 100644
--- a/spec/fixtures/sites.yml
+++ b/spec/fixtures/sites.yml
@@ -1,66 +1,70 @@
global_giving:
name: GlobalGiving
url: http://www.globalgiving.com
pledge_bank:
name: PledgeBank
url: http://www.pledgebank.com
change_org:
name: Change.org
url: http://www.change.org
razoo:
name: Razoo
url: http://beta.razoo.com
democracy_in_action:
name: DemocracyinAction
url: http://www.democracyinaction.org
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
#
# last_accessed: <%= 1.day.ago %>
give_meaning:
name: GiveMeaning
url: http://www.givemeaning.com
changing_the_present:
name: ChangingthePresent
url: http://www.changingthepresent.com
fundable:
name: Fundable
url: http://www.fundable.org
bring_light:
name: BringLight
url: http://www.bringlight.com
kiva:
name: Kiva
url: http://www.kiva.org
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org
first_giving:
name: Firstgiving
url: http://www.firstgiving.com
zazengo:
name: Zazengo
url: http://www.zazengo.com
helpalot:
name: Helpalot
- url: http://www.helpalot.com
\ No newline at end of file
+ url: http://www.helpalot.com
+
+donorschoose:
+ name: DonorsChoose
+ url: http://www.donorschoose.org
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
864a11fb014c557f2262bd429c2b0535d531577b
|
Adding in new Helpalot feed, and fixing a few small issues
|
diff --git a/app/models/action.rb b/app/models/action.rb
index c696ed8..27d121e 100644
--- a/app/models/action.rb
+++ b/app/models/action.rb
@@ -1,76 +1,88 @@
class Action < ActiveRecord::Base
include GeoKit::Geocoders
belongs_to :feed
belongs_to :site
acts_as_taggable
acts_as_mappable :lat_column_name => :latitude, :lng_column_name => :longitude
before_save :look_for_tags, :look_for_location, :geocode_lookup, :denormalize
def update_from_feed_item(item)
puts " -- Action: #{item.title}"
self.title = item.title
self.url = item.link
- self.description = item.description
+ self.description = description_for(item)
self.created_at = item.pubDate if item.pubDate
self.created_at = item.dc_date if item.dc_date
+ self.created_at = item.updated if item.updated
figure_out_address_from(item)
end
def description=(new_description)
write_attribute(:description, fix_quoted_html(new_description))
end
+
+ # Seems like Atom uses <content> not <description> ??
+ def description_for(item)
+ if item.description
+ item.description
+ elsif item.content
+ item.content
+ else
+ ""
+ end
+ end
def self.per_page
10
end
protected
def fix_quoted_html(text)
text.gsub(/\</, '<').gsub(/\>/, '>')
end
def look_for_location
if feed.location_finder and self.description
match = self.description.match(feed.location_finder.to_s)
self.location = match[1] if match and match[1]
puts " Found Location: #{self.location}"
end
end
def look_for_tags
if feed.tag_finder and description
match = description.match(feed.tag_finder.to_s)
self.tag_list = match[1] if match and match[1]
puts " Found Tags: #{self.tag_list}"
end
end
def figure_out_address_from(item)
if item.geo_lat and item.geo_long
self.latitude = item.geo_lat
self.longitude = item.geo_long
end
end
def geocode_lookup
unless location.nil? or location.empty?
result = MultiGeocoder.geocode(location)
if result.success
self.latitude = result.lat
self.longitude = result.lng
puts " Geocoding Successful - #{result}"
end
end
end
def denormalize
self.site_id = self.feed.site_id
self.action_type = self.feed.action_type
end
end
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index da6c054..77d924d 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,161 +1,170 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
action_type: Group Fundraiser
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
action_type: Pledged Action
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Group Fundraiser
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
action_type: Affinity Group
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Pledged Action
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
action_type: Group Fundraiser
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
action_type: Group Fundraiser
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
location_finder:
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
action_type: Petition
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
# tag_finder:
# location_finder:
# last_accessed: <%= 1.day.ago %>
# site: the_point
# action_type: Pledged Action
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
action_type: Pledged Action
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
action_type: Group Fundraiser
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
action_type: Group Fundraiser
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
action_type: Group Fundraiser
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
action_type: Micro-credit Loan
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/pca/badgefeed.aspx
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
action_type: Group Fundraiser
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
action_type: Group Fundraiser
zazengo:
name: Latest Zazengo Projects
url: http://www.zazengo.com/projects.rss
tag_finder: "<span class=\"issues\">([\w\s,]+)</span>"
location_finder: "<span class=\"street-address\">([\w\s,]+)</span>"
last_accessed: <%= 1.day.ago %>
site: zazengo
- action_type: Affinity Group
\ No newline at end of file
+ action_type: Affinity Group
+
+helpalot:
+ name: Helpalot
+ url: http://www.helpalot.org/en/feed/projects/
+ tag_finder:
+ location_finder: "<br /><br />\n([\w\s,]+)\n<br />"
+ last_accessed: <%= 1.day.ago %>
+ site: helpalot
+ action_type: Affinity Group
diff --git a/spec/fixtures/sites.yml b/spec/fixtures/sites.yml
index c0198e6..0fd1848 100644
--- a/spec/fixtures/sites.yml
+++ b/spec/fixtures/sites.yml
@@ -1,62 +1,66 @@
global_giving:
name: GlobalGiving
url: http://www.globalgiving.com
pledge_bank:
name: PledgeBank
url: http://www.pledgebank.com
change_org:
name: Change.org
url: http://www.change.org
razoo:
name: Razoo
url: http://beta.razoo.com
democracy_in_action:
name: DemocracyinAction
url: http://www.democracyinaction.org
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
#
# last_accessed: <%= 1.day.ago %>
give_meaning:
name: GiveMeaning
url: http://www.givemeaning.com
changing_the_present:
name: ChangingthePresent
url: http://www.changingthepresent.com
fundable:
name: Fundable
url: http://www.fundable.org
bring_light:
name: BringLight
url: http://www.bringlight.com
kiva:
name: Kiva
url: http://www.kiva.org
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org
first_giving:
name: Firstgiving
url: http://www.firstgiving.com
zazengo:
name: Zazengo
- url: http://www.zazengo.com
\ No newline at end of file
+ url: http://www.zazengo.com
+
+helpalot:
+ name: Helpalot
+ url: http://www.helpalot.com
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
3e747cc6f74fd848c46003580dcb522e32b2dddf
|
Catching created_at date from the RDF style feed
|
diff --git a/app/models/action.rb b/app/models/action.rb
index 8d656db..c696ed8 100644
--- a/app/models/action.rb
+++ b/app/models/action.rb
@@ -1,75 +1,76 @@
class Action < ActiveRecord::Base
include GeoKit::Geocoders
belongs_to :feed
belongs_to :site
acts_as_taggable
acts_as_mappable :lat_column_name => :latitude, :lng_column_name => :longitude
before_save :look_for_tags, :look_for_location, :geocode_lookup, :denormalize
def update_from_feed_item(item)
puts " -- Action: #{item.title}"
self.title = item.title
self.url = item.link
self.description = item.description
self.created_at = item.pubDate if item.pubDate
+ self.created_at = item.dc_date if item.dc_date
figure_out_address_from(item)
end
def description=(new_description)
write_attribute(:description, fix_quoted_html(new_description))
end
def self.per_page
10
end
protected
def fix_quoted_html(text)
text.gsub(/\</, '<').gsub(/\>/, '>')
end
def look_for_location
if feed.location_finder and self.description
match = self.description.match(feed.location_finder.to_s)
self.location = match[1] if match and match[1]
puts " Found Location: #{self.location}"
end
end
def look_for_tags
if feed.tag_finder and description
match = description.match(feed.tag_finder.to_s)
self.tag_list = match[1] if match and match[1]
puts " Found Tags: #{self.tag_list}"
end
end
def figure_out_address_from(item)
if item.geo_lat and item.geo_long
self.latitude = item.geo_lat
self.longitude = item.geo_long
end
end
def geocode_lookup
unless location.nil? or location.empty?
result = MultiGeocoder.geocode(location)
if result.success
self.latitude = result.lat
self.longitude = result.lng
puts " Geocoding Successful - #{result}"
end
end
end
def denormalize
self.site_id = self.feed.site_id
self.action_type = self.feed.action_type
end
end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
76279a3e5a50485d0c8686013e1435f7639a60a7
|
Putting in a bit of "coming soon" on the action view
|
diff --git a/app/views/actions/_action.html.haml b/app/views/actions/_action.html.haml
index aa57591..a402ab9 100644
--- a/app/views/actions/_action.html.haml
+++ b/app/views/actions/_action.html.haml
@@ -1,24 +1,29 @@
%div[action]
= link_to action.title, action_path(action), :class => 'action-title', :rel => 'facebox'
.action-source
.action-byline= "Created on #{link_to action.site.name, action.site.url} by TODO"
.action-created= action.created_at.to_s(:default)
.action-type= "#{action.action_type} "
%span{:class => 'action-goal'}
%strong
- Goal:
+ Goal:
+ Coming Soon...
%br/
%span{:class => 'action-location'}
%strong
Location:
- = action.location
+ - unless action.location.nil? or action.location.empty?
+ = action.location
+ - else
+ Location unknown
%br/
%span{:class => 'action-tags'}
%strong
Tags:
+
= tag_list_for action
%br/
.action-description
= shorten_and_clean(action.description)
= link_to action.url, action.url, :class => 'action-url'
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
6dd1b52d596fbee3c7cef360b4e70de5f02be317
|
Fixing a bug with going directly to /map
|
diff --git a/app/controllers/map_controller.rb b/app/controllers/map_controller.rb
index b9e4457..94a85a4 100644
--- a/app/controllers/map_controller.rb
+++ b/app/controllers/map_controller.rb
@@ -1,56 +1,58 @@
class MapController < ApplicationController
include ActionView::Helpers::JavaScriptHelper
def index
- @search = Search.new(params[:search].merge(:kind => 'map', :ip_address => request.remote_ip))
+ @search = Search.new(params[:search])
+ @search.kind = 'map'
+ @search.ip_address = request.remote_ip
@actions = @search.results(params[:page])
setup_map
@actions.each do |action|
# now for the lat and lng of the marker we want to add.
marker_lat = action.latitude
marker_lng = action.longitude
@gmap.use_marker_code('createWithIconAndHtml', :with_args => [:point, :html, :icon_image])
incident_point = Mappa::GLatLng.new(:lat => marker_lat, :lng => marker_lng)
@gmap.add_marker(:point => incident_point, :create_with => 'createWithIconAndHtml', :html => "'#{escape_javascript(small_map_view_of(action))}'", :icon_image => "'/images/marker.png'")
end
end
protected
def setup_map
@gmap = Mappa::GMap.new()
@gmap.api_key = 'ABQIAAAAkGYfBpkZ5yYF_f9sthqC5BTJQa0g3IQ9GZqIMmInSLzwtGDKaBRu7u3V_uePSTUgmfHvnGnehFX3-A'
# set the longitude and latitiude of the centre point of our map
@gmap.lat, @gmap.lng = @search.current_latitude, @search.current_longitude
# set the zoom level of our map. This number is in the range of 1-18. 1 is lowest zoom and 18 is highest
# we've picked a nice middling 12.
@gmap.zoom = 2
@gmap.add_control(:control => 'small')
@gmap.add_control(:control => 'type')
@gmap.add_control(:control => 'overview')
end
def small_map_view_of(action)
%{
<div class="map-action">
<div class="title">
<a href="#{action.url}" target="_blank">#{action.title}</a>
</div>
<div class="location">
<b>Location:</b> #{action.location}
</div>
<div class="byline">
<b>Created on:</b> <a href="#{action.site.url}" target="_blank">#{action.site.name}</a>
</div>
<div class="created">
<b>Created at:</b> #{action.created_at.to_s(:default)}
</div>
</div>
}
end
end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
8101e141bc78b1eaab065a80d9aece13d01261c5
|
Putting up a notice message on the maps page that there aren't that many location actions in there yet
|
diff --git a/app/views/map/index.html.haml b/app/views/map/index.html.haml
index 77d049f..b56909f 100644
--- a/app/views/map/index.html.haml
+++ b/app/views/map/index.html.haml
@@ -1,8 +1,14 @@
- content_for :map_headers do
= map_header(@gmap)
= map_body(@gmap)
= render :partial => 'actions/search_form'
+#notice
+ %p
+ %strong
+ Note:
+ At this point, only a few social action platforms publish location information in their RSS feeds. We are working with the platforms to develop a standard format for referencing location. In the meantime, please <a href="/map">use this map to show all social change campaigns for which location is known</a>.
+
#gmap
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index 8c95d95..03337d6 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,175 +1,175 @@
body
:font-family Arial, Helvetica, sans-serif
a
:color #3366cc
:text-decoration none
h2
:margin 0px 0px 5px 0px
p
:margin 3px
:margin-top 5px
// Block Elements
-#search_results, #tag_cloud, #facebox
+#search_results, #tag_cloud, #facebox, #notice
:width 710px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 0px 10px
// Search box
#search_box
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:background-color #e9f3f1
:padding 10px 10px 30px 10px
table
td
:padding-right 5px
:padding-top 10px
.first
td
:padding-top 0
.platform_select
:width 170px
:float left
:margin-top 10px
// Results Elements
.action
:width 700px
:margin-bottom 30px
.action-title
:margin-top 5px
:margin-bottom 5px
:font-size 160%
:display block
.action-source
:width 250px
:float right
/:margin-left 25px
:text-align right
.action-goal
.action-location
.action-tags
.action-url
:margin-top 10px
:display block
:color #ff6600
.action-url a
.action-url a:hover
.action-byline
.action-byline a
:font-weight bold
.action-byline a:hover
.action-created
.action-type
:font-style italic
.action-description
:clear both
:margin-top 5px
// Pagination
.pagination
:padding 3px
:margin 3px
.pagination a
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:text-decoration none
:color #3366cc
.pagination a:hover, .pagination a:active
:border 1px solid #3366cc
:color #000
.pagination span.current
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:font-weight bold
:background-color #3366cc
:color #FFF
.pagination span.disabled
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #eee
:color #ddd
// Map
#gmap
:height 400px
:width 710px
:margin-top 20px
.map-action
:font-size 12px
:width 200px
:border 1px red
:font-family Arial, Helvetica, sans-serif
.title
.location
:font-size 80%
.byline
:font-size 80%
.created
:font-size 80%
// Tags
.tag1
:font-size 1.0em
.tag2
:font-size 1.2em
.tag3
:font-size 1.4em
.tag4
:font-size 1.6em
// Facebox Popup
#facebox
.action-title
:color #3366cc
.description
:height 200px
:overflow auto
:clear both
// Header
#header
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 20px 10px
// Footer
#footer
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 20px 10px
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
8497e4b90e5ac632dbdd0c2a941e7d1fe959b21d
|
Header text change
|
diff --git a/app/views/layouts/_main_header.html.erb b/app/views/layouts/_main_header.html.erb
index 8a20428..d299379 100644
--- a/app/views/layouts/_main_header.html.erb
+++ b/app/views/layouts/_main_header.html.erb
@@ -1,25 +1,25 @@
<div id="header">
<h2>A Mashup of 29+ Social Action Platforms</h2>
<div style="float:right;width:360x;margin-left:15px;margin-top:10px"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="playerLoader" width="360" height="301" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
<param name="movie" value="http://farm.sproutbuilder.com/112320/load/uwBkG7aMAWbz_4HQ.swf"/>
<param name="quality" value="high"/>
<param name="allowScriptAccess" value="always"/>
<param name="allowFullScreen" value="true"/>
<param name="wmode" value="transparent"/>
<embed src="http://farm.sproutbuilder.com/112320/load/uwBkG7aMAWbz_4HQ.swf" width="360" height="301" name="playerLoader" align="middle" wmode="transparent" play="true" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"/>
</object><img style="visibility:hidden;width:0px;height:0px;" border=0 width=0 height=0 src="http://counters.gigya.com/wildfire/CIMP/Jmx*PTEyMDU3MDAyMjkyNjImcHQ9MTIwNTcwMDIzMTMyMiZwPTEyMDc*MSZkPTExMjM4MyZuPQ==.jpg" /></div>
<p style="margin-top:10px">Hello NetSquared Mashup Voters,</p>
<p>You have arrived on the initial version of <strong><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">"A Mashup of 29+ Social Action Platforms."</a></strong></p><p>Please test drive our mashup using the form below.</p>
<p>This version of the mashup allows you to</p>
<ul style="margin-top:4px;margin-bottom:4px">
- <li><strong>Search across 17 social action platforms for 5 kinds of campaigns</strong>: group fundraisers, pledged actions, petitions, micro-credit loans, and affinity groups.</li>
+ <li><strong>Search across 14 social action platforms for 5 kinds of campaigns</strong>: group fundraisers, pledged actions, petitions, micro-credit loans, and affinity groups.</li>
<li><strong>Map peer-to-peer social change campaigns</strong> using the Google Maps API.</li>
</ul>
<p></p>
<p><em>How can we make this mashup better</em>? </p>
<p>Please send your feedback to <strong><a href="mailto:[email protected]">[email protected]</a></strong> or <strong><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">post a comment</a>.</strong> </p>
<p>Thank you for your support!</p>
</div>
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
ba947b0406b78e47d09a26c400c2980df046ca48
|
A bit of cleanup, and adding in description on search results
|
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 0386ad5..f962d0f 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,39 +1,45 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def map_loader
if [email protected]? && @gmap.onload
{:onload => @gmap.onload_func_name + '()', :onunload => 'GUnload'}
else
{}
end
end
def options_for_action_type_select
[
['All actions', "all"],
['Affinity Group'],
['Group Fundraiser'],
['Micro-credit Loan'],
['Petition'],
['Pledged Action']
]
end
def options_for_created_select
[
['Any Time', nil],
['Last 30 days', 30],
['Last 14 days',14],
['Last week', 7],
['Yesterday', 2],
['Today', 1]
]
end
def tag_list_for(action)
action.tags.collect do |tag|
link_to tag.name, tag_path(tag)
end.join(', ')
end
+
+ def shorten_and_clean(text)
+ output = strip_tags(text).to(200).split(' ')
+ output.pop
+ output.join(' ') + '...'
+ end
end
diff --git a/app/models/search.rb b/app/models/search.rb
index 73beca7..4b9bec1 100644
--- a/app/models/search.rb
+++ b/app/models/search.rb
@@ -1,113 +1,114 @@
class Search < ActiveRecord::BaseWithoutTable
column :keywords, :string
column :action_type, :string
column :created, :integer
attr_accessor :sites, :kind, :ip_address
validates_inclusion_of :created, :in => %w{ 30 14 7 2 1 }
def results(page)
if kind == 'map'
Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => build_conditions)
else
Action.paginate(:all, :page => page, :order => build_order, :conditions => build_conditions)
end
end
def build_conditions
reset_conditions
add_keywords
add_action_type
add_sites
add_created
add_mapping
conditions.join(' AND ')
end
def build_order
kind == 'random' ? 'RAND()' : 'created_at DESC'
end
def sites
@sites ||= []
end
def has_site?(site)
+ return true if sites.empty?
sites.include?(site.id.to_s)
end
def reset_conditions
@conditions = []
end
def conditions
@conditions ||= []
end
def add_keywords
unless keywords.nil? or keywords.empty?
keyword_conditions = []
keywords.split(' ').each do |keyword|
keyword_conditions << sanitize(["(description LIKE ? OR title LIKE ?)", "%#{keyword}%", "%#{keyword}%"])
end
conditions << "(" + keyword_conditions.join(' OR ') + ")"
end
end
def add_action_type
unless action_type.nil? or action_type == 'all'
conditions << "action_type = '#{action_type}'"
end
end
def add_sites
unless sites.nil? or sites.empty?
conditions << sanitize(["site_id IN (?)", sites])
end
end
def add_created
unless created.nil?
conditions << sanitize(["actions.created_at > ?", created.days.ago])
end
end
def add_mapping
if kind == 'map'
conditions << 'latitude IS NOT NULL and longitude IS NOT NULL'
end
end
def sanitize(arg)
ActiveRecord::Base.send(:sanitize_sql, arg)
end
def current_latitude
current_location.lat || 21.98
end
def current_longitude
current_location.lng || -10.00
end
def current_location
# debugger
@current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
end
def current_ip
ip_address == '127.0.0.1' ? '67.162.124.13' : ip_address
end
# def get_current_location
# location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
# unless location.lat.nil? and location.lng.nil?
# return location.lat, location.lng
# else
# return 41.98, -87.90 # Chicago, an estimate
# end
# end
end
diff --git a/app/views/actions/_action.html.haml b/app/views/actions/_action.html.haml
index d229798..aa57591 100644
--- a/app/views/actions/_action.html.haml
+++ b/app/views/actions/_action.html.haml
@@ -1,30 +1,24 @@
%div[action]
= link_to action.title, action_path(action), :class => 'action-title', :rel => 'facebox'
.action-source
- %span{:class => 'action-byline'}
- Created on
- = link_to action.site.name, action.site.url
- by
- = link_to 'TODO', ''
- %br/
- %span{:class => 'action-created'}
- = action.created_at.to_s(:default)
- %br/
- %span{:class => 'action-type'} TODO
+ .action-byline= "Created on #{link_to action.site.name, action.site.url} by TODO"
+ .action-created= action.created_at.to_s(:default)
+ .action-type= "#{action.action_type} "
%span{:class => 'action-goal'}
%strong
Goal:
- TODO
%br/
%span{:class => 'action-location'}
%strong
Location:
= action.location
%br/
%span{:class => 'action-tags'}
%strong
Tags:
= tag_list_for action
%br/
+ .action-description
+ = shorten_and_clean(action.description)
= link_to action.url, action.url, :class => 'action-url'
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index de13e44..8c95d95 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,173 +1,175 @@
body
:font-family Arial, Helvetica, sans-serif
a
:color #3366cc
:text-decoration none
h2
:margin 0px 0px 5px 0px
p
:margin 3px
:margin-top 5px
// Block Elements
#search_results, #tag_cloud, #facebox
:width 710px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 0px 10px
// Search box
#search_box
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:background-color #e9f3f1
:padding 10px 10px 30px 10px
table
td
:padding-right 5px
:padding-top 10px
.first
td
:padding-top 0
.platform_select
:width 170px
:float left
:margin-top 10px
// Results Elements
.action
:width 700px
:margin-bottom 30px
.action-title
:margin-top 5px
:margin-bottom 5px
:font-size 160%
:display block
.action-source
- :width 320px
+ :width 250px
:float right
- :margin-left 25px
+ /:margin-left 25px
:text-align right
.action-goal
.action-location
.action-tags
.action-url
:margin-top 10px
:display block
:color #ff6600
.action-url a
.action-url a:hover
.action-byline
.action-byline a
:font-weight bold
.action-byline a:hover
.action-created
-
.action-type
:font-style italic
+.action-description
+ :clear both
+ :margin-top 5px
// Pagination
.pagination
:padding 3px
:margin 3px
.pagination a
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:text-decoration none
:color #3366cc
.pagination a:hover, .pagination a:active
:border 1px solid #3366cc
:color #000
.pagination span.current
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:font-weight bold
:background-color #3366cc
:color #FFF
.pagination span.disabled
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #eee
:color #ddd
// Map
#gmap
:height 400px
:width 710px
:margin-top 20px
.map-action
:font-size 12px
:width 200px
:border 1px red
:font-family Arial, Helvetica, sans-serif
.title
.location
:font-size 80%
.byline
:font-size 80%
.created
:font-size 80%
// Tags
.tag1
:font-size 1.0em
.tag2
:font-size 1.2em
.tag3
:font-size 1.4em
.tag4
:font-size 1.6em
// Facebox Popup
#facebox
.action-title
:color #3366cc
.description
:height 200px
:overflow auto
:clear both
// Header
#header
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 20px 10px
// Footer
#footer
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 20px 10px
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
b5ec23cfe8679d20cfc53f8590c6d2d73f9de01d
|
Adding search on title as well as description
|
diff --git a/app/models/search.rb b/app/models/search.rb
index a5adc76..73beca7 100644
--- a/app/models/search.rb
+++ b/app/models/search.rb
@@ -1,113 +1,113 @@
class Search < ActiveRecord::BaseWithoutTable
column :keywords, :string
column :action_type, :string
column :created, :integer
attr_accessor :sites, :kind, :ip_address
validates_inclusion_of :created, :in => %w{ 30 14 7 2 1 }
def results(page)
if kind == 'map'
Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => build_conditions)
else
Action.paginate(:all, :page => page, :order => build_order, :conditions => build_conditions)
end
end
def build_conditions
reset_conditions
add_keywords
add_action_type
add_sites
add_created
add_mapping
conditions.join(' AND ')
end
def build_order
kind == 'random' ? 'RAND()' : 'created_at DESC'
end
def sites
@sites ||= []
end
def has_site?(site)
sites.include?(site.id.to_s)
end
def reset_conditions
@conditions = []
end
def conditions
@conditions ||= []
end
def add_keywords
unless keywords.nil? or keywords.empty?
keyword_conditions = []
keywords.split(' ').each do |keyword|
- keyword_conditions << sanitize(["description LIKE ?", "%#{keyword}%"]) # TODO add url, title
+ keyword_conditions << sanitize(["(description LIKE ? OR title LIKE ?)", "%#{keyword}%", "%#{keyword}%"])
end
conditions << "(" + keyword_conditions.join(' OR ') + ")"
end
end
def add_action_type
unless action_type.nil? or action_type == 'all'
conditions << "action_type = '#{action_type}'"
end
end
def add_sites
unless sites.nil? or sites.empty?
conditions << sanitize(["site_id IN (?)", sites])
end
end
def add_created
unless created.nil?
conditions << sanitize(["actions.created_at > ?", created.days.ago])
end
end
def add_mapping
if kind == 'map'
conditions << 'latitude IS NOT NULL and longitude IS NOT NULL'
end
end
def sanitize(arg)
ActiveRecord::Base.send(:sanitize_sql, arg)
end
def current_latitude
current_location.lat || 21.98
end
def current_longitude
current_location.lng || -10.00
end
def current_location
# debugger
@current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
end
def current_ip
ip_address == '127.0.0.1' ? '67.162.124.13' : ip_address
end
# def get_current_location
# location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
# unless location.lat.nil? and location.lng.nil?
# return location.lat, location.lng
# else
# return 41.98, -87.90 # Chicago, an estimate
# end
# end
end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
29aaf67cc37b53cfc89209e6d20779e7aa14705e
|
Oops, forgot this file. Getting used to git
|
diff --git a/app/views/layouts/_main_header.html.erb b/app/views/layouts/_main_header.html.erb
new file mode 100644
index 0000000..8a20428
--- /dev/null
+++ b/app/views/layouts/_main_header.html.erb
@@ -0,0 +1,25 @@
+<div id="header">
+<h2>A Mashup of 29+ Social Action Platforms</h2>
+
+<div style="float:right;width:360x;margin-left:15px;margin-top:10px"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="playerLoader" width="360" height="301" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
+ <param name="movie" value="http://farm.sproutbuilder.com/112320/load/uwBkG7aMAWbz_4HQ.swf"/>
+ <param name="quality" value="high"/>
+ <param name="allowScriptAccess" value="always"/>
+ <param name="allowFullScreen" value="true"/>
+ <param name="wmode" value="transparent"/>
+ <embed src="http://farm.sproutbuilder.com/112320/load/uwBkG7aMAWbz_4HQ.swf" width="360" height="301" name="playerLoader" align="middle" wmode="transparent" play="true" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"/>
+</object><img style="visibility:hidden;width:0px;height:0px;" border=0 width=0 height=0 src="http://counters.gigya.com/wildfire/CIMP/Jmx*PTEyMDU3MDAyMjkyNjImcHQ9MTIwNTcwMDIzMTMyMiZwPTEyMDc*MSZkPTExMjM4MyZuPQ==.jpg" /></div>
+<p style="margin-top:10px">Hello NetSquared Mashup Voters,</p>
+<p>You have arrived on the initial version of <strong><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">"A Mashup of 29+ Social Action Platforms."</a></strong></p><p>Please test drive our mashup using the form below.</p>
+
+<p>This version of the mashup allows you to</p>
+<ul style="margin-top:4px;margin-bottom:4px">
+ <li><strong>Search across 17 social action platforms for 5 kinds of campaigns</strong>: group fundraisers, pledged actions, petitions, micro-credit loans, and affinity groups.</li>
+ <li><strong>Map peer-to-peer social change campaigns</strong> using the Google Maps API.</li>
+ </ul>
+<p></p>
+<p><em>How can we make this mashup better</em>? </p>
+
+<p>Please send your feedback to <strong><a href="mailto:[email protected]">[email protected]</a></strong> or <strong><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">post a comment</a>.</strong> </p>
+<p>Thank you for your support!</p>
+</div>
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
541b12d45e48308e0bf5c858537f742cc492810a
|
New header, and small header on pages other than the home page
|
diff --git a/app/views/layouts/_footer.html.erb b/app/views/layouts/_footer.html.erb
index 269b609..1d90bee 100644
--- a/app/views/layouts/_footer.html.erb
+++ b/app/views/layouts/_footer.html.erb
@@ -1,14 +1,14 @@
<div id="footer">
- <p><a href="http://creativecommons.org/licenses/by-nc-sa/2.5/"><img src="/images/creativecommons.gif" border="0" align="left" style="margin:3px 10px 20px 0px"></a>© Copyright 2008 Peter Deitz and Cameron Booth. <a href="http://creativecommons.org/licenses/by-nc-sa/2.5/">Some Rights Reserved</a>.</p>
- <p><em>This mashup uses Ruby on Rails. The project </em><em>lead is Peter Deitz, <a href="http://www.socialactions.com">Social Actions</a>.</em><em> </em><em>The lead engineer is Cameron Booth, <a href="http://www.cdbdesign.net">CDBdesign.net</a></em>.
+<p><a href="http://creativecommons.org/licenses/by-nc-sa/2.5/"><img src="/images/creativecommons.gif" border="0" align="left" style="margin:3px 10px 20px 0px"></a>© Copyright 2008 Peter Deitz and Cameron Booth. <a href="http://creativecommons.org/licenses/by-nc-sa/2.5/">Some Rights Reserved</a>.</p>
+<p><em>This mashup uses Ruby on Rails. The project </em><em>lead is Peter Deitz, <a href="http://www.socialactions.com">Social Actions</a>.</em><em> </em><em>The lead engineer is Cameron Booth, <a href="http://www.cdbdesign.net">cdbdesign.net</a></em>.
</div>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
-var pageTracker = _gat._getTracker("UA-772094-6");
+var pageTracker = _gat._getTracker("UA-772094-7");
pageTracker._initData();
pageTracker._trackPageview();
</script>
\ No newline at end of file
diff --git a/app/views/layouts/_header.html.erb b/app/views/layouts/_header.html.erb
index 54b7beb..260b715 100644
--- a/app/views/layouts/_header.html.erb
+++ b/app/views/layouts/_header.html.erb
@@ -1,29 +1,8 @@
<div id="header">
+<h2>A Mashup of 29+ Social Action Platforms</h2>
- <h2>A Mashup of 29+ Social Action Platforms</h2>
-
- <div style="float:right;width:360x;margin-left:15px;margin-top:10px"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="playerLoader" width="360" height="301" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
- <param name="movie" value="http://farm.sproutbuilder.com/112320/load/uwBkG7aMAWbz_4HQ.swf"/>
- <param name="quality" value="high"/>
- <param name="allowScriptAccess" value="always"/>
- <param name="allowFullScreen" value="true"/>
- <param name="wmode" value="transparent"/>
- <embed src="http://farm.sproutbuilder.com/112320/load/uwBkG7aMAWbz_4HQ.swf" width="360" height="301" name="playerLoader" align="middle" wmode="transparent" play="true" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"/>
- </object><img style="visibility:hidden;width:0px;height:0px;" border=0 width=0 height=0 src="http://counters.gigya.com/wildfire/CIMP/Jmx*PTEyMDU2OTU5OTAwMDImcHQ9MTIwNTY5NjA3Nzc5NyZwPTEyMDc*MSZkPTExMjM4MyZuPQ==.jpg" /></div>
-
- <p style="margin-top:10px">Hello NetSquared Mashup Voters,</p>
- <p>You have arrived on the initial version of <strong><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">"A Mashup of 29+ Social Action Platforms."</a></strong></p><p>Please test drive our mashup using the form below.</p>
-
- <p>This version of the mashup allows you to</p>
- <ul style="margin-top:4px;margin-bottom:4px">
- <li><strong>Search across 17 social action platforms for 5 kinds of campaigns</strong>: group fundraisers, pledged actions, petitions, micro-credit loans, and affinity groups.</li>
- <li><strong>Map peer-to-peer social change campaigns</strong> using the Google Maps API.</li>
- </ul>
- <p></p>
- <p><em>How can we make this mashup better</em>? </p>
-
- <p>Please send your feedback to <a href="mailto:[email protected]"><strong>[email protected]</strong></a> or <span class="style1"><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">post a comment</a>.</span> </p>
- <p>Thank you for your support!</p>
- <img style="visibility:hidden;width:0px;height:0px;" border=0 width=0 height=0 src="http://counters.gigya.com/wildfire/CIMP/Jmx*PTEyMDU2OTU5OTAwMDImcHQ9MTIwNTY5NTk5MzA2NCZwPTEyMDc*MSZkPTExMjM4MyZuPQ==.jpg" />
-
+<p style="margin-top:10px"><a href="http://www.netsquared.org/"><img src="http://www.socialactions.com/images/mashup/N2Y3Global.jpg" style="float:right;margin-left:15px" border="0" /></a>You are test driving the initial version of <strong><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">"A Mashup of 29+ Social Action Platforms."</a></strong> </p>
+<p style="margin-top:10px">Please send your feedback to <a href="mailto:[email protected]"><strong>[email protected]</strong></a> or <strong><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">post a comment</a>.</strong> </p>
+<p style="margin-top:10px"><strong><a href="/">Return to the homepage.</a></strong> Thank you for your support! </p>
</div>
+
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 303764e..901f022 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,16 +1,19 @@
!!! 1.0
%html{"xmlns"=>"http://www.w3.org/1999/xhtml", "xml:lang"=>"en"}
%head
%meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}/
%title A Mashup of 29+ Social Action Platforms
= stylesheet_link_tag 'main', 'facebox'
= javascript_include_tag 'jquery', 'facebox', 'application'
= yield :map_headers
%body{ map_loader }
- = render :partial => 'layouts/header'
+ - if params[:controller] == 'actions' and params[:action] == 'index' and params[:search].nil?
+ = render :partial => 'layouts/main_header'
+ - else
+ = render :partial => 'layouts/header'
= yield
= render :partial => 'layouts/footer'
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
2d983c9f54f48849bd1cae12adb63ea03c5be7f7
|
Bringing in random search result
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index 5df06f0..c937095 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,21 +1,31 @@
class ActionsController < ApplicationController
def index
@search = Search.new(params[:search])
@actions = @search.results(params[:page])
respond_to do |format|
format.html
format.xml
end
end
+ def random
+ @search = Search.new(params[:search].merge(:kind => 'random'))
+ @actions = @search.results(params[:page])
+ if @actions.empty?
+ redirect_to(:back)
+ else
+ redirect_to(@actions.first.url)
+ end
+ end
+
def show
@action = Action.find(params[:id])
respond_to do |format|
format.html { render :layout => false}
format.xml
end
end
end
diff --git a/app/models/search.rb b/app/models/search.rb
index e905335..a5adc76 100644
--- a/app/models/search.rb
+++ b/app/models/search.rb
@@ -1,109 +1,113 @@
class Search < ActiveRecord::BaseWithoutTable
column :keywords, :string
column :action_type, :string
column :created, :integer
attr_accessor :sites, :kind, :ip_address
validates_inclusion_of :created, :in => %w{ 30 14 7 2 1 }
def results(page)
if kind == 'map'
Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => build_conditions)
else
- Action.paginate(:all, :page => page, :order => 'created_at DESC', :conditions => build_conditions)
+ Action.paginate(:all, :page => page, :order => build_order, :conditions => build_conditions)
end
end
def build_conditions
reset_conditions
add_keywords
add_action_type
add_sites
add_created
add_mapping
conditions.join(' AND ')
end
+ def build_order
+ kind == 'random' ? 'RAND()' : 'created_at DESC'
+ end
+
def sites
@sites ||= []
end
def has_site?(site)
sites.include?(site.id.to_s)
end
def reset_conditions
@conditions = []
end
def conditions
@conditions ||= []
end
def add_keywords
unless keywords.nil? or keywords.empty?
keyword_conditions = []
keywords.split(' ').each do |keyword|
keyword_conditions << sanitize(["description LIKE ?", "%#{keyword}%"]) # TODO add url, title
end
conditions << "(" + keyword_conditions.join(' OR ') + ")"
end
end
def add_action_type
unless action_type.nil? or action_type == 'all'
conditions << "action_type = '#{action_type}'"
end
end
def add_sites
unless sites.nil? or sites.empty?
conditions << sanitize(["site_id IN (?)", sites])
end
end
def add_created
unless created.nil?
conditions << sanitize(["actions.created_at > ?", created.days.ago])
end
end
def add_mapping
if kind == 'map'
conditions << 'latitude IS NOT NULL and longitude IS NOT NULL'
end
end
def sanitize(arg)
ActiveRecord::Base.send(:sanitize_sql, arg)
end
def current_latitude
current_location.lat || 21.98
end
def current_longitude
current_location.lng || -10.00
end
def current_location
# debugger
@current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
end
def current_ip
ip_address == '127.0.0.1' ? '67.162.124.13' : ip_address
end
# def get_current_location
# location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
# unless location.lat.nil? and location.lng.nil?
# return location.lat, location.lng
# else
# return 41.98, -87.90 # Chicago, an estimate
# end
# end
end
diff --git a/app/views/actions/_search_form.html.haml b/app/views/actions/_search_form.html.haml
index 0c248a4..e8e58dd 100644
--- a/app/views/actions/_search_form.html.haml
+++ b/app/views/actions/_search_form.html.haml
@@ -1,33 +1,33 @@
#search_box
%h2 Find an Action
- form_for @search, :url => actions_path, :html => {:method => :get} do |f|
%table{ :border=>"0", :cellpadding=>"0", :cellspacing=>"0" }
%tr.first
%td Search Term:
%td= f.text_field :keywords, :size => 22
%td
= submit_tag 'Search'
= submit_tag 'Google Map', :onclick => "$('#new_search').attr('action', '#{map_index_path}')"
= submit_tag 'Tag Cloud', :onclick => "$('#new_search').attr('action', '#{tags_path}')"
- = submit_tag 'Random'
+ = submit_tag 'Random', :onclick => "$('#new_search').attr('action', '#{random_path}')"
%tr
%td Type of Action:
%td= f.select :action_type, options_for_action_type_select
%td
Created:
= f.select :created, options_for_created_select
- Site.find(:all, :order => :name).each_slice(4) do |sites|
.platform_select
- sites.each do |site|
= check_box_tag 'search[sites][]', site.id, @search.has_site?(site)
= site.name
%br/
%br{:clear => 'all'}/
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index f78278f..13c3e7b 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,38 +1,38 @@
ActionController::Routing::Routes.draw do |map|
map.resources :actions, :tags, :map
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
- # map.map '/map', :controller => 'actions', :action => 'm'
+ map.random '/random', :controller => 'actions', :action => 'random'
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.connect '', :controller => 'actions', :action => 'index'
end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
0c7511d4a1b3f80bf1e90d355f840c365aec2500
|
Adding action_type into the mix
|
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 35c4f93..0386ad5 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,39 +1,39 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def map_loader
if [email protected]? && @gmap.onload
{:onload => @gmap.onload_func_name + '()', :onunload => 'GUnload'}
else
{}
end
end
def options_for_action_type_select
[
['All actions', "all"],
- ['Group fundraising', "fundraiser"],
- ['Grassroots petition', "petitions"],
- ['Volunteer opportunity', "volunteer"],
- ['Collective action', "pledge"],
- ['Affinity group', "affinitygroup"]
+ ['Affinity Group'],
+ ['Group Fundraiser'],
+ ['Micro-credit Loan'],
+ ['Petition'],
+ ['Pledged Action']
]
end
def options_for_created_select
[
['Any Time', nil],
['Last 30 days', 30],
['Last 14 days',14],
['Last week', 7],
['Yesterday', 2],
['Today', 1]
]
end
def tag_list_for(action)
action.tags.collect do |tag|
link_to tag.name, tag_path(tag)
end.join(', ')
end
end
diff --git a/app/models/action.rb b/app/models/action.rb
index 457c7e1..8d656db 100644
--- a/app/models/action.rb
+++ b/app/models/action.rb
@@ -1,74 +1,75 @@
class Action < ActiveRecord::Base
include GeoKit::Geocoders
belongs_to :feed
belongs_to :site
acts_as_taggable
acts_as_mappable :lat_column_name => :latitude, :lng_column_name => :longitude
before_save :look_for_tags, :look_for_location, :geocode_lookup, :denormalize
def update_from_feed_item(item)
puts " -- Action: #{item.title}"
self.title = item.title
self.url = item.link
self.description = item.description
self.created_at = item.pubDate if item.pubDate
figure_out_address_from(item)
end
def description=(new_description)
write_attribute(:description, fix_quoted_html(new_description))
end
def self.per_page
10
end
protected
def fix_quoted_html(text)
text.gsub(/\</, '<').gsub(/\>/, '>')
end
def look_for_location
if feed.location_finder and self.description
match = self.description.match(feed.location_finder.to_s)
self.location = match[1] if match and match[1]
puts " Found Location: #{self.location}"
end
end
def look_for_tags
if feed.tag_finder and description
match = description.match(feed.tag_finder.to_s)
self.tag_list = match[1] if match and match[1]
puts " Found Tags: #{self.tag_list}"
end
end
def figure_out_address_from(item)
if item.geo_lat and item.geo_long
self.latitude = item.geo_lat
self.longitude = item.geo_long
end
end
def geocode_lookup
unless location.nil? or location.empty?
result = MultiGeocoder.geocode(location)
if result.success
self.latitude = result.lat
self.longitude = result.lng
puts " Geocoding Successful - #{result}"
end
end
end
def denormalize
self.site_id = self.feed.site_id
+ self.action_type = self.feed.action_type
end
end
diff --git a/app/models/search.rb b/app/models/search.rb
index f2dece0..e905335 100644
--- a/app/models/search.rb
+++ b/app/models/search.rb
@@ -1,109 +1,109 @@
class Search < ActiveRecord::BaseWithoutTable
column :keywords, :string
column :action_type, :string
column :created, :integer
attr_accessor :sites, :kind, :ip_address
validates_inclusion_of :created, :in => %w{ 30 14 7 2 1 }
def results(page)
if kind == 'map'
Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => build_conditions)
else
Action.paginate(:all, :page => page, :order => 'created_at DESC', :conditions => build_conditions)
end
end
def build_conditions
reset_conditions
add_keywords
add_action_type
add_sites
add_created
add_mapping
conditions.join(' AND ')
end
def sites
@sites ||= []
end
def has_site?(site)
sites.include?(site.id.to_s)
end
def reset_conditions
@conditions = []
end
def conditions
@conditions ||= []
end
def add_keywords
unless keywords.nil? or keywords.empty?
keyword_conditions = []
keywords.split(' ').each do |keyword|
keyword_conditions << sanitize(["description LIKE ?", "%#{keyword}%"]) # TODO add url, title
end
conditions << "(" + keyword_conditions.join(' OR ') + ")"
end
end
def add_action_type
unless action_type.nil? or action_type == 'all'
- # conditions << "action_type = '#{action_type}'"
+ conditions << "action_type = '#{action_type}'"
end
end
def add_sites
unless sites.nil? or sites.empty?
conditions << sanitize(["site_id IN (?)", sites])
end
end
def add_created
unless created.nil?
conditions << sanitize(["actions.created_at > ?", created.days.ago])
end
end
def add_mapping
if kind == 'map'
conditions << 'latitude IS NOT NULL and longitude IS NOT NULL'
end
end
def sanitize(arg)
ActiveRecord::Base.send(:sanitize_sql, arg)
end
def current_latitude
current_location.lat || 21.98
end
def current_longitude
current_location.lng || -10.00
end
def current_location
# debugger
@current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
end
def current_ip
ip_address == '127.0.0.1' ? '67.162.124.13' : ip_address
end
# def get_current_location
# location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
# unless location.lat.nil? and location.lng.nil?
# return location.lat, location.lng
# else
# return 41.98, -87.90 # Chicago, an estimate
# end
# end
end
diff --git a/db/migrate/014_add_action_type_to_feed.rb b/db/migrate/014_add_action_type_to_feed.rb
new file mode 100644
index 0000000..6246d8a
--- /dev/null
+++ b/db/migrate/014_add_action_type_to_feed.rb
@@ -0,0 +1,12 @@
+
+require 'active_record/fixtures'
+class AddActionTypeToFeed < ActiveRecord::Migration
+ def self.up
+ add_column :feeds, :action_type, :string
+ Fixtures.create_fixtures('spec/fixtures', 'feeds')
+ end
+
+ def self.down
+ remove_column :feeds, :action_type
+ end
+end
diff --git a/db/migrate/015_add_action_type_to_action.rb b/db/migrate/015_add_action_type_to_action.rb
new file mode 100644
index 0000000..ff4b37f
--- /dev/null
+++ b/db/migrate/015_add_action_type_to_action.rb
@@ -0,0 +1,12 @@
+class AddActionTypeToAction < ActiveRecord::Migration
+ def self.up
+ add_column :actions, :action_type, :string
+ Feed.find(:all).each do |feed|
+ execute("UPDATE actions SET action_type = '#{feed.action_type}' WHERE feed_id = #{feed.id}")
+ end
+ end
+
+ def self.down
+ remove_column :actions, :action_type
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index c7669a0..fc41d04 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,59 +1,61 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of ActiveRecord to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 13) do
+ActiveRecord::Schema.define(:version => 15) do
create_table "actions", :force => true do |t|
t.text "description"
t.string "url"
t.text "title"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "feed_id"
t.decimal "latitude", :precision => 15, :scale => 10
t.decimal "longitude", :precision => 15, :scale => 10
t.string "location"
t.integer "site_id"
+ t.string "action_type"
end
create_table "feeds", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "last_accessed"
t.datetime "created_at"
t.datetime "updated_at"
t.string "tag_finder"
t.integer "site_id"
t.string "location_finder"
+ t.string "action_type"
end
create_table "sites", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type"], :name => "index_taggings_on_taggable_id_and_taggable_type"
create_table "tags", :force => true do |t|
t.string "name"
end
end
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index 6755899..da6c054 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,144 +1,161 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
+ action_type: Group Fundraiser
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
-
+ action_type: Pledged Action
+
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
-
+ action_type: Group Fundraiser
+
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
+ action_type: Affinity Group
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
-
+ action_type: Pledged Action
+
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
+ action_type: Group Fundraiser
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
+ action_type: Group Fundraiser
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
location_finder:
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
-
+ action_type: Petition
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
# tag_finder:
# location_finder:
# last_accessed: <%= 1.day.ago %>
# site: the_point
+ # action_type: Pledged Action
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
+ action_type: Pledged Action
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
-
+ action_type: Pledged Action
+
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
+ action_type: Group Fundraiser
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
-
+ action_type: Group Fundraiser
+
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
+ action_type: Group Fundraiser
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
-
+ action_type: Micro-credit Loan
+
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/pca/badgefeed.aspx
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
+ action_type: Group Fundraiser
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
location_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
+ action_type: Group Fundraiser
zazengo:
name: Latest Zazengo Projects
url: http://www.zazengo.com/projects.rss
tag_finder: "<span class=\"issues\">([\w\s,]+)</span>"
location_finder: "<span class=\"street-address\">([\w\s,]+)</span>"
last_accessed: <%= 1.day.ago %>
- site: zazengo
\ No newline at end of file
+ site: zazengo
+ action_type: Affinity Group
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
ef18e938903d09cc650671a530f3c860c4137aec
|
Adding in header and footers
|
diff --git a/app/views/layouts/_footer.html.erb b/app/views/layouts/_footer.html.erb
new file mode 100644
index 0000000..269b609
--- /dev/null
+++ b/app/views/layouts/_footer.html.erb
@@ -0,0 +1,14 @@
+<div id="footer">
+ <p><a href="http://creativecommons.org/licenses/by-nc-sa/2.5/"><img src="/images/creativecommons.gif" border="0" align="left" style="margin:3px 10px 20px 0px"></a>© Copyright 2008 Peter Deitz and Cameron Booth. <a href="http://creativecommons.org/licenses/by-nc-sa/2.5/">Some Rights Reserved</a>.</p>
+ <p><em>This mashup uses Ruby on Rails. The project </em><em>lead is Peter Deitz, <a href="http://www.socialactions.com">Social Actions</a>.</em><em> </em><em>The lead engineer is Cameron Booth, <a href="http://www.cdbdesign.net">CDBdesign.net</a></em>.
+</div>
+
+<script type="text/javascript">
+var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
+document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
+</script>
+<script type="text/javascript">
+var pageTracker = _gat._getTracker("UA-772094-6");
+pageTracker._initData();
+pageTracker._trackPageview();
+</script>
\ No newline at end of file
diff --git a/app/views/layouts/_header.html.erb b/app/views/layouts/_header.html.erb
new file mode 100644
index 0000000..54b7beb
--- /dev/null
+++ b/app/views/layouts/_header.html.erb
@@ -0,0 +1,29 @@
+<div id="header">
+
+ <h2>A Mashup of 29+ Social Action Platforms</h2>
+
+ <div style="float:right;width:360x;margin-left:15px;margin-top:10px"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="playerLoader" width="360" height="301" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
+ <param name="movie" value="http://farm.sproutbuilder.com/112320/load/uwBkG7aMAWbz_4HQ.swf"/>
+ <param name="quality" value="high"/>
+ <param name="allowScriptAccess" value="always"/>
+ <param name="allowFullScreen" value="true"/>
+ <param name="wmode" value="transparent"/>
+ <embed src="http://farm.sproutbuilder.com/112320/load/uwBkG7aMAWbz_4HQ.swf" width="360" height="301" name="playerLoader" align="middle" wmode="transparent" play="true" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"/>
+ </object><img style="visibility:hidden;width:0px;height:0px;" border=0 width=0 height=0 src="http://counters.gigya.com/wildfire/CIMP/Jmx*PTEyMDU2OTU5OTAwMDImcHQ9MTIwNTY5NjA3Nzc5NyZwPTEyMDc*MSZkPTExMjM4MyZuPQ==.jpg" /></div>
+
+ <p style="margin-top:10px">Hello NetSquared Mashup Voters,</p>
+ <p>You have arrived on the initial version of <strong><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">"A Mashup of 29+ Social Action Platforms."</a></strong></p><p>Please test drive our mashup using the form below.</p>
+
+ <p>This version of the mashup allows you to</p>
+ <ul style="margin-top:4px;margin-bottom:4px">
+ <li><strong>Search across 17 social action platforms for 5 kinds of campaigns</strong>: group fundraisers, pledged actions, petitions, micro-credit loans, and affinity groups.</li>
+ <li><strong>Map peer-to-peer social change campaigns</strong> using the Google Maps API.</li>
+ </ul>
+ <p></p>
+ <p><em>How can we make this mashup better</em>? </p>
+
+ <p>Please send your feedback to <a href="mailto:[email protected]"><strong>[email protected]</strong></a> or <span class="style1"><a href="http://www.netsquared.org/2008/conference/projects/mashup-social-actions">post a comment</a>.</span> </p>
+ <p>Thank you for your support!</p>
+ <img style="visibility:hidden;width:0px;height:0px;" border=0 width=0 height=0 src="http://counters.gigya.com/wildfire/CIMP/Jmx*PTEyMDU2OTU5OTAwMDImcHQ9MTIwNTY5NTk5MzA2NCZwPTEyMDc*MSZkPTExMjM4MyZuPQ==.jpg" />
+
+</div>
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 94862f9..303764e 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,12 +1,16 @@
!!! 1.0
%html{"xmlns"=>"http://www.w3.org/1999/xhtml", "xml:lang"=>"en"}
%head
%meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}/
%title A Mashup of 29+ Social Action Platforms
= stylesheet_link_tag 'main', 'facebox'
= javascript_include_tag 'jquery', 'facebox', 'application'
= yield :map_headers
%body{ map_loader }
+
+ = render :partial => 'layouts/header'
- = yield
\ No newline at end of file
+ = yield
+
+ = render :partial => 'layouts/footer'
\ No newline at end of file
diff --git a/public/images/creativecommons.gif b/public/images/creativecommons.gif
new file mode 100644
index 0000000..d84265c
Binary files /dev/null and b/public/images/creativecommons.gif differ
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index 50d9b45..de13e44 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,156 +1,173 @@
body
:font-family Arial, Helvetica, sans-serif
a
:color #3366cc
:text-decoration none
h2
:margin 0px 0px 5px 0px
p
- :margin 3px 3px 0px 3px
+ :margin 3px
+ :margin-top 5px
// Block Elements
#search_results, #tag_cloud, #facebox
:width 710px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 0px 10px
// Search box
#search_box
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:background-color #e9f3f1
:padding 10px 10px 30px 10px
table
td
:padding-right 5px
:padding-top 10px
.first
td
:padding-top 0
.platform_select
:width 170px
:float left
:margin-top 10px
// Results Elements
.action
:width 700px
:margin-bottom 30px
.action-title
:margin-top 5px
:margin-bottom 5px
:font-size 160%
:display block
.action-source
:width 320px
:float right
:margin-left 25px
:text-align right
.action-goal
.action-location
.action-tags
.action-url
:margin-top 10px
:display block
:color #ff6600
.action-url a
.action-url a:hover
.action-byline
.action-byline a
:font-weight bold
.action-byline a:hover
.action-created
.action-type
:font-style italic
// Pagination
.pagination
:padding 3px
:margin 3px
.pagination a
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:text-decoration none
:color #3366cc
.pagination a:hover, .pagination a:active
:border 1px solid #3366cc
:color #000
.pagination span.current
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:font-weight bold
:background-color #3366cc
:color #FFF
.pagination span.disabled
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #eee
:color #ddd
// Map
#gmap
:height 400px
:width 710px
:margin-top 20px
.map-action
:font-size 12px
:width 200px
:border 1px red
:font-family Arial, Helvetica, sans-serif
.title
.location
:font-size 80%
.byline
:font-size 80%
.created
:font-size 80%
// Tags
.tag1
:font-size 1.0em
.tag2
:font-size 1.2em
.tag3
:font-size 1.4em
.tag4
:font-size 1.6em
// Facebox Popup
#facebox
.action-title
:color #3366cc
.description
:height 200px
:overflow auto
- :clear both
\ No newline at end of file
+ :clear both
+
+// Header
+#header
+ :width 700px
+ :font-family Arial, Helvetica, sans-serif
+ :font-size 14px
+ :color #000
+ :padding 10px 10px 20px 10px
+
+// Footer
+#footer
+ :width 700px
+ :font-family Arial, Helvetica, sans-serif
+ :font-size 14px
+ :color #000
+ :padding 10px 10px 20px 10px
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
d8a5f06a83b85e90c9e4b325c14c31c2bd47e0b9
|
Showing the tag cloud a bit nicer, only tags with more than 1 action associated, and alphabetical
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index 3412c37..5df06f0 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,22 +1,21 @@
class ActionsController < ApplicationController
def index
@search = Search.new(params[:search])
@actions = @search.results(params[:page])
respond_to do |format|
format.html
format.xml
end
-
end
def show
@action = Action.find(params[:id])
respond_to do |format|
format.html { render :layout => false}
format.xml
end
end
end
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb
index c8eb2a5..63a5bfc 100644
--- a/app/controllers/tags_controller.rb
+++ b/app/controllers/tags_controller.rb
@@ -1,20 +1,22 @@
class TagsController < ApplicationController
before_filter :load_tags, :load_search
def index
end
def show
@tag = Tag.find_by_name(params[:id])
@actions = Action.paginate(:all, :page => params[:page], :include => 'taggings', :conditions => ['taggings.tag_id = ?', @tag.id], :order => 'actions.created_at DESC')
end
private
def load_tags
- @tags = Action.tag_counts
+ @tags = Action.tag_counts(:order => 'tags.name', :at_least => 2)
+ # :order - A piece of SQL to order by. Eg 'tags.count desc' or 'taggings.created_at desc'
+
end
def load_search
@search = Search.new(params[:search])
end
end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
9e0c15c27c676acaa886014adfa1546c3e241d0c
|
Bringing mapping into proper search
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index f33891a..3412c37 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,24 +1,22 @@
class ActionsController < ApplicationController
def index
- redirect_to '/map' and return false if params[:commit] == 'Google Map'
- redirect_to '/tags' and return false if params[:commit] == 'Tag Cloud'
@search = Search.new(params[:search])
- @actions = Action.paginate(:all, :page => params[:page], :order => 'created_at DESC', :conditions => @search.build_conditions)
+ @actions = @search.results(params[:page])
respond_to do |format|
format.html
format.xml
end
end
def show
@action = Action.find(params[:id])
respond_to do |format|
format.html { render :layout => false}
format.xml
end
end
end
diff --git a/app/controllers/map_controller.rb b/app/controllers/map_controller.rb
index 3764e58..b9e4457 100644
--- a/app/controllers/map_controller.rb
+++ b/app/controllers/map_controller.rb
@@ -1,85 +1,56 @@
class MapController < ApplicationController
- before_filter :setup_map
-
include ActionView::Helpers::JavaScriptHelper
def index
- @search = Search.new(params[:search])
- actions = Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => 'latitude IS NOT NULL and longitude IS NOT NULL')
- actions.each do |action|
+ @search = Search.new(params[:search].merge(:kind => 'map', :ip_address => request.remote_ip))
+ @actions = @search.results(params[:page])
+ setup_map
+ @actions.each do |action|
# now for the lat and lng of the marker we want to add.
marker_lat = action.latitude
marker_lng = action.longitude
@gmap.use_marker_code('createWithIconAndHtml', :with_args => [:point, :html, :icon_image])
incident_point = Mappa::GLatLng.new(:lat => marker_lat, :lng => marker_lng)
@gmap.add_marker(:point => incident_point, :create_with => 'createWithIconAndHtml', :html => "'#{escape_javascript(small_map_view_of(action))}'", :icon_image => "'/images/marker.png'")
end
- # render :template => "map/index"
-
-
end
protected
def setup_map
@gmap = Mappa::GMap.new()
@gmap.api_key = 'ABQIAAAAkGYfBpkZ5yYF_f9sthqC5BTJQa0g3IQ9GZqIMmInSLzwtGDKaBRu7u3V_uePSTUgmfHvnGnehFX3-A'
# set the longitude and latitiude of the centre point of our map
- @gmap.lat, @gmap.lng = current_latitude, current_longitude
+ @gmap.lat, @gmap.lng = @search.current_latitude, @search.current_longitude
# set the zoom level of our map. This number is in the range of 1-18. 1 is lowest zoom and 18 is highest
# we've picked a nice middling 12.
- @gmap.zoom = 4
+ @gmap.zoom = 2
@gmap.add_control(:control => 'small')
@gmap.add_control(:control => 'type')
@gmap.add_control(:control => 'overview')
end
-
- def current_latitude
- current_location.lat || 41.98
- end
-
- def current_longitude
- current_location.lng || -87.90
- end
-
- def current_location
- # debugger
- @current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
- end
-
- def current_ip
- request.remote_ip == '127.0.0.1' ? '67.162.124.13' : request.remote_ip
- end
-
- # def get_current_location
- # location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
- # unless location.lat.nil? and location.lng.nil?
- # return location.lat, location.lng
- # else
- # return 41.98, -87.90 # Chicago, an estimate
- # end
- # end
+
def small_map_view_of(action)
%{
<div class="map-action">
<div class="title">
- <a href="/actions/#{action.id}">#{action.title}</a>
+ <a href="#{action.url}" target="_blank">#{action.title}</a>
</div>
<div class="location">
<b>Location:</b> #{action.location}
</div>
<div class="byline">
- <b>Created on:</b> <a href="#{action.site.url}">#{action.site.name}</a>
+ <b>Created on:</b> <a href="#{action.site.url}" target="_blank">#{action.site.name}</a>
</div>
<div class="created">
<b>Created at:</b> #{action.created_at.to_s(:default)}
</div>
</div>
}
end
end
diff --git a/app/models/search.rb b/app/models/search.rb
index cd32527..f2dece0 100644
--- a/app/models/search.rb
+++ b/app/models/search.rb
@@ -1,65 +1,109 @@
class Search < ActiveRecord::BaseWithoutTable
column :keywords, :string
column :action_type, :string
column :created, :integer
- attr_accessor :sites
+ attr_accessor :sites, :kind, :ip_address
validates_inclusion_of :created, :in => %w{ 30 14 7 2 1 }
+ def results(page)
+ if kind == 'map'
+ Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => build_conditions)
+ else
+ Action.paginate(:all, :page => page, :order => 'created_at DESC', :conditions => build_conditions)
+ end
+ end
+
def build_conditions
reset_conditions
add_keywords
add_action_type
add_sites
add_created
+ add_mapping
conditions.join(' AND ')
end
def sites
@sites ||= []
end
def has_site?(site)
sites.include?(site.id.to_s)
end
def reset_conditions
@conditions = []
end
def conditions
@conditions ||= []
end
def add_keywords
unless keywords.nil? or keywords.empty?
keyword_conditions = []
keywords.split(' ').each do |keyword|
keyword_conditions << sanitize(["description LIKE ?", "%#{keyword}%"]) # TODO add url, title
end
conditions << "(" + keyword_conditions.join(' OR ') + ")"
end
end
def add_action_type
unless action_type.nil? or action_type == 'all'
# conditions << "action_type = '#{action_type}'"
end
end
def add_sites
unless sites.nil? or sites.empty?
conditions << sanitize(["site_id IN (?)", sites])
end
end
def add_created
unless created.nil?
conditions << sanitize(["actions.created_at > ?", created.days.ago])
end
end
+ def add_mapping
+ if kind == 'map'
+ conditions << 'latitude IS NOT NULL and longitude IS NOT NULL'
+ end
+ end
+
def sanitize(arg)
ActiveRecord::Base.send(:sanitize_sql, arg)
end
+
+
+ def current_latitude
+ current_location.lat || 21.98
+ end
+
+ def current_longitude
+ current_location.lng || -10.00
+ end
+
+ def current_location
+ # debugger
+ @current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
+ end
+
+ def current_ip
+ ip_address == '127.0.0.1' ? '67.162.124.13' : ip_address
+ end
+
+ # def get_current_location
+ # location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
+ # unless location.lat.nil? and location.lng.nil?
+ # return location.lat, location.lng
+ # else
+ # return 41.98, -87.90 # Chicago, an estimate
+ # end
+ # end
+
+
end
diff --git a/app/views/actions/_search_form.html.haml b/app/views/actions/_search_form.html.haml
index 8f60c3c..0c248a4 100644
--- a/app/views/actions/_search_form.html.haml
+++ b/app/views/actions/_search_form.html.haml
@@ -1,33 +1,33 @@
#search_box
%h2 Find an Action
- form_for @search, :url => actions_path, :html => {:method => :get} do |f|
%table{ :border=>"0", :cellpadding=>"0", :cellspacing=>"0" }
%tr.first
%td Search Term:
%td= f.text_field :keywords, :size => 22
%td
= submit_tag 'Search'
- = submit_tag 'Google Map'
+ = submit_tag 'Google Map', :onclick => "$('#new_search').attr('action', '#{map_index_path}')"
- = submit_tag 'Tag Cloud'
+ = submit_tag 'Tag Cloud', :onclick => "$('#new_search').attr('action', '#{tags_path}')"
= submit_tag 'Random'
%tr
%td Type of Action:
%td= f.select :action_type, options_for_action_type_select
%td
Created:
= f.select :created, options_for_created_select
- Site.find(:all, :order => :name).each_slice(4) do |sites|
.platform_select
- sites.each do |site|
= check_box_tag 'search[sites][]', site.id, @search.has_site?(site)
= site.name
%br/
%br{:clear => 'all'}/
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index 2b5d222..f78278f 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,38 +1,38 @@
ActionController::Routing::Routes.draw do |map|
map.resources :actions, :tags, :map
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
-
+ # map.map '/map', :controller => 'actions', :action => 'm'
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.connect '', :controller => 'actions', :action => 'index'
end
diff --git a/db/migrate/013_site_id_fix_to_old_actions.rb b/db/migrate/013_site_id_fix_to_old_actions.rb
new file mode 100644
index 0000000..5cc6ed3
--- /dev/null
+++ b/db/migrate/013_site_id_fix_to_old_actions.rb
@@ -0,0 +1,11 @@
+class SiteIdFixToOldActions < ActiveRecord::Migration
+ def self.up
+ # Need to fix the ones that end up with a blank site because they've already been crawled and lost in the RSS
+ Action.find(:all, :conditions => 'site_id IS NULL').each do |action|
+ action.save!
+ end
+ end
+
+ def self.down
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index fe95d50..c7669a0 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,59 +1,59 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of ActiveRecord to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 12) do
+ActiveRecord::Schema.define(:version => 13) do
create_table "actions", :force => true do |t|
t.text "description"
t.string "url"
t.text "title"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "feed_id"
t.decimal "latitude", :precision => 15, :scale => 10
t.decimal "longitude", :precision => 15, :scale => 10
t.string "location"
t.integer "site_id"
end
create_table "feeds", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "last_accessed"
t.datetime "created_at"
t.datetime "updated_at"
t.string "tag_finder"
t.integer "site_id"
t.string "location_finder"
end
create_table "sites", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type"], :name => "index_taggings_on_taggable_id_and_taggable_type"
create_table "tags", :force => true do |t|
t.string "name"
end
end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
adcc5e454d4df0a23a3f402113cb67c4bd59e013
|
Adding some denormalization and then making the site checkboxes work on the search
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index bc61cb3..f33891a 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,24 +1,24 @@
class ActionsController < ApplicationController
def index
redirect_to '/map' and return false if params[:commit] == 'Google Map'
redirect_to '/tags' and return false if params[:commit] == 'Tag Cloud'
@search = Search.new(params[:search])
- @actions = Action.paginate(:all, :page => params[:page], :order => 'created_at DESC', :conditions => @search.build_conditions, :include => :feed)
+ @actions = Action.paginate(:all, :page => params[:page], :order => 'created_at DESC', :conditions => @search.build_conditions)
respond_to do |format|
format.html
format.xml
end
end
def show
@action = Action.find(params[:id])
respond_to do |format|
format.html { render :layout => false}
format.xml
end
end
end
diff --git a/app/models/action.rb b/app/models/action.rb
index 1d4ac60..457c7e1 100644
--- a/app/models/action.rb
+++ b/app/models/action.rb
@@ -1,71 +1,74 @@
class Action < ActiveRecord::Base
include GeoKit::Geocoders
-
belongs_to :feed
- delegate :site, :to => :feed
+ belongs_to :site
acts_as_taggable
acts_as_mappable :lat_column_name => :latitude, :lng_column_name => :longitude
- before_save :look_for_tags, :look_for_location, :geocode_lookup
+ before_save :look_for_tags, :look_for_location, :geocode_lookup, :denormalize
def update_from_feed_item(item)
puts " -- Action: #{item.title}"
self.title = item.title
self.url = item.link
self.description = item.description
self.created_at = item.pubDate if item.pubDate
figure_out_address_from(item)
end
def description=(new_description)
write_attribute(:description, fix_quoted_html(new_description))
end
def self.per_page
10
end
protected
def fix_quoted_html(text)
text.gsub(/\</, '<').gsub(/\>/, '>')
end
def look_for_location
if feed.location_finder and self.description
match = self.description.match(feed.location_finder.to_s)
self.location = match[1] if match and match[1]
puts " Found Location: #{self.location}"
end
end
def look_for_tags
if feed.tag_finder and description
match = description.match(feed.tag_finder.to_s)
self.tag_list = match[1] if match and match[1]
puts " Found Tags: #{self.tag_list}"
end
end
def figure_out_address_from(item)
if item.geo_lat and item.geo_long
self.latitude = item.geo_lat
self.longitude = item.geo_long
end
end
def geocode_lookup
unless location.nil? or location.empty?
result = MultiGeocoder.geocode(location)
if result.success
self.latitude = result.lat
self.longitude = result.lng
puts " Geocoding Successful - #{result}"
end
end
end
+ def denormalize
+ self.site_id = self.feed.site_id
+ end
+
end
diff --git a/app/models/search.rb b/app/models/search.rb
index f4471de..cd32527 100644
--- a/app/models/search.rb
+++ b/app/models/search.rb
@@ -1,53 +1,65 @@
class Search < ActiveRecord::BaseWithoutTable
column :keywords, :string
column :action_type, :string
column :created, :integer
attr_accessor :sites
validates_inclusion_of :created, :in => %w{ 30 14 7 2 1 }
def build_conditions
reset_conditions
add_keywords
add_action_type
add_sites
add_created
conditions.join(' AND ')
end
+
+ def sites
+ @sites ||= []
+ end
+
+ def has_site?(site)
+ sites.include?(site.id.to_s)
+ end
def reset_conditions
@conditions = []
end
def conditions
@conditions ||= []
end
def add_keywords
unless keywords.nil? or keywords.empty?
keyword_conditions = []
keywords.split(' ').each do |keyword|
- keyword_conditions << ActiveRecord::Base.send(:sanitize_sql, ["description LIKE ?", "%#{keyword}%"]) # TODO add url, title
+ keyword_conditions << sanitize(["description LIKE ?", "%#{keyword}%"]) # TODO add url, title
end
conditions << "(" + keyword_conditions.join(' OR ') + ")"
end
end
def add_action_type
unless action_type.nil? or action_type == 'all'
# conditions << "action_type = '#{action_type}'"
end
end
def add_sites
unless sites.nil? or sites.empty?
- # conditions << "sites IN (#{sites.join(',')})"
+ conditions << sanitize(["site_id IN (?)", sites])
end
end
def add_created
unless created.nil?
- conditions << ActiveRecord::Base.send(:sanitize_sql, ["actions.created_at > ?", created.days.ago])
+ conditions << sanitize(["actions.created_at > ?", created.days.ago])
end
end
+
+ def sanitize(arg)
+ ActiveRecord::Base.send(:sanitize_sql, arg)
+ end
end
diff --git a/app/views/actions/_search_form.html.haml b/app/views/actions/_search_form.html.haml
index 565d551..8f60c3c 100644
--- a/app/views/actions/_search_form.html.haml
+++ b/app/views/actions/_search_form.html.haml
@@ -1,33 +1,33 @@
#search_box
%h2 Find an Action
- form_for @search, :url => actions_path, :html => {:method => :get} do |f|
%table{ :border=>"0", :cellpadding=>"0", :cellspacing=>"0" }
%tr.first
%td Search Term:
%td= f.text_field :keywords, :size => 22
%td
= submit_tag 'Search'
= submit_tag 'Google Map'
= submit_tag 'Tag Cloud'
= submit_tag 'Random'
%tr
%td Type of Action:
%td= f.select :action_type, options_for_action_type_select
%td
Created:
= f.select :created, options_for_created_select
- Site.find(:all, :order => :name).each_slice(4) do |sites|
.platform_select
- sites.each do |site|
- = check_box_tag 'search[sites][]', site.id, true
+ = check_box_tag 'search[sites][]', site.id, @search.has_site?(site)
= site.name
%br/
%br{:clear => 'all'}/
\ No newline at end of file
diff --git a/db/migrate/012_add_site_id_to_action.rb b/db/migrate/012_add_site_id_to_action.rb
new file mode 100644
index 0000000..5c6e9e3
--- /dev/null
+++ b/db/migrate/012_add_site_id_to_action.rb
@@ -0,0 +1,9 @@
+class AddSiteIdToAction < ActiveRecord::Migration
+ def self.up
+ add_column :actions, :site_id, :integer
+ end
+
+ def self.down
+ remove_column :actions, :site_id
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 1428a33..fe95d50 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,58 +1,59 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of ActiveRecord to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 11) do
+ActiveRecord::Schema.define(:version => 12) do
create_table "actions", :force => true do |t|
t.text "description"
t.string "url"
t.text "title"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "feed_id"
t.decimal "latitude", :precision => 15, :scale => 10
t.decimal "longitude", :precision => 15, :scale => 10
t.string "location"
+ t.integer "site_id"
end
create_table "feeds", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "last_accessed"
t.datetime "created_at"
t.datetime "updated_at"
t.string "tag_finder"
t.integer "site_id"
t.string "location_finder"
end
create_table "sites", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type"], :name => "index_taggings_on_taggable_id_and_taggable_type"
create_table "tags", :force => true do |t|
t.string "name"
end
end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
e4ae200b9ffe5fed94d9e1982c009875529d0552
|
Small adjustment to site name
|
diff --git a/spec/fixtures/sites.yml b/spec/fixtures/sites.yml
index 245dac3..c0198e6 100644
--- a/spec/fixtures/sites.yml
+++ b/spec/fixtures/sites.yml
@@ -1,62 +1,62 @@
global_giving:
name: GlobalGiving
url: http://www.globalgiving.com
pledge_bank:
name: PledgeBank
url: http://www.pledgebank.com
change_org:
name: Change.org
url: http://www.change.org
razoo:
- name: Razoo Acts
+ name: Razoo
url: http://beta.razoo.com
democracy_in_action:
name: DemocracyinAction
url: http://www.democracyinaction.org
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
#
# last_accessed: <%= 1.day.ago %>
give_meaning:
name: GiveMeaning
url: http://www.givemeaning.com
changing_the_present:
name: ChangingthePresent
url: http://www.changingthepresent.com
fundable:
name: Fundable
url: http://www.fundable.org
bring_light:
name: BringLight
url: http://www.bringlight.com
kiva:
name: Kiva
url: http://www.kiva.org
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org
first_giving:
name: Firstgiving
url: http://www.firstgiving.com
zazengo:
name: Zazengo
url: http://www.zazengo.com
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
3fbc14b40ce47e6fb92b9d559f5ed39ff869514d
|
Small adjustment to sites.yml
|
diff --git a/spec/fixtures/sites.yml b/spec/fixtures/sites.yml
index 1cc510c..245dac3 100644
--- a/spec/fixtures/sites.yml
+++ b/spec/fixtures/sites.yml
@@ -1,62 +1,62 @@
global_giving:
name: GlobalGiving
url: http://www.globalgiving.com
pledge_bank:
name: PledgeBank
url: http://www.pledgebank.com
change_org:
- name: Change.org Giving Networks
+ name: Change.org
url: http://www.change.org
razoo:
name: Razoo Acts
url: http://beta.razoo.com
democracy_in_action:
name: DemocracyinAction
url: http://www.democracyinaction.org
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
#
# last_accessed: <%= 1.day.ago %>
give_meaning:
name: GiveMeaning
url: http://www.givemeaning.com
changing_the_present:
name: ChangingthePresent
url: http://www.changingthepresent.com
fundable:
name: Fundable
url: http://www.fundable.org
bring_light:
name: BringLight
url: http://www.bringlight.com
kiva:
name: Kiva
url: http://www.kiva.org
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org
first_giving:
name: Firstgiving
url: http://www.firstgiving.com
zazengo:
name: Zazengo
url: http://www.zazengo.com
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
667a45416780e191245f30e4fd0b576540e11d7c
|
Fixing a few errors tests would have caught
|
diff --git a/app/controllers/map_controller.rb b/app/controllers/map_controller.rb
index d1582d3..3764e58 100644
--- a/app/controllers/map_controller.rb
+++ b/app/controllers/map_controller.rb
@@ -1,84 +1,85 @@
class MapController < ApplicationController
before_filter :setup_map
include ActionView::Helpers::JavaScriptHelper
def index
+ @search = Search.new(params[:search])
actions = Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => 'latitude IS NOT NULL and longitude IS NOT NULL')
actions.each do |action|
# now for the lat and lng of the marker we want to add.
marker_lat = action.latitude
marker_lng = action.longitude
@gmap.use_marker_code('createWithIconAndHtml', :with_args => [:point, :html, :icon_image])
incident_point = Mappa::GLatLng.new(:lat => marker_lat, :lng => marker_lng)
@gmap.add_marker(:point => incident_point, :create_with => 'createWithIconAndHtml', :html => "'#{escape_javascript(small_map_view_of(action))}'", :icon_image => "'/images/marker.png'")
end
# render :template => "map/index"
end
protected
def setup_map
@gmap = Mappa::GMap.new()
@gmap.api_key = 'ABQIAAAAkGYfBpkZ5yYF_f9sthqC5BTJQa0g3IQ9GZqIMmInSLzwtGDKaBRu7u3V_uePSTUgmfHvnGnehFX3-A'
# set the longitude and latitiude of the centre point of our map
@gmap.lat, @gmap.lng = current_latitude, current_longitude
# set the zoom level of our map. This number is in the range of 1-18. 1 is lowest zoom and 18 is highest
# we've picked a nice middling 12.
@gmap.zoom = 4
@gmap.add_control(:control => 'small')
@gmap.add_control(:control => 'type')
@gmap.add_control(:control => 'overview')
end
def current_latitude
current_location.lat || 41.98
end
def current_longitude
current_location.lng || -87.90
end
def current_location
# debugger
@current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
end
def current_ip
request.remote_ip == '127.0.0.1' ? '67.162.124.13' : request.remote_ip
end
# def get_current_location
# location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
# unless location.lat.nil? and location.lng.nil?
# return location.lat, location.lng
# else
# return 41.98, -87.90 # Chicago, an estimate
# end
# end
def small_map_view_of(action)
%{
<div class="map-action">
<div class="title">
<a href="/actions/#{action.id}">#{action.title}</a>
</div>
<div class="location">
<b>Location:</b> #{action.location}
</div>
<div class="byline">
<b>Created on:</b> <a href="#{action.site.url}">#{action.site.name}</a>
</div>
<div class="created">
<b>Created at:</b> #{action.created_at.to_s(:default)}
</div>
</div>
}
end
end
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb
index 41ea2a3..c8eb2a5 100644
--- a/app/controllers/tags_controller.rb
+++ b/app/controllers/tags_controller.rb
@@ -1,16 +1,20 @@
class TagsController < ApplicationController
- before_filter :load_tags
+ before_filter :load_tags, :load_search
def index
end
def show
@tag = Tag.find_by_name(params[:id])
@actions = Action.paginate(:all, :page => params[:page], :include => 'taggings', :conditions => ['taggings.tag_id = ?', @tag.id], :order => 'actions.created_at DESC')
end
private
def load_tags
@tags = Action.tag_counts
end
+
+ def load_search
+ @search = Search.new(params[:search])
+ end
end
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index 594b42d..50d9b45 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,155 +1,156 @@
body
:font-family Arial, Helvetica, sans-serif
a
:color #3366cc
:text-decoration none
h2
:margin 0px 0px 5px 0px
p
:margin 3px 3px 0px 3px
// Block Elements
#search_results, #tag_cloud, #facebox
:width 710px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 0px 10px
// Search box
#search_box
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:background-color #e9f3f1
:padding 10px 10px 30px 10px
table
td
:padding-right 5px
:padding-top 10px
.first
td
:padding-top 0
.platform_select
:width 170px
:float left
:margin-top 10px
// Results Elements
.action
:width 700px
:margin-bottom 30px
.action-title
:margin-top 5px
:margin-bottom 5px
:font-size 160%
:display block
.action-source
:width 320px
:float right
:margin-left 25px
:text-align right
.action-goal
.action-location
.action-tags
.action-url
:margin-top 10px
:display block
:color #ff6600
.action-url a
.action-url a:hover
.action-byline
.action-byline a
:font-weight bold
.action-byline a:hover
.action-created
.action-type
:font-style italic
// Pagination
.pagination
:padding 3px
:margin 3px
.pagination a
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:text-decoration none
:color #3366cc
.pagination a:hover, .pagination a:active
:border 1px solid #3366cc
:color #000
.pagination span.current
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:font-weight bold
:background-color #3366cc
:color #FFF
.pagination span.disabled
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #eee
:color #ddd
// Map
#gmap
:height 400px
:width 710px
:margin-top 20px
.map-action
:font-size 12px
:width 200px
:border 1px red
:font-family Arial, Helvetica, sans-serif
.title
.location
:font-size 80%
.byline
:font-size 80%
.created
:font-size 80%
// Tags
.tag1
:font-size 1.0em
.tag2
:font-size 1.2em
.tag3
:font-size 1.4em
.tag4
:font-size 1.6em
// Facebox Popup
#facebox
.action-title
:color #3366cc
.description
:height 200px
- :overflow auto
\ No newline at end of file
+ :overflow auto
+ :clear both
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
1f12f9fbc08b19b97409957885f4f050e8a06f60
|
Adding a facebox popup thingy for viewing actions. Looks nice.
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index 1cd284f..bc61cb3 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,24 +1,24 @@
class ActionsController < ApplicationController
def index
redirect_to '/map' and return false if params[:commit] == 'Google Map'
redirect_to '/tags' and return false if params[:commit] == 'Tag Cloud'
@search = Search.new(params[:search])
@actions = Action.paginate(:all, :page => params[:page], :order => 'created_at DESC', :conditions => @search.build_conditions, :include => :feed)
respond_to do |format|
format.html
format.xml
end
end
def show
@action = Action.find(params[:id])
respond_to do |format|
- format.html
+ format.html { render :layout => false}
format.xml
end
end
end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 883940a..35c4f93 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,39 +1,39 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def map_loader
if [email protected]? && @gmap.onload
{:onload => @gmap.onload_func_name + '()', :onunload => 'GUnload'}
else
{}
end
end
def options_for_action_type_select
[
['All actions', "all"],
['Group fundraising', "fundraiser"],
['Grassroots petition', "petitions"],
['Volunteer opportunity', "volunteer"],
['Collective action', "pledge"],
['Affinity group', "affinitygroup"]
]
end
def options_for_created_select
[
['Any Time', nil],
- ['Last 30 days', "30"],
- ['Last 14 days',"14"],
- ['Last week', "7"],
- ['Yesterday', "2"],
- ['Today', "1"]
+ ['Last 30 days', 30],
+ ['Last 14 days',14],
+ ['Last week', 7],
+ ['Yesterday', 2],
+ ['Today', 1]
]
end
def tag_list_for(action)
action.tags.collect do |tag|
link_to tag.name, tag_path(tag)
end.join(', ')
end
end
diff --git a/app/views/actions/_action.html.haml b/app/views/actions/_action.html.haml
index fdfd503..d229798 100644
--- a/app/views/actions/_action.html.haml
+++ b/app/views/actions/_action.html.haml
@@ -1,30 +1,30 @@
%div[action]
- = link_to action.title, action_path(action), :class => 'action-title'
+ = link_to action.title, action_path(action), :class => 'action-title', :rel => 'facebox'
.action-source
%span{:class => 'action-byline'}
Created on
= link_to action.site.name, action.site.url
by
= link_to 'TODO', ''
%br/
%span{:class => 'action-created'}
= action.created_at.to_s(:default)
%br/
%span{:class => 'action-type'} TODO
%span{:class => 'action-goal'}
%strong
Goal:
TODO
%br/
%span{:class => 'action-location'}
%strong
Location:
= action.location
%br/
%span{:class => 'action-tags'}
%strong
Tags:
= tag_list_for action
%br/
= link_to action.url, action.url, :class => 'action-url'
diff --git a/app/views/actions/_search_form.html.haml b/app/views/actions/_search_form.html.haml
index 12596bd..565d551 100644
--- a/app/views/actions/_search_form.html.haml
+++ b/app/views/actions/_search_form.html.haml
@@ -1,37 +1,33 @@
#search_box
%h2 Find an Action
- form_for @search, :url => actions_path, :html => {:method => :get} do |f|
%table{ :border=>"0", :cellpadding=>"0", :cellspacing=>"0" }
%tr.first
%td Search Term:
%td= f.text_field :keywords, :size => 22
%td
= submit_tag 'Search'
= submit_tag 'Google Map'
= submit_tag 'Tag Cloud'
= submit_tag 'Random'
%tr
%td Type of Action:
%td= f.select :action_type, options_for_action_type_select
%td
Created:
= f.select :created, options_for_created_select
- Site.find(:all, :order => :name).each_slice(4) do |sites|
.platform_select
- sites.each do |site|
- /= f.check_box 'sites[]', site.id, true
= check_box_tag 'search[sites][]', site.id, true
= site.name
%br/
-
- = debug @search
- = @search.build_conditions
%br{:clear => 'all'}/
\ No newline at end of file
diff --git a/app/views/actions/show.html.haml b/app/views/actions/show.html.haml
index 272a3e8..585f0e4 100644
--- a/app/views/actions/show.html.haml
+++ b/app/views/actions/show.html.haml
@@ -1,22 +1,33 @@
-%h1 Viewing action
-
%div[@action]
- %h2= @action.title
+ .action-title
+ = @action.title
+ .action-source
+ %span{:class => 'action-byline'}
+ Created on
+ = link_to @action.site.name, @action.site.url
+ by
+ = link_to 'TODO', ''
+ %br/
+ %span{:class => 'action-created'}
+ = @action.created_at.to_s(:default)
+ %br/
+ %span{:class => 'action-type'} TODO
+ %span{:class => 'action-goal'}
+ %strong
+ Goal:
+ TODO
+ %br/
+ %span{:class => 'action-location'}
+ %strong
+ Location:
+ = @action.location
+ %br/
+ %span{:class => 'action-tags'}
+ %strong
+ Tags:
+ = tag_list_for @action
+ %br/
.description
= @action.description
-
- %p
- Link:
- = link_to @action.url, @action.url, :popup => true
-
- .dates
- Created:
- = @action.created_at
-
- .platform
- Source:
- = link_to @action.site.name, @action.site.url, :popup => true
-
-
- %p= link_to :back
+ = link_to @action.url, @action.url, :class => 'action-url'
\ No newline at end of file
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 9454fe1..94862f9 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,11 +1,12 @@
!!! 1.0
%html{"xmlns"=>"http://www.w3.org/1999/xhtml", "xml:lang"=>"en"}
%head
%meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}/
%title A Mashup of 29+ Social Action Platforms
- = stylesheet_link_tag 'main'
+ = stylesheet_link_tag 'main', 'facebox'
+ = javascript_include_tag 'jquery', 'facebox', 'application'
= yield :map_headers
%body{ map_loader }
= yield
\ No newline at end of file
diff --git a/public/facebox/b.png b/public/facebox/b.png
new file mode 100644
index 0000000..f184e62
Binary files /dev/null and b/public/facebox/b.png differ
diff --git a/public/facebox/bl.png b/public/facebox/bl.png
new file mode 100644
index 0000000..f627185
Binary files /dev/null and b/public/facebox/bl.png differ
diff --git a/public/facebox/br.png b/public/facebox/br.png
new file mode 100644
index 0000000..31f204f
Binary files /dev/null and b/public/facebox/br.png differ
diff --git a/public/facebox/closelabel.gif b/public/facebox/closelabel.gif
new file mode 100755
index 0000000..87b4f8b
Binary files /dev/null and b/public/facebox/closelabel.gif differ
diff --git a/public/facebox/loading.gif b/public/facebox/loading.gif
new file mode 100755
index 0000000..f864d5f
Binary files /dev/null and b/public/facebox/loading.gif differ
diff --git a/public/facebox/shadow.gif b/public/facebox/shadow.gif
new file mode 100644
index 0000000..e58b35b
Binary files /dev/null and b/public/facebox/shadow.gif differ
diff --git a/public/facebox/tl.png b/public/facebox/tl.png
new file mode 100644
index 0000000..d99c8f6
Binary files /dev/null and b/public/facebox/tl.png differ
diff --git a/public/facebox/tr.png b/public/facebox/tr.png
new file mode 100644
index 0000000..e99b6ec
Binary files /dev/null and b/public/facebox/tr.png differ
diff --git a/public/javascripts/application.js b/public/javascripts/application.js
index fe45776..43d975f 100644
--- a/public/javascripts/application.js
+++ b/public/javascripts/application.js
@@ -1,2 +1,5 @@
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
+jQuery(document).ready(function() {
+ jQuery('a[rel*=facebox]').facebox()
+})
\ No newline at end of file
diff --git a/public/javascripts/facebox.js b/public/javascripts/facebox.js
new file mode 100644
index 0000000..dc5ffca
--- /dev/null
+++ b/public/javascripts/facebox.js
@@ -0,0 +1,234 @@
+/*
+ * Facebox (for jQuery)
+ * version: 1.2 (03/13/2008)
+ * @requires jQuery v1.2 or later
+ *
+ * Examples at http://famspam.com/facebox/
+ * Code at http://github.com/defunkt/facebox
+ * List at http://groups.google.com/groups/facebox
+ *
+ * Licensed under the MIT:
+ * http://www.opensource.org/licenses/mit-license.php
+ *
+ * Copyright 2007, 2008 Chris Wanstrath [ [email protected] ]
+ *
+ * Usage:
+ *
+ * jQuery(document).ready(function() {
+ * jQuery('a[rel*=facebox]').facebox()
+ * })
+ *
+ * <a href="#terms" rel="facebox">Terms</a>
+ * Loads the #terms div in the box
+ *
+ * <a href="terms.html" rel="facebox">Terms</a>
+ * Loads the terms.html page in the box
+ *
+ * <a href="terms.png" rel="facebox">Terms</a>
+ * Loads the terms.png image in the box
+ *
+ *
+ * You can also use it programmatically:
+ *
+ * jQuery.facebox('some html')
+ *
+ * This will open a facebox with "some html" as the content.
+ *
+ * jQuery.facebox(function() { ajaxes })
+ *
+ * This will show a loading screen before the passed function is called,
+ * allowing for a better ajax experience.
+ *
+ * Want to close the facebox? Trigger the 'close.facebox' document event:
+ *
+ * jQuery(document).trigger('close.facebox')
+ *
+ */
+(function($) {
+ $.facebox = function(data, klass) {
+ $.facebox.init()
+ $.facebox.loading()
+ $.isFunction(data) ? data.call() : $.facebox.reveal(data, klass)
+ }
+
+ $.facebox.settings = {
+ loading_image : '/facebox/loading.gif',
+ close_image : '/facebox/closelabel.gif',
+ window_hash : '#facebox',
+ image_types : [ 'png', 'jpg', 'jpeg', 'gif' ],
+ facebox_html : '\
+ <div id="facebox" style="display:none;"> \
+ <div class="popup"> \
+ <table> \
+ <tbody> \
+ <tr> \
+ <td class="tl"/><td class="b"/><td class="tr"/> \
+ </tr> \
+ <tr> \
+ <td class="b"/> \
+ <td class="body"> \
+ <div class="content"> \
+ </div> \
+ <div class="footer"> \
+ <a href="#" class="close"> \
+ <img src="/facebox/closelabel.gif" title="close" class="close_image" /> \
+ </a> \
+ </div> \
+ </td> \
+ <td class="b"/> \
+ </tr> \
+ <tr> \
+ <td class="bl"/><td class="b"/><td class="br"/> \
+ </tr> \
+ </tbody> \
+ </table> \
+ </div> \
+ </div>'
+ }
+
+ // Opening the facebox adds #facebox to the url. Clicking 'back' closes the facebox
+ // but keeps you on the page you were on.
+ function back_button_observer() {
+ if (window.location.hash != $.facebox.settings.window_hash) $(document).trigger('close.facebox')
+ }
+
+ function observe_back_button() {
+ $.facebox.settings.old_hash = window.location.hash || '#'
+ window.location.hash = $.facebox.settings.window_hash
+ $.facebox.settings.back_button_observer = setInterval(back_button_observer, 200)
+ }
+
+ function stop_observing_back_button() {
+ if (window.location.hash != $.facebox.settings.old_hash) window.location.hash = $.facebox.settings.old_hash
+ $.facebox.settings.old_hash = null
+ clearInterval($.facebox.settings.back_button_observer)
+ }
+
+ $.facebox.loading = function() {
+ if ($('#facebox .loading').length == 1) return true
+
+ observe_back_button()
+
+ $('#facebox .content').empty()
+ $('#facebox .body').children().hide().end().
+ append('<div class="loading"><img src="'+$.facebox.settings.loading_image+'"/></div>')
+
+ var pageScroll = $.facebox.getPageScroll()
+ $('#facebox').css({
+ top: pageScroll[1] + ($.facebox.getPageHeight() / 10),
+ left: pageScroll[0]
+ }).show()
+
+ $(document).bind('keydown.facebox', function(e) {
+ if (e.keyCode == 27) $.facebox.close()
+ })
+ $('#facebox .close').click($.facebox.close)
+ }
+
+ $.facebox.reveal = function(data, klass) {
+ if (klass) $('#facebox .content').addClass(klass)
+ $('#facebox .content').append(data)
+ $('#facebox .loading').remove()
+ $('#facebox .body').children().fadeIn('normal')
+ }
+
+ $.facebox.close = function() {
+ $(document).trigger('close.facebox')
+ return false
+ }
+
+ $(document).bind('close.facebox', function() {
+ stop_observing_back_button()
+ $(document).unbind('keydown.facebox')
+ $('#facebox').fadeOut(function() {
+ $('#facebox .content').empty().removeClass().addClass('content')
+ })
+ })
+
+ $.fn.facebox = function(settings) {
+ $.facebox.init(settings)
+
+ var image_types = $.facebox.settings.image_types.join('|')
+ image_types = new RegExp('\.' + image_types + '$', 'i')
+
+ function click_handler() {
+ $.facebox.loading(true)
+
+ // support for rel="facebox[.inline_popup]" syntax, to add a class
+ var klass = this.rel.match(/facebox\[\.(\w+)\]/)
+ if (klass) klass = klass[1]
+
+ // div
+ if (this.href.match(/#/)) {
+ var url = window.location.href.split('#')[0]
+ var target = this.href.replace(url,'')
+ $.facebox.reveal($(target).clone().show(), klass)
+
+ // image
+ } else if (this.href.match(image_types)) {
+ var image = new Image()
+ image.onload = function() {
+ $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
+ }
+ image.src = this.href
+
+ // ajax
+ } else {
+ $.get(this.href, function(data) { $.facebox.reveal(data, klass) })
+ }
+
+ return false
+ }
+
+ return this.click(click_handler)
+ }
+
+ $.facebox.init = function(settings) {
+ if ($.facebox.settings.inited) return true
+ else $.facebox.settings.inited = true
+
+ if (settings) $.extend($.facebox.settings, settings)
+ $('body').append($.facebox.settings.facebox_html)
+
+ var preload = [ new Image(), new Image() ]
+ preload[0].src = $.facebox.settings.close_image
+ preload[1].src = $.facebox.settings.loading_image
+
+ $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
+ preload.push(new Image())
+ preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
+ })
+
+ $('#facebox .close').click($.facebox.close)
+ $('#facebox .close_image').attr('src', $.facebox.settings.close_image)
+ }
+
+ // getPageScroll() by quirksmode.com
+ $.facebox.getPageScroll = function() {
+ var xScroll, yScroll;
+ if (self.pageYOffset) {
+ yScroll = self.pageYOffset;
+ xScroll = self.pageXOffset;
+ } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
+ yScroll = document.documentElement.scrollTop;
+ xScroll = document.documentElement.scrollLeft;
+ } else if (document.body) {// all other Explorers
+ yScroll = document.body.scrollTop;
+ xScroll = document.body.scrollLeft;
+ }
+ return new Array(xScroll,yScroll)
+ }
+
+ // adapter from getPageSize() by quirksmode.com
+ $.facebox.getPageHeight = function() {
+ var windowHeight
+ if (self.innerHeight) { // all except Explorer
+ windowHeight = self.innerHeight;
+ } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
+ windowHeight = document.documentElement.clientHeight;
+ } else if (document.body) { // other Explorers
+ windowHeight = document.body.clientHeight;
+ }
+ return windowHeight
+ }
+})(jQuery);
diff --git a/public/javascripts/jquery.js b/public/javascripts/jquery.js
new file mode 100644
index 0000000..ebe02bd
--- /dev/null
+++ b/public/javascripts/jquery.js
@@ -0,0 +1,31 @@
+/*
+ * jQuery 1.2.1 - New Wave Javascript
+ *
+ * Copyright (c) 2007 John Resig (jquery.com)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * $Date: 2007-09-16 23:42:06 -0400 (Sun, 16 Sep 2007) $
+ * $Rev: 3353 $
+ */
+(function(){if(typeof jQuery!="undefined")var _jQuery=jQuery;var jQuery=window.jQuery=function(selector,context){return this instanceof jQuery?this.init(selector,context):new jQuery(selector,context);};if(typeof $!="undefined")var _$=$;window.$=jQuery;var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(typeof selector=="string"){var m=quickExpr.exec(selector);if(m&&(m[1]||!context)){if(m[1])selector=jQuery.clean([m[1]],context);else{var tmp=document.getElementById(m[3]);if(tmp)if(tmp.id!=m[3])return jQuery().find(selector);else{this[0]=tmp;this.length=1;return this;}else
+selector=[];}}else
+return new jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return new jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(selector.constructor==Array&&selector||(selector.jquery||selector.length&&selector!=window&&!selector.nodeType&&selector[0]!=undefined&&selector[0].nodeType)&&jQuery.makeArray(selector)||[selector]);},jquery:"1.2.1",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(a){var ret=jQuery(a);ret.prevObject=this;return ret;},setArray:function(a){this.length=0;Array.prototype.push.apply(this,a);return this;},each:function(fn,args){return jQuery.each(this,fn,args);},index:function(obj){var pos=-1;this.each(function(i){if(this==obj)pos=i;});return pos;},attr:function(key,value,type){var obj=key;if(key.constructor==String)if(value==undefined)return this.length&&jQuery[type||"attr"](this[0],key)||undefined;else{obj={};obj[key]=value;}return this.each(function(index){for(var prop in obj)jQuery.attr(type?this.style:this,prop,jQuery.prop(this,obj[prop],type,index,prop));});},css:function(key,value){return this.attr(key,value,"curCSS");},text:function(e){if(typeof e!="object"&&e!=null)return this.empty().append(document.createTextNode(e));var t="";jQuery.each(e||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)t+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return t;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,1,function(a){this.appendChild(a);});},prepend:function(){return this.domManip(arguments,true,-1,function(a){this.insertBefore(a,this.firstChild);});},before:function(){return this.domManip(arguments,false,1,function(a){this.parentNode.insertBefore(a,this);});},after:function(){return this.domManip(arguments,false,-1,function(a){this.parentNode.insertBefore(a,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(t){var data=jQuery.map(this,function(a){return jQuery.find(t,a);});return this.pushStack(/[^+>] [^+>]/.test(t)||t.indexOf("..")>-1?jQuery.unique(data):data);},clone:function(events){var ret=this.map(function(){return this.outerHTML?jQuery(this.outerHTML)[0]:this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(t){return this.pushStack(jQuery.isFunction(t)&&jQuery.grep(this,function(el,index){return t.apply(el,[index]);})||jQuery.multiFilter(t,this));},not:function(t){return this.pushStack(t.constructor==String&&jQuery.multiFilter(t,this,true)||jQuery.grep(this,function(a){return(t.constructor==Array||t.jquery)?jQuery.inArray(a,t)<0:a!=t;}));},add:function(t){return this.pushStack(jQuery.merge(this.get(),t.constructor==String?jQuery(t).get():t.length!=undefined&&(!t.nodeName||jQuery.nodeName(t,"form"))?t:[t]));},is:function(expr){return expr?jQuery.multiFilter(expr,this).length>0:false;},hasClass:function(expr){return this.is("."+expr);},val:function(val){if(val==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,a=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){var val=jQuery.browser.msie&&!option.attributes["value"].specified?option.text:option.value;if(one)return val;a.push(val);}}return a;}else
+return this[0].value.replace(/\r/g,"");}}else
+return this.each(function(){if(val.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,val)>=0||jQuery.inArray(this.name,val)>=0);else if(jQuery.nodeName(this,"select")){var tmp=val.constructor==Array?val:[val];jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,tmp)>=0||jQuery.inArray(this.text,tmp)>=0);});if(!tmp.length)this.selectedIndex=-1;}else
+this.value=val;});},html:function(val){return val==undefined?(this.length?this[0].innerHTML:null):this.empty().append(val);},replaceWith:function(val){return this.after(val).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(fn){return this.pushStack(jQuery.map(this,function(elem,i){return fn.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},domManip:function(args,table,dir,fn){var clone=this.length>1,a;return this.each(function(){if(!a){a=jQuery.clean(args,this.ownerDocument);if(dir<0)a.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(a[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(document.createElement("tbody"));jQuery.each(a,function(){var elem=clone?this.cloneNode(true):this;if(!evalScript(0,elem))fn.call(obj,elem);});});}};function evalScript(i,elem){var script=jQuery.nodeName(elem,"script");if(script){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
+jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}else if(elem.nodeType==1)jQuery("script",elem).each(evalScript);return script;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},a=1,al=arguments.length,deep=false;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};}if(al==1){target=this;a=0;}var prop;for(;a<al;a++)if((prop=arguments[a])!=null)for(var i in prop){if(target==prop[i])continue;if(deep&&typeof prop[i]=='object'&&target[i])jQuery.extend(target[i],prop[i]);else if(prop[i]!=undefined)target[i]=prop[i];}return target;};var expando="jQuery"+(new Date()).getTime(),uuid=0,win={};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/function/i.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){if(window.execScript)window.execScript(data);else if(jQuery.browser.safari)window.setTimeout(data,0);else
+eval.call(window,data);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?win:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!=undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?win:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(obj,fn,args){if(args){if(obj.length==undefined)for(var i in obj)fn.apply(obj[i],args);else
+for(var i=0,ol=obj.length;i<ol;i++)if(fn.apply(obj[i],args)===false)break;}else{if(obj.length==undefined)for(var i in obj)fn.call(obj[i],i,obj[i]);else
+for(var i=0,ol=obj.length,val=obj[0];i<ol&&fn.call(val,i,val)!==false;val=obj[++i]){}}return obj;},prop:function(elem,value,type,index,prop){if(jQuery.isFunction(value))value=value.call(elem,[index]);var exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i;return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(prop)?value+"px":value;},className:{add:function(elem,c){jQuery.each((c||"").split(/\s+/),function(i,cur){if(!jQuery.className.has(elem.className,cur))elem.className+=(elem.className?" ":"")+cur;});},remove:function(elem,c){elem.className=c!=undefined?jQuery.grep(elem.className.split(/\s+/),function(cur){return!jQuery.className.has(c,cur);}).join(" "):"";},has:function(t,c){return jQuery.inArray(c,(t.className||t).toString().split(/\s+/))>-1;}},swap:function(e,o,f){for(var i in o){e.style["old"+i]=e.style[i];e.style[i]=o[i];}f.apply(e,[]);for(var i in o)e.style[i]=e.style["old"+i];},css:function(e,p){if(p=="height"||p=="width"){var old={},oHeight,oWidth,d=["Top","Bottom","Right","Left"];jQuery.each(d,function(){old["padding"+this]=0;old["border"+this+"Width"]=0;});jQuery.swap(e,old,function(){if(jQuery(e).is(':visible')){oHeight=e.offsetHeight;oWidth=e.offsetWidth;}else{e=jQuery(e.cloneNode(true)).find(":radio").removeAttr("checked").end().css({visibility:"hidden",position:"absolute",display:"block",right:"0",left:"0"}).appendTo(e.parentNode)[0];var parPos=jQuery.css(e.parentNode,"position")||"static";if(parPos=="static")e.parentNode.style.position="relative";oHeight=e.clientHeight;oWidth=e.clientWidth;if(parPos=="static")e.parentNode.style.position="static";e.parentNode.removeChild(e);}});return p=="height"?oHeight:oWidth;}return jQuery.curCSS(e,p);},curCSS:function(elem,prop,force){var ret,stack=[],swap=[];function color(a){if(!jQuery.browser.safari)return false;var ret=document.defaultView.getComputedStyle(a,null);return!ret||ret.getPropertyValue("color")=="";}if(prop=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(elem.style,"opacity");return ret==""?"1":ret;}if(prop.match(/float/i))prop=styleFloat;if(!force&&elem.style[prop])ret=elem.style[prop];else if(document.defaultView&&document.defaultView.getComputedStyle){if(prop.match(/float/i))prop="float";prop=prop.replace(/([A-Z])/g,"-$1").toLowerCase();var cur=document.defaultView.getComputedStyle(elem,null);if(cur&&!color(elem))ret=cur.getPropertyValue(prop);else{for(var a=elem;a&&color(a);a=a.parentNode)stack.unshift(a);for(a=0;a<stack.length;a++)if(color(stack[a])){swap[a]=stack[a].style.display;stack[a].style.display="block";}ret=prop=="display"&&swap[stack.length-1]!=null?"none":document.defaultView.getComputedStyle(elem,null).getPropertyValue(prop)||"";for(a=0;a<swap.length;a++)if(swap[a]!=null)stack[a].style.display=swap[a];}if(prop=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var newProp=prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();});ret=elem.currentStyle[prop]||elem.currentStyle[newProp];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var style=elem.style.left;var runtimeStyle=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;elem.style.left=ret||0;ret=elem.style.pixelLeft+"px";elem.style.left=style;elem.runtimeStyle.left=runtimeStyle;}}return ret;},clean:function(a,doc){var r=[];doc=doc||document;jQuery.each(a,function(i,arg){if(!arg)return;if(arg.constructor==Number)arg=arg.toString();if(typeof arg=="string"){arg=arg.replace(/(<(\w+)[^>]*?)\/>/g,function(m,all,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area)$/i)?m:all+"></"+tag+">";});var s=jQuery.trim(arg).toLowerCase(),div=doc.createElement("div"),tb=[];var wrap=!s.indexOf("<opt")&&[1,"<select>","</select>"]||!s.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||s.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!s.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!s.indexOf("<td")||!s.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!s.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+arg+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){if(!s.indexOf("<table")&&s.indexOf("<tbody")<0)tb=div.firstChild&&div.firstChild.childNodes;else if(wrap[1]=="<table>"&&s.indexOf("<tbody")<0)tb=div.childNodes;for(var n=tb.length-1;n>=0;--n)if(jQuery.nodeName(tb[n],"tbody")&&!tb[n].childNodes.length)tb[n].parentNode.removeChild(tb[n]);if(/^\s/.test(arg))div.insertBefore(doc.createTextNode(arg.match(/^\s*/)[0]),div.firstChild);}arg=jQuery.makeArray(div.childNodes);}if(0===arg.length&&(!jQuery.nodeName(arg,"form")&&!jQuery.nodeName(arg,"select")))return;if(arg[0]==undefined||jQuery.nodeName(arg,"form")||arg.options)r.push(arg);else
+r=jQuery.merge(r,arg);});return r;},attr:function(elem,name,value){var fix=jQuery.isXMLDoc(elem)?{}:jQuery.props;if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(fix[name]){if(value!=undefined)elem[fix[name]]=value;return elem[fix[name]];}else if(jQuery.browser.msie&&name=="style")return jQuery.attr(elem.style,"cssText",value);else if(value==undefined&&jQuery.browser.msie&&jQuery.nodeName(elem,"form")&&(name=="action"||name=="method"))return elem.getAttributeNode(name).nodeValue;else if(elem.tagName){if(value!=undefined){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem.setAttribute(name,value);}if(jQuery.browser.msie&&/href|src/.test(name)&&!jQuery.isXMLDoc(elem))return elem.getAttribute(name,2);return elem.getAttribute(name);}else{if(name=="opacity"&&jQuery.browser.msie){if(value!=undefined){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(value).toString()=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100).toString():"";}name=name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();});if(value!=undefined)elem[name]=value;return elem[name];}},trim:function(t){return(t||"").replace(/^\s+|\s+$/g,"");},makeArray:function(a){var r=[];if(typeof a!="array")for(var i=0,al=a.length;i<al;i++)r.push(a[i]);else
+r=a.slice(0);return r;},inArray:function(b,a){for(var i=0,al=a.length;i<al;i++)if(a[i]==b)return i;return-1;},merge:function(first,second){if(jQuery.browser.msie){for(var i=0;second[i];i++)if(second[i].nodeType!=8)first.push(second[i]);}else
+for(var i=0;second[i];i++)first.push(second[i]);return first;},unique:function(first){var r=[],done={};try{for(var i=0,fl=first.length;i<fl;i++){var id=jQuery.data(first[i]);if(!done[id]){done[id]=true;r.push(first[i]);}}}catch(e){r=first;}return r;},grep:function(elems,fn,inv){if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+"}");var result=[];for(var i=0,el=elems.length;i<el;i++)if(!inv&&fn(elems[i],i)||inv&&!fn(elems[i],i))result.push(elems[i]);return result;},map:function(elems,fn){if(typeof fn=="string")fn=eval("false||function(a){return "+fn+"}");var result=[];for(var i=0,el=elems.length;i<el;i++){var val=fn(elems[i],i);if(val!==null&&val!=undefined){if(val.constructor!=Array)val=[val];result=result.concat(val);}}return result;}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",styleFloat:jQuery.browser.msie?"styleFloat":"cssFloat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,innerHTML:"innerHTML",className:"className",value:"value",disabled:"disabled",checked:"checked",readonly:"readOnly",selected:"selected",maxlength:"maxLength"}});jQuery.each({parent:"a.parentNode",parents:"jQuery.dir(a,'parentNode')",next:"jQuery.nth(a,2,'nextSibling')",prev:"jQuery.nth(a,2,'previousSibling')",nextAll:"jQuery.dir(a,'nextSibling')",prevAll:"jQuery.dir(a,'previousSibling')",siblings:"jQuery.sibling(a.parentNode.firstChild,a)",children:"jQuery.sibling(a.firstChild)",contents:"jQuery.nodeName(a,'iframe')?a.contentDocument||a.contentWindow.document:jQuery.makeArray(a.childNodes)"},function(i,n){jQuery.fn[i]=function(a){var ret=jQuery.map(this,n);if(a&&typeof a=="string")ret=jQuery.multiFilter(a,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(i,n){jQuery.fn[i]=function(){var a=arguments;return this.each(function(){for(var j=0,al=a.length;j<al;j++)jQuery(a[j])[n](this);});};});jQuery.each({removeAttr:function(key){jQuery.attr(this,key,"");this.removeAttribute(key);},addClass:function(c){jQuery.className.add(this,c);},removeClass:function(c){jQuery.className.remove(this,c);},toggleClass:function(c){jQuery.className[jQuery.className.has(this,c)?"remove":"add"](this,c);},remove:function(a){if(!a||jQuery.filter(a,[this]).r.length){jQuery.removeData(this);this.parentNode.removeChild(this);}},empty:function(){jQuery("*",this).each(function(){jQuery.removeData(this);});while(this.firstChild)this.removeChild(this.firstChild);}},function(i,n){jQuery.fn[i]=function(){return this.each(n,arguments);};});jQuery.each(["Height","Width"],function(i,name){var n=name.toLowerCase();jQuery.fn[n]=function(h){return this[0]==window?jQuery.browser.safari&&self["inner"+name]||jQuery.boxModel&&Math.max(document.documentElement["client"+name],document.body["client"+name])||document.body["client"+name]:this[0]==document?Math.max(document.body["scroll"+name],document.body["offset"+name]):h==undefined?(this.length?jQuery.css(this[0],n):null):this.css(n,h.constructor==String?h:h+"px");};});var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":"m[2]=='*'||jQuery.nodeName(a,m[2])","#":"a.getAttribute('id')==m[2]",":":{lt:"i<m[3]-0",gt:"i>m[3]-0",nth:"m[3]-0==i",eq:"m[3]-0==i",first:"i==0",last:"i==r.length-1",even:"i%2==0",odd:"i%2","first-child":"a.parentNode.getElementsByTagName('*')[0]==a","last-child":"jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a","only-child":"!jQuery.nth(a.parentNode.lastChild,2,'previousSibling')",parent:"a.firstChild",empty:"!a.firstChild",contains:"(a.textContent||a.innerText||jQuery(a).text()||'').indexOf(m[3])>=0",visible:'"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',hidden:'"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',enabled:"!a.disabled",disabled:"a.disabled",checked:"a.checked",selected:"a.selected||jQuery.attr(a,'selected')",text:"'text'==a.type",radio:"'radio'==a.type",checkbox:"'checkbox'==a.type",file:"'file'==a.type",password:"'password'==a.type",submit:"'submit'==a.type",image:"'image'==a.type",reset:"'reset'==a.type",button:'"button"==a.type||jQuery.nodeName(a,"button")',input:"/input|select|textarea|button/i.test(a.nodeName)",has:"jQuery.find(m[3],a).length",header:"/h\\d/i.test(a.nodeName)",animated:"jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length"}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&!context.nodeType)context=null;context=context||document;var ret=[context],done=[],last;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false;var re=quickChild;var m=re.exec(t);if(m){var nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName.toUpperCase()))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var nodeName=m[2],merge={};m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName.toUpperCase()){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=jQuery.filter(m[3],r,true).r;else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(\d*)n\+?(\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"n+"+m[3]||m[3]),first=(test[1]||1)-0,last=test[2]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==1){if(last==0||node.nodeIndex==last)add=true;}else if((node.nodeIndex+last)%first==0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var f=jQuery.expr[m[1]];if(typeof f!="string")f=jQuery.expr[m[1]][m[2]];f=eval("false||function(a,i){return "+f+"}");r=jQuery.grep(r,f,not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[];var cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&(!elem||n!=elem))r.push(n);}return r;}});jQuery.event={add:function(element,type,handler,data){if(jQuery.browser.msie&&element.setInterval!=undefined)element=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=function(){return fn.apply(this,arguments);};handler.data=data;handler.guid=fn.guid;}var parts=type.split(".");type=parts[0];handler.type=parts[1];var events=jQuery.data(element,"events")||jQuery.data(element,"events",{});var handle=jQuery.data(element,"handle",function(){var val;if(typeof jQuery=="undefined"||jQuery.event.triggered)return val;val=jQuery.event.handle.apply(element,arguments);return val;});var handlers=events[type];if(!handlers){handlers=events[type]={};if(element.addEventListener)element.addEventListener(type,handle,false);else
+element.attachEvent("on"+type,handle);}handlers[handler.guid]=handler;this.global[type]=true;},guid:1,global:{},remove:function(element,type,handler){var events=jQuery.data(element,"events"),ret,index;if(typeof type=="string"){var parts=type.split(".");type=parts[0];}if(events){if(type&&type.type){handler=type.handler;type=type.type;}if(!type){for(type in events)this.remove(element,type);}else if(events[type]){if(handler)delete events[type][handler.guid];else
+for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(element.removeEventListener)element.removeEventListener(type,jQuery.data(element,"handle"),false);else
+element.detachEvent("on"+type,jQuery.data(element,"handle"));ret=null;delete events[type];}}for(ret in events)break;if(!ret){jQuery.removeData(element,"events");jQuery.removeData(element,"handle");}}},trigger:function(type,data,element,donative,extra){data=jQuery.makeArray(data||[]);if(!element){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{var val,ret,fn=jQuery.isFunction(element[type]||null),evt=!data[0]||!data[0].preventDefault;if(evt)data.unshift(this.fix({type:type,target:element}));data[0].type=type;if(jQuery.isFunction(jQuery.data(element,"handle")))val=jQuery.data(element,"handle").apply(element,data);if(!fn&&element["on"+type]&&element["on"+type].apply(element,data)===false)val=false;if(evt)data.shift();if(extra&&extra.apply(element,data)===false)val=false;if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(element,'a')&&type=="click")){this.triggered=true;element[type]();}this.triggered=false;}return val;},handle:function(event){var val;event=jQuery.event.fix(event||window.event||{});var parts=event.type.split(".");event.type=parts[0];var c=jQuery.data(this,"events")&&jQuery.data(this,"events")[event.type],args=Array.prototype.slice.call(arguments,1);args.unshift(event);for(var j in c){args[0].handler=c[j];args[0].data=c[j].data;if(!parts[1]||c[j].type==parts[1]){var tmp=c[j].apply(this,args);if(val!==false)val=tmp;if(tmp===false){event.preventDefault();event.stopPropagation();}}}if(jQuery.browser.msie)event.target=event.preventDefault=event.stopPropagation=event.handler=event.data=null;return val;},fix:function(event){var originalEvent=event;event=jQuery.extend({},originalEvent);event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};if(!event.target&&event.srcElement)event.target=event.srcElement;if(jQuery.browser.safari&&event.target.nodeType==3)event.target=originalEvent.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var e=document.documentElement,b=document.body;event.pageX=event.clientX+(e&&e.scrollLeft||b.scrollLeft||0);event.pageY=event.clientY+(e&&e.scrollTop||b.scrollTop||0);}if(!event.which&&(event.charCode||event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){return this.each(function(){jQuery.event.add(this,type,function(event){jQuery(this).unbind(event);return(fn||data).apply(this,arguments);},fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){if(this[0])return jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(){var a=arguments;return this.click(function(e){this.lastToggle=0==this.lastToggle?1:0;e.preventDefault();return a[this.lastToggle].apply(this,[e])||false;});},hover:function(f,g){function handleHover(e){var p=e.relatedTarget;while(p&&p!=this)try{p=p.parentNode;}catch(e){p=this;};if(p==this)return false;return(e.type=="mouseover"?f:g).apply(this,[e]);}return this.mouseover(handleHover).mouseout(handleHover);},ready:function(f){bindReady();if(jQuery.isReady)f.apply(document,[jQuery]);else
+jQuery.readyList.push(function(){return f.apply(this,[jQuery]);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.apply(document);});jQuery.readyList=null;}if(jQuery.browser.mozilla||jQuery.browser.opera)document.removeEventListener("DOMContentLoaded",jQuery.ready,false);if(!window.frames.length)jQuery(window).load(function(){jQuery("#__ie_init").remove();});}}});jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,o){jQuery.fn[o]=function(f){return f?this.bind(o,f):this.trigger(o);};});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(jQuery.browser.mozilla||jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);else if(jQuery.browser.msie){document.write("<scr"+"ipt id=__ie_init defer=true "+"src=//:><\/script>");var script=document.getElementById("__ie_init");if(script)script.onreadystatechange=function(){if(this.readyState!="complete")return;jQuery.ready();};script=null;}else if(jQuery.browser.safari)jQuery.safariTimer=setInterval(function(){if(document.readyState=="loaded"||document.readyState=="complete"){clearInterval(jQuery.safariTimer);jQuery.safariTimer=null;jQuery.ready();}},10);jQuery.event.add(window,"load",jQuery.ready);}jQuery.fn.extend({load:function(url,params,callback){if(jQuery.isFunction(url))return this.bind("load",url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);setTimeout(function(){self.each(callback,[res.responseText,status,res]);},13);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=(new Date).getTime();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null},lastModified:{},ajax:function(s){var jsonp,jsre=/=(\?|%3F)/g,status,data;s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=s.data.replace(jsre,"="+jsonp);s.url=s.url.replace(jsre,"="+jsonp);s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&s.type.toLowerCase()=="get")s.url+=(s.url.match(/\?/)?"&":"?")+"_="+(new Date()).getTime();if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");if(!s.url.indexOf("http")&&s.dataType=="script"){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(!jsonp&&(s.success||s.complete)){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return;}var requestDone=false;var xml=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();xml.open(s.type,s.url,s.async);if(s.data)xml.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xml.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xml.setRequestHeader("X-Requested-With","XMLHttpRequest");if(s.beforeSend)s.beforeSend(xml);if(s.global)jQuery.event.trigger("ajaxSend",[xml,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xml&&(xml.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xml)&&"error"||s.ifModified&&jQuery.httpNotModified(xml,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xml,s.dataType);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xml.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
+jQuery.handleError(s,xml,status);complete();if(s.async)xml=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xml){xml.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xml.send(s.data);}catch(e){jQuery.handleError(s,xml,null,e);}if(!s.async)onreadystatechange();return xml;function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xml,s]);}function complete(){if(s.complete)s.complete(xml,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xml,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}},handleError:function(s,xml,status,e){if(s.error)s.error(xml,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xml,s,e]);},active:0,httpSuccess:function(r){try{return!r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||jQuery.browser.safari&&r.status==undefined;}catch(e){}return false;},httpNotModified:function(xml,url){try{var xmlRes=xml.getResponseHeader("Last-Modified");return xml.status==304||xmlRes==jQuery.lastModified[url]||jQuery.browser.safari&&xml.status==undefined;}catch(e){}return false;},httpData:function(r,type){var ct=r.getResponseHeader("content-type");var xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0;var data=xml?r.responseXML:r.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
+for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
+s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock?this.oldblock:"";if(jQuery.css(this,"display")=="none")this.style.display="block";}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");if(this.oldblock=="none")this.oldblock="block";this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle(fn,fn2):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var opt=jQuery.speed(speed,easing,callback);return this[opt.queue===false?"each":"queue"](function(){opt=jQuery.extend({},opt);var hidden=jQuery(this).is(":hidden"),self=this;for(var p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return jQuery.isFunction(opt.complete)&&opt.complete.apply(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
+e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.apply(this);}});},stop:function(){var timers=jQuery.timers;return this.each(function(){for(var i=0;i<timers.length;i++)if(timers[i].elem==this)timers.splice(i--,1);}).dequeue();}});var queue=function(elem,type,array){if(!elem)return;var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",array?jQuery.makeArray(array):[]);return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].apply(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:{slow:600,fast:200}[opt.duration])||400;opt.old=opt.complete;opt.complete=function(){jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.apply(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.apply(this.elem,[this.now,this]);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.curCSS(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.css(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=(new Date()).getTime();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(){return self.step();}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timers.length==1){var timer=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length)clearInterval(timer);},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(){var t=(new Date()).getTime();if(t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done&&jQuery.isFunction(this.options.complete))this.options.complete.apply(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.fx.step={scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}};jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var absolute=jQuery.css(elem,"position")=="absolute",parent=elem.parentNode,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522;if(elem.getBoundingClientRect){box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));if(msie){var border=jQuery("html").css("borderWidth");border=(border=="medium"||jQuery.boxModel&&parseInt(version)>=7)&&2||border;add(-border,-border);}}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&/^t[d|h]$/i.test(parent.tagName)||!safari2)border(offsetParent);if(safari2&&!absolute&&jQuery.css(offsetParent,"position")=="absolute")absolute=true;offsetParent=offsetParent.offsetParent;}while(parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table-row.*$/i.test(jQuery.css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&jQuery.css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if(safari2&&absolute)add(-doc.body.offsetLeft,-doc.body.offsetTop);}results={top:top,left:left};}return results;function border(elem){add(jQuery.css(elem,"borderLeftWidth"),jQuery.css(elem,"borderTopWidth"));}function add(l,t){left+=parseInt(l)||0;top+=parseInt(t)||0;}};})();
diff --git a/public/stylesheets/facebox.css b/public/stylesheets/facebox.css
new file mode 100644
index 0000000..67e4619
--- /dev/null
+++ b/public/stylesheets/facebox.css
@@ -0,0 +1,76 @@
+#facebox .b {
+ background:url(/facebox/b.png);
+}
+
+#facebox .tl {
+ background:url(/facebox/tl.png);
+}
+
+#facebox .tr {
+ background:url(/facebox/tr.png);
+}
+
+#facebox .bl {
+ background:url(/facebox/bl.png);
+}
+
+#facebox .br {
+ background:url(/facebox/br.png);
+}
+
+#facebox {
+ position: absolute;
+ width: 100%;
+ top: 0;
+ left: 0;
+ z-index: 100;
+ text-align: left;
+}
+
+#facebox .popup {
+ position: relative;
+}
+
+#facebox table {
+ margin: auto;
+ border-collapse: collapse;
+ width:auto;
+}
+
+#facebox td {
+ border-bottom: 0;
+ padding:0;
+}
+
+#facebox .body {
+ padding: 10px;
+ background: #fff;
+ width: 370px;
+}
+
+#facebox .loading {
+ text-align: center;
+}
+
+#facebox .image {
+ text-align: center;
+}
+
+#facebox img {
+ border: 0;
+ margin: 0;
+}
+
+#facebox .footer {
+ border-top: 1px solid #DDDDDD;
+ padding-top: 5px;
+ margin-top: 10px;
+ text-align: right;
+}
+
+#facebox .tl, #facebox .tr, #facebox .bl, #facebox .br {
+ height: 10px;
+ width: 10px;
+ overflow: hidden;
+ padding: 0;
+}
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index 0585b52..594b42d 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,145 +1,155 @@
+body
+ :font-family Arial, Helvetica, sans-serif
+
a
:color #3366cc
:text-decoration none
h2
:margin 0px 0px 5px 0px
p
:margin 3px 3px 0px 3px
// Block Elements
-#search_results, #tag_cloud
+#search_results, #tag_cloud, #facebox
:width 710px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 0px 10px
// Search box
#search_box
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:background-color #e9f3f1
:padding 10px 10px 30px 10px
table
td
:padding-right 5px
:padding-top 10px
.first
td
:padding-top 0
.platform_select
:width 170px
:float left
:margin-top 10px
// Results Elements
.action
:width 700px
:margin-bottom 30px
.action-title
:margin-top 5px
:margin-bottom 5px
:font-size 160%
:display block
.action-source
:width 320px
:float right
:margin-left 25px
:text-align right
.action-goal
.action-location
.action-tags
.action-url
:margin-top 10px
:display block
:color #ff6600
.action-url a
.action-url a:hover
.action-byline
.action-byline a
:font-weight bold
.action-byline a:hover
.action-created
.action-type
:font-style italic
// Pagination
.pagination
:padding 3px
:margin 3px
.pagination a
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:text-decoration none
:color #3366cc
.pagination a:hover, .pagination a:active
:border 1px solid #3366cc
:color #000
.pagination span.current
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:font-weight bold
:background-color #3366cc
:color #FFF
.pagination span.disabled
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #eee
:color #ddd
// Map
#gmap
:height 400px
:width 710px
:margin-top 20px
.map-action
:font-size 12px
:width 200px
:border 1px red
:font-family Arial, Helvetica, sans-serif
.title
.location
:font-size 80%
.byline
:font-size 80%
.created
:font-size 80%
// Tags
.tag1
:font-size 1.0em
.tag2
:font-size 1.2em
.tag3
:font-size 1.4em
.tag4
:font-size 1.6em
+// Facebox Popup
+#facebox
+ .action-title
+ :color #3366cc
+ .description
+ :height 200px
+ :overflow auto
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
2259357fb5928909035f426cb49f4d1092c10f20
|
Getting somewhere on the search, still kinda sucky, but getting closere
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index b58a3c1..1cd284f 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,21 +1,24 @@
class ActionsController < ApplicationController
def index
redirect_to '/map' and return false if params[:commit] == 'Google Map'
redirect_to '/tags' and return false if params[:commit] == 'Tag Cloud'
- @actions = Action.paginate(:all, :page => params[:page], :order => 'created_at DESC')
+ @search = Search.new(params[:search])
+ @actions = Action.paginate(:all, :page => params[:page], :order => 'created_at DESC', :conditions => @search.build_conditions, :include => :feed)
respond_to do |format|
format.html
format.xml
end
end
def show
@action = Action.find(params[:id])
respond_to do |format|
format.html
format.xml
end
end
+
end
+
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 50483e2..883940a 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,38 +1,39 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def map_loader
if [email protected]? && @gmap.onload
{:onload => @gmap.onload_func_name + '()', :onunload => 'GUnload'}
else
{}
end
end
def options_for_action_type_select
- options_for_select([
+ [
['All actions', "all"],
['Group fundraising', "fundraiser"],
['Grassroots petition', "petitions"],
['Volunteer opportunity', "volunteer"],
['Collective action', "pledge"],
['Affinity group', "affinitygroup"]
- ])
+ ]
end
def options_for_created_select
- options_for_select([
- ['Last 30 days', "last30days"],
- ['Last 14 days',"last14days"],
- ['Last week', "lastweek"],
- ['Yesterday', "yesterday"],
- ['Today', "today"]
- ])
+ [
+ ['Any Time', nil],
+ ['Last 30 days', "30"],
+ ['Last 14 days',"14"],
+ ['Last week', "7"],
+ ['Yesterday', "2"],
+ ['Today', "1"]
+ ]
end
def tag_list_for(action)
action.tags.collect do |tag|
link_to tag.name, tag_path(tag)
end.join(', ')
end
end
diff --git a/app/models/search.rb b/app/models/search.rb
new file mode 100644
index 0000000..f4471de
--- /dev/null
+++ b/app/models/search.rb
@@ -0,0 +1,53 @@
+class Search < ActiveRecord::BaseWithoutTable
+ column :keywords, :string
+ column :action_type, :string
+ column :created, :integer
+ attr_accessor :sites
+
+ validates_inclusion_of :created, :in => %w{ 30 14 7 2 1 }
+
+ def build_conditions
+ reset_conditions
+ add_keywords
+ add_action_type
+ add_sites
+ add_created
+ conditions.join(' AND ')
+ end
+
+ def reset_conditions
+ @conditions = []
+ end
+
+ def conditions
+ @conditions ||= []
+ end
+
+ def add_keywords
+ unless keywords.nil? or keywords.empty?
+ keyword_conditions = []
+ keywords.split(' ').each do |keyword|
+ keyword_conditions << ActiveRecord::Base.send(:sanitize_sql, ["description LIKE ?", "%#{keyword}%"]) # TODO add url, title
+ end
+ conditions << "(" + keyword_conditions.join(' OR ') + ")"
+ end
+ end
+
+ def add_action_type
+ unless action_type.nil? or action_type == 'all'
+ # conditions << "action_type = '#{action_type}'"
+ end
+ end
+
+ def add_sites
+ unless sites.nil? or sites.empty?
+ # conditions << "sites IN (#{sites.join(',')})"
+ end
+ end
+
+ def add_created
+ unless created.nil?
+ conditions << ActiveRecord::Base.send(:sanitize_sql, ["actions.created_at > ?", created.days.ago])
+ end
+ end
+end
diff --git a/app/views/actions/_search_form.html.haml b/app/views/actions/_search_form.html.haml
index 8de4e7c..12596bd 100644
--- a/app/views/actions/_search_form.html.haml
+++ b/app/views/actions/_search_form.html.haml
@@ -1,33 +1,37 @@
#search_box
%h2 Find an Action
- - form_tag actions_path, :method => :get do
+ - form_for @search, :url => actions_path, :html => {:method => :get} do |f|
%table{ :border=>"0", :cellpadding=>"0", :cellspacing=>"0" }
%tr.first
%td Search Term:
- %td= text_field_tag 'search_term', nil, :size => 22
+ %td= f.text_field :keywords, :size => 22
%td
= submit_tag 'Search'
= submit_tag 'Google Map'
= submit_tag 'Tag Cloud'
= submit_tag 'Random'
%tr
%td Type of Action:
- %td= select_tag 'action_type', options_for_action_type_select
+ %td= f.select :action_type, options_for_action_type_select
%td
Created:
- = select_tag 'create', options_for_created_select
+ = f.select :created, options_for_created_select
- Site.find(:all, :order => :name).each_slice(4) do |sites|
.platform_select
- sites.each do |site|
- = check_box_tag site.id, site.name, true
+ /= f.check_box 'sites[]', site.id, true
+ = check_box_tag 'search[sites][]', site.id, true
= site.name
%br/
-
+
+ = debug @search
+ = @search.build_conditions
+
%br{:clear => 'all'}/
\ No newline at end of file
diff --git a/test/fixtures/searches.yml b/test/fixtures/searches.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/test/fixtures/searches.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/test/unit/search_test.rb b/test/unit/search_test.rb
new file mode 100644
index 0000000..371b20c
--- /dev/null
+++ b/test/unit/search_test.rb
@@ -0,0 +1,8 @@
+require File.dirname(__FILE__) + '/../test_helper'
+
+class SearchTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ def test_truth
+ assert true
+ end
+end
diff --git a/vendor/plugins/active_record_base_without_table_edge/CHANGELOG b/vendor/plugins/active_record_base_without_table_edge/CHANGELOG
new file mode 100644
index 0000000..3f1efcb
--- /dev/null
+++ b/vendor/plugins/active_record_base_without_table_edge/CHANGELOG
@@ -0,0 +1,7 @@
+[15 September 2007]
+
+* Update for new attribute implementation. Require Rails >= r7315.
+
+[27 April 2007]
+
+* Correctly cache class instance variables containing column information [Reported by Nils Jonsson]
diff --git a/vendor/plugins/active_record_base_without_table_edge/MIT-LICENSE b/vendor/plugins/active_record_base_without_table_edge/MIT-LICENSE
new file mode 100644
index 0000000..602bda2
--- /dev/null
+++ b/vendor/plugins/active_record_base_without_table_edge/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2006 Jonathan Viney
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/plugins/active_record_base_without_table_edge/README b/vendor/plugins/active_record_base_without_table_edge/README
new file mode 100644
index 0000000..e5aa941
--- /dev/null
+++ b/vendor/plugins/active_record_base_without_table_edge/README
@@ -0,0 +1,27 @@
+= ActiveRecordBaseWithoutTable
+
+If you find this plugin useful, please consider a donation to show your support!
+
+ http://www.paypal.com/cgi-bin/webscr?cmd=_send-money
+
+ Email address: [email protected]
+
+== Instructions
+
+Get the power of ActiveRecord models, including validation, without having a table in the database.
+
+ class Contact < ActiveRecord::BaseWithoutTable
+ column :name, :string
+ column :email_address, :string
+ column :message, :text
+
+ validates_presence_of :name, :email_address, :string
+ end
+
+This model can be used just like a regular model based on a table, except it will never be saved to the database.
+
+There is a good blog post available on the plugin:
+
+ http://www.kangarooit.com/developer_blog/2007/02/email-form-validation-in-ruby-on-rails.php
+
+Any bugs, questions, comments please feel free to email me: [email protected]
diff --git a/vendor/plugins/active_record_base_without_table_edge/Rakefile b/vendor/plugins/active_record_base_without_table_edge/Rakefile
new file mode 100644
index 0000000..ac92445
--- /dev/null
+++ b/vendor/plugins/active_record_base_without_table_edge/Rakefile
@@ -0,0 +1,22 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the active_record_base_without_table plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the active_record_base_without_table plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'ActiveRecordBaseWithoutTable'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/vendor/plugins/active_record_base_without_table_edge/lib/active_record/base_without_table.rb b/vendor/plugins/active_record_base_without_table_edge/lib/active_record/base_without_table.rb
new file mode 100644
index 0000000..12cb05e
--- /dev/null
+++ b/vendor/plugins/active_record_base_without_table_edge/lib/active_record/base_without_table.rb
@@ -0,0 +1,26 @@
+module ActiveRecord
+ class BaseWithoutTable < Base
+ self.abstract_class = true
+
+ def create_or_update
+ errors.empty?
+ end
+
+ class << self
+ def columns()
+ @columns ||= []
+ end
+
+ def column(name, sql_type = nil, default = nil, null = true)
+ columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
+ reset_column_information
+ end
+
+ # Do not reset @columns
+ def reset_column_information
+ generated_methods.each { |name| undef_method(name) }
+ @column_names = @columns_hash = @content_columns = @dynamic_methods_hash = @read_methods = nil
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/active_record_base_without_table_edge/test/abstract_unit.rb b/vendor/plugins/active_record_base_without_table_edge/test/abstract_unit.rb
new file mode 100644
index 0000000..f72a878
--- /dev/null
+++ b/vendor/plugins/active_record_base_without_table_edge/test/abstract_unit.rb
@@ -0,0 +1,15 @@
+require 'test/unit'
+
+begin
+ require File.dirname(__FILE__) + '/../../../../config/boot'
+ require 'active_record'
+rescue LoadError
+ require 'rubygems'
+ require_gem 'activerecord'
+end
+
+require File.dirname(__FILE__) + '/../lib/active_record/base_without_table'
+
+config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
+ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + '/debug.log')
+ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'mysql'])
diff --git a/vendor/plugins/active_record_base_without_table_edge/test/active_record_base_without_table_test.rb b/vendor/plugins/active_record_base_without_table_edge/test/active_record_base_without_table_test.rb
new file mode 100644
index 0000000..944e26d
--- /dev/null
+++ b/vendor/plugins/active_record_base_without_table_edge/test/active_record_base_without_table_test.rb
@@ -0,0 +1,41 @@
+require File.dirname(__FILE__) + '/abstract_unit'
+
+class Person < ActiveRecord::BaseWithoutTable
+ column :name, :string
+ column :lucky_number, :integer, 4
+
+ validates_presence_of :name
+end
+
+class ActiveRecordBaseWithoutTableTest < Test::Unit::TestCase
+ def test_default_value
+ assert_equal 4, Person.new.lucky_number
+ end
+
+ def test_validation
+ p = Person.new
+
+ assert !p.save
+ assert p.errors[:name]
+
+ assert p.update_attributes(:name => 'Name')
+ end
+
+ def test_typecast
+ assert_equal 1, Person.new(:lucky_number => "1").lucky_number
+ end
+
+ def test_cached_column_variables_reset_when_column_defined
+ cached_variables = %w(column_names columns_hash content_columns dynamic_methods_hash generated_methods)
+
+ Person.column_names
+ Person.columns_hash
+ Person.content_columns
+ Person.column_methods_hash
+ Person.generated_methods
+
+ cached_variables.each { |v| assert_not_nil Person.instance_variable_get("@#{v}") }
+ Person.column :new_column, :string
+ cached_variables.each { |v| assert Person.instance_variable_get("@#{v}").blank? }
+ end
+end
diff --git a/vendor/plugins/active_record_base_without_table_edge/test/database.yml b/vendor/plugins/active_record_base_without_table_edge/test/database.yml
new file mode 100644
index 0000000..d849c05
--- /dev/null
+++ b/vendor/plugins/active_record_base_without_table_edge/test/database.yml
@@ -0,0 +1,6 @@
+mysql:
+ :adapter: mysql
+ :host: localhost
+ :username: root
+ :password: moose
+ :database: rails_plugin_test
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
778aaeae339f1808478a5cc051ffb7d6edb7716c
|
Oops, fixing. I should be building tests ;-)
|
diff --git a/app/helpers/tags_helper.rb b/app/helpers/tags_helper.rb
index 5837d75..8f7d118 100644
--- a/app/helpers/tags_helper.rb
+++ b/app/helpers/tags_helper.rb
@@ -1,21 +1,21 @@
module TagsHelper
def tag_cloud(tags, classes)
return if tags.empty?
max_count = tags.sort_by(&:count).last.count.to_f
tags.each do |tag|
index = ((tag.count / max_count) * (classes.size - 1)).round
yield tag, classes[index]
end
end
- def page_entries_info_for_tag(collection, tag)
+ def page_entries_info_with_tag(collection, tag)
%{Displaying entries <b>%d - %d</b> of <b>%d</b> in total that match the tag <b>%s</b>} % [
collection.offset + 1,
collection.offset + collection.length,
collection.total_entries,
tag.name
]
end
end
diff --git a/app/views/tags/show.html.haml b/app/views/tags/show.html.haml
index 75a4311..31797aa 100644
--- a/app/views/tags/show.html.haml
+++ b/app/views/tags/show.html.haml
@@ -1,15 +1,16 @@
= render :partial => 'actions/search_form'
#tag_cloud
- tag_cloud @tags, %w(tag1 tag2 tag2 tag4) do |tag, css_class|
- if tag == @tag
- = tag.name
+ %span{:class => css_class}
+ = tag.name
- else
= link_to tag.name, tag_path(tag), :class => css_class
#search_results
%h2 Results
= page_entries_info_with_tag @actions, @tag
= render :partial => 'actions/action', :collection => @actions
= will_paginate @actions
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
eac060392cc47ae07774a573dfe5321e9d1f735e
|
Styled up the google map a bit
|
diff --git a/app/controllers/map_controller.rb b/app/controllers/map_controller.rb
index 6a51ff1..d1582d3 100644
--- a/app/controllers/map_controller.rb
+++ b/app/controllers/map_controller.rb
@@ -1,65 +1,84 @@
class MapController < ApplicationController
before_filter :setup_map
include ActionView::Helpers::JavaScriptHelper
def index
actions = Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => 'latitude IS NOT NULL and longitude IS NOT NULL')
actions.each do |action|
# now for the lat and lng of the marker we want to add.
marker_lat = action.latitude
marker_lng = action.longitude
@gmap.use_marker_code('createWithIconAndHtml', :with_args => [:point, :html, :icon_image])
incident_point = Mappa::GLatLng.new(:lat => marker_lat, :lng => marker_lng)
- @gmap.add_marker(:point => incident_point, :create_with => 'createWithIconAndHtml', :html => "'#{escape_javascript(action.title)}'", :icon_image => "'/images/marker.png'")
+ @gmap.add_marker(:point => incident_point, :create_with => 'createWithIconAndHtml', :html => "'#{escape_javascript(small_map_view_of(action))}'", :icon_image => "'/images/marker.png'")
end
# render :template => "map/index"
end
protected
def setup_map
@gmap = Mappa::GMap.new()
@gmap.api_key = 'ABQIAAAAkGYfBpkZ5yYF_f9sthqC5BTJQa0g3IQ9GZqIMmInSLzwtGDKaBRu7u3V_uePSTUgmfHvnGnehFX3-A'
# set the longitude and latitiude of the centre point of our map
@gmap.lat, @gmap.lng = current_latitude, current_longitude
# set the zoom level of our map. This number is in the range of 1-18. 1 is lowest zoom and 18 is highest
# we've picked a nice middling 12.
@gmap.zoom = 4
@gmap.add_control(:control => 'small')
@gmap.add_control(:control => 'type')
@gmap.add_control(:control => 'overview')
end
def current_latitude
current_location.lat || 41.98
end
def current_longitude
current_location.lng || -87.90
end
def current_location
# debugger
@current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
end
def current_ip
request.remote_ip == '127.0.0.1' ? '67.162.124.13' : request.remote_ip
end
# def get_current_location
# location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
# unless location.lat.nil? and location.lng.nil?
# return location.lat, location.lng
# else
# return 41.98, -87.90 # Chicago, an estimate
# end
# end
+
+ def small_map_view_of(action)
+ %{
+ <div class="map-action">
+ <div class="title">
+ <a href="/actions/#{action.id}">#{action.title}</a>
+ </div>
+ <div class="location">
+ <b>Location:</b> #{action.location}
+ </div>
+ <div class="byline">
+ <b>Created on:</b> <a href="#{action.site.url}">#{action.site.name}</a>
+ </div>
+ <div class="created">
+ <b>Created at:</b> #{action.created_at.to_s(:default)}
+ </div>
+ </div>
+ }
+ end
end
diff --git a/app/helpers/tags_helper.rb b/app/helpers/tags_helper.rb
index 021136e..5837d75 100644
--- a/app/helpers/tags_helper.rb
+++ b/app/helpers/tags_helper.rb
@@ -1,21 +1,21 @@
module TagsHelper
def tag_cloud(tags, classes)
return if tags.empty?
max_count = tags.sort_by(&:count).last.count.to_f
tags.each do |tag|
index = ((tag.count / max_count) * (classes.size - 1)).round
yield tag, classes[index]
end
end
- def page_entries_info(collection, tag)
+ def page_entries_info_for_tag(collection, tag)
%{Displaying entries <b>%d - %d</b> of <b>%d</b> in total that match the tag <b>%s</b>} % [
collection.offset + 1,
collection.offset + collection.length,
collection.total_entries,
tag.name
]
end
end
diff --git a/app/views/actions/_form.html.haml b/app/views/actions/_form.html.haml
deleted file mode 100644
index e69de29..0000000
diff --git a/app/views/actions/edit.html.haml b/app/views/actions/edit.html.haml
deleted file mode 100644
index 84af5b7..0000000
--- a/app/views/actions/edit.html.haml
+++ /dev/null
@@ -1,11 +0,0 @@
-%h1 Editing action
-
-= error_messages_for :action
-
-- form_for(:action, :url => object_url, :html => { :method => :put }) do |f|
- = render :partial => "form", :locals => {:f => f}
- %p= submit_tag "Update"
-
-= link_to 'Show', object_path
-|
-= link_to 'Back', objects_path
diff --git a/app/views/actions/new.html.haml b/app/views/actions/new.html.haml
deleted file mode 100644
index 72ebe56..0000000
--- a/app/views/actions/new.html.haml
+++ /dev/null
@@ -1,9 +0,0 @@
-%h1 Creating action
-
-= error_messages_for :action
-
-- form_for(:action, :url => objects_url) do |f|
- = render :partial => "form", :locals => {:f => f}
- %p= submit_tag "Create"
-
-= link_to 'Back', objects_path
diff --git a/app/views/actions/show.html.haml b/app/views/actions/show.html.haml
index 9194a75..272a3e8 100644
--- a/app/views/actions/show.html.haml
+++ b/app/views/actions/show.html.haml
@@ -1,22 +1,22 @@
%h1 Viewing action
-%div[current_object]
- %h2= current_object.title
+%div[@action]
+ %h2= @action.title
.description
- = current_object.description
+ = @action.description
%p
Link:
- = link_to current_object.url, current_object.url, :popup => true
+ = link_to @action.url, @action.url, :popup => true
.dates
Created:
- = current_object.created_at
+ = @action.created_at
.platform
Source:
- = link_to current_object.site.name, current_object.site.url, :popup => true
+ = link_to @action.site.name, @action.site.url, :popup => true
- %p= link_to 'Back', objects_path
+ %p= link_to :back
diff --git a/app/views/actions/show.xml.haml b/app/views/actions/show.xml.haml
index 281c019..f868b92 100644
--- a/app/views/actions/show.xml.haml
+++ b/app/views/actions/show.xml.haml
@@ -1 +1 @@
-= current_object.to_xml
\ No newline at end of file
+= @action.to_xml
\ No newline at end of file
diff --git a/app/views/tags/show.html.haml b/app/views/tags/show.html.haml
index 18dc4d9..75a4311 100644
--- a/app/views/tags/show.html.haml
+++ b/app/views/tags/show.html.haml
@@ -1,15 +1,15 @@
= render :partial => 'actions/search_form'
#tag_cloud
- tag_cloud @tags, %w(tag1 tag2 tag2 tag4) do |tag, css_class|
- if tag == @tag
= tag.name
- else
= link_to tag.name, tag_path(tag), :class => css_class
#search_results
%h2 Results
- = page_entries_info @actions, @tag
+ = page_entries_info_with_tag @actions, @tag
= render :partial => 'actions/action', :collection => @actions
= will_paginate @actions
\ No newline at end of file
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index 47d5948..0585b52 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,131 +1,145 @@
a
:color #3366cc
:text-decoration none
h2
:margin 0px 0px 5px 0px
p
:margin 3px 3px 0px 3px
// Block Elements
#search_results, #tag_cloud
:width 710px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 0px 10px
// Search box
#search_box
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:background-color #e9f3f1
:padding 10px 10px 30px 10px
table
td
:padding-right 5px
:padding-top 10px
.first
td
:padding-top 0
.platform_select
:width 170px
:float left
:margin-top 10px
// Results Elements
.action
:width 700px
:margin-bottom 30px
.action-title
:margin-top 5px
:margin-bottom 5px
:font-size 160%
:display block
.action-source
:width 320px
:float right
:margin-left 25px
:text-align right
.action-goal
.action-location
.action-tags
.action-url
:margin-top 10px
:display block
:color #ff6600
.action-url a
.action-url a:hover
.action-byline
.action-byline a
:font-weight bold
.action-byline a:hover
.action-created
.action-type
:font-style italic
// Pagination
.pagination
:padding 3px
:margin 3px
.pagination a
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:text-decoration none
:color #3366cc
.pagination a:hover, .pagination a:active
:border 1px solid #3366cc
:color #000
.pagination span.current
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:font-weight bold
:background-color #3366cc
:color #FFF
.pagination span.disabled
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #eee
:color #ddd
// Map
#gmap
:height 400px
:width 710px
:margin-top 20px
+
+.map-action
+ :font-size 12px
+ :width 200px
+ :border 1px red
+ :font-family Arial, Helvetica, sans-serif
+ .title
+ .location
+ :font-size 80%
+ .byline
+ :font-size 80%
+ .created
+ :font-size 80%
+
// Tags
.tag1
:font-size 1.0em
.tag2
:font-size 1.2em
.tag3
:font-size 1.4em
.tag4
:font-size 1.6em
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
595a493811cdd50fbe45ffcb8c0df438c4fb21f6
|
Tag cloud and tag pages now work
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index 0eb8283..b58a3c1 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,19 +1,21 @@
class ActionsController < ApplicationController
def index
+ redirect_to '/map' and return false if params[:commit] == 'Google Map'
+ redirect_to '/tags' and return false if params[:commit] == 'Tag Cloud'
@actions = Action.paginate(:all, :page => params[:page], :order => 'created_at DESC')
respond_to do |format|
format.html
format.xml
end
end
def show
@action = Action.find(params[:id])
respond_to do |format|
format.html
format.xml
end
end
end
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb
new file mode 100644
index 0000000..41ea2a3
--- /dev/null
+++ b/app/controllers/tags_controller.rb
@@ -0,0 +1,16 @@
+class TagsController < ApplicationController
+ before_filter :load_tags
+
+ def index
+ end
+
+ def show
+ @tag = Tag.find_by_name(params[:id])
+ @actions = Action.paginate(:all, :page => params[:page], :include => 'taggings', :conditions => ['taggings.tag_id = ?', @tag.id], :order => 'actions.created_at DESC')
+ end
+
+private
+ def load_tags
+ @tags = Action.tag_counts
+ end
+end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 75aa4ad..50483e2 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,32 +1,38 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def map_loader
if [email protected]? && @gmap.onload
{:onload => @gmap.onload_func_name + '()', :onunload => 'GUnload'}
else
{}
end
end
def options_for_action_type_select
options_for_select([
['All actions', "all"],
['Group fundraising', "fundraiser"],
['Grassroots petition', "petitions"],
['Volunteer opportunity', "volunteer"],
['Collective action', "pledge"],
['Affinity group', "affinitygroup"]
])
end
def options_for_created_select
options_for_select([
['Last 30 days', "last30days"],
['Last 14 days',"last14days"],
['Last week', "lastweek"],
['Yesterday', "yesterday"],
['Today', "today"]
])
end
+ def tag_list_for(action)
+ action.tags.collect do |tag|
+ link_to tag.name, tag_path(tag)
+ end.join(', ')
+ end
+
end
diff --git a/app/helpers/tags_helper.rb b/app/helpers/tags_helper.rb
new file mode 100644
index 0000000..021136e
--- /dev/null
+++ b/app/helpers/tags_helper.rb
@@ -0,0 +1,21 @@
+module TagsHelper
+ def tag_cloud(tags, classes)
+ return if tags.empty?
+
+ max_count = tags.sort_by(&:count).last.count.to_f
+
+ tags.each do |tag|
+ index = ((tag.count / max_count) * (classes.size - 1)).round
+ yield tag, classes[index]
+ end
+ end
+
+ def page_entries_info(collection, tag)
+ %{Displaying entries <b>%d - %d</b> of <b>%d</b> in total that match the tag <b>%s</b>} % [
+ collection.offset + 1,
+ collection.offset + collection.length,
+ collection.total_entries,
+ tag.name
+ ]
+ end
+end
diff --git a/app/views/actions/_action.html.haml b/app/views/actions/_action.html.haml
index 22b79dd..fdfd503 100644
--- a/app/views/actions/_action.html.haml
+++ b/app/views/actions/_action.html.haml
@@ -1,30 +1,30 @@
%div[action]
= link_to action.title, action_path(action), :class => 'action-title'
.action-source
%span{:class => 'action-byline'}
Created on
= link_to action.site.name, action.site.url
by
= link_to 'TODO', ''
%br/
%span{:class => 'action-created'}
= action.created_at.to_s(:default)
%br/
%span{:class => 'action-type'} TODO
%span{:class => 'action-goal'}
%strong
Goal:
TODO
%br/
%span{:class => 'action-location'}
%strong
Location:
= action.location
%br/
%span{:class => 'action-tags'}
%strong
Tags:
- = action.tag_list.to_s
+ = tag_list_for action
%br/
= link_to action.url, action.url, :class => 'action-url'
diff --git a/app/views/actions/_search_form.html.haml b/app/views/actions/_search_form.html.haml
index b25221d..8de4e7c 100644
--- a/app/views/actions/_search_form.html.haml
+++ b/app/views/actions/_search_form.html.haml
@@ -1,33 +1,33 @@
#search_box
%h2 Find an Action
- %form
+ - form_tag actions_path, :method => :get do
%table{ :border=>"0", :cellpadding=>"0", :cellspacing=>"0" }
%tr.first
%td Search Term:
%td= text_field_tag 'search_term', nil, :size => 22
%td
= submit_tag 'Search'
= submit_tag 'Google Map'
= submit_tag 'Tag Cloud'
= submit_tag 'Random'
%tr
%td Type of Action:
%td= select_tag 'action_type', options_for_action_type_select
%td
Created:
= select_tag 'create', options_for_created_select
- Site.find(:all, :order => :name).each_slice(4) do |sites|
.platform_select
- sites.each do |site|
= check_box_tag site.id, site.name, true
= site.name
%br/
%br{:clear => 'all'}/
\ No newline at end of file
diff --git a/app/views/map/index.html.haml b/app/views/map/index.html.haml
index 5cd1b75..77d049f 100644
--- a/app/views/map/index.html.haml
+++ b/app/views/map/index.html.haml
@@ -1,5 +1,8 @@
- content_for :map_headers do
= map_header(@gmap)
= map_body(@gmap)
-#gmap{:style => "height:400px;width:400px"}
+= render :partial => 'actions/search_form'
+
+
+#gmap
diff --git a/app/views/tags/index.html.haml b/app/views/tags/index.html.haml
new file mode 100644
index 0000000..69ad72e
--- /dev/null
+++ b/app/views/tags/index.html.haml
@@ -0,0 +1,5 @@
+= render :partial => 'actions/search_form'
+
+#tag_cloud
+ - tag_cloud @tags, %w(tag1 tag2 tag2 tag4) do |tag, css_class|
+ = link_to tag.name, tag_path(tag), :class => css_class
diff --git a/app/views/tags/show.html.haml b/app/views/tags/show.html.haml
new file mode 100644
index 0000000..18dc4d9
--- /dev/null
+++ b/app/views/tags/show.html.haml
@@ -0,0 +1,15 @@
+= render :partial => 'actions/search_form'
+
+#tag_cloud
+ - tag_cloud @tags, %w(tag1 tag2 tag2 tag4) do |tag, css_class|
+ - if tag == @tag
+ = tag.name
+ - else
+ = link_to tag.name, tag_path(tag), :class => css_class
+
+
+#search_results
+ %h2 Results
+ = page_entries_info @actions, @tag
+ = render :partial => 'actions/action', :collection => @actions
+ = will_paginate @actions
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index a646b96..2b5d222 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,38 +1,38 @@
ActionController::Routing::Routes.draw do |map|
- map.resources :actions
+ map.resources :actions, :tags, :map
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.connect '', :controller => 'actions', :action => 'index'
end
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index c990e5c..47d5948 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,115 +1,131 @@
a
:color #3366cc
:text-decoration none
h2
:margin 0px 0px 5px 0px
p
:margin 3px 3px 0px 3px
// Block Elements
-#search_results
+#search_results, #tag_cloud
:width 710px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 0px 10px
// Search box
#search_box
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:background-color #e9f3f1
:padding 10px 10px 30px 10px
table
td
:padding-right 5px
:padding-top 10px
.first
td
:padding-top 0
.platform_select
:width 170px
:float left
:margin-top 10px
// Results Elements
.action
:width 700px
:margin-bottom 30px
.action-title
:margin-top 5px
:margin-bottom 5px
:font-size 160%
:display block
.action-source
:width 320px
:float right
:margin-left 25px
:text-align right
.action-goal
.action-location
.action-tags
.action-url
:margin-top 10px
:display block
:color #ff6600
.action-url a
.action-url a:hover
.action-byline
.action-byline a
:font-weight bold
.action-byline a:hover
.action-created
.action-type
:font-style italic
// Pagination
.pagination
:padding 3px
:margin 3px
.pagination a
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:text-decoration none
:color #3366cc
.pagination a:hover, .pagination a:active
:border 1px solid #3366cc
:color #000
.pagination span.current
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #3366cc
:font-weight bold
:background-color #3366cc
:color #FFF
.pagination span.disabled
:padding 2px 5px 2px 5px
:margin 2px
:border 1px solid #eee
:color #ddd
+// Map
+#gmap
+ :height 400px
+ :width 710px
+ :margin-top 20px
+
+// Tags
+.tag1
+ :font-size 1.0em
+.tag2
+ :font-size 1.2em
+.tag3
+ :font-size 1.4em
+.tag4
+ :font-size 1.6em
+
diff --git a/spec/controllers/tags_controller_spec.rb b/spec/controllers/tags_controller_spec.rb
new file mode 100644
index 0000000..8cd029f
--- /dev/null
+++ b/spec/controllers/tags_controller_spec.rb
@@ -0,0 +1,10 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe TagsController do
+
+ #Delete this example and add some real ones
+ it "should use TagsController" do
+ controller.should be_an_instance_of(TagsController)
+ end
+
+end
diff --git a/spec/helpers/tags_helper_spec.rb b/spec/helpers/tags_helper_spec.rb
new file mode 100644
index 0000000..8ded44b
--- /dev/null
+++ b/spec/helpers/tags_helper_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe TagsHelper do
+
+ #Delete this example and add some real ones or delete this file
+ it "should include the TagsHelper" do
+ included_modules = self.metaclass.send :included_modules
+ included_modules.should include(TagsHelper)
+ end
+
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/lib/tag.rb b/vendor/plugins/acts_as_taggable_on_steroids/lib/tag.rb
index 91859d5..6048d64 100644
--- a/vendor/plugins/acts_as_taggable_on_steroids/lib/tag.rb
+++ b/vendor/plugins/acts_as_taggable_on_steroids/lib/tag.rb
@@ -1,26 +1,30 @@
class Tag < ActiveRecord::Base
has_many :taggings
validates_presence_of :name
validates_uniqueness_of :name
cattr_accessor :destroy_unused
self.destroy_unused = false
# LIKE is used for cross-database case-insensitivity
def self.find_or_create_with_like_by_name(name)
find(:first, :conditions => ["name LIKE ?", name]) || create(:name => name)
end
def ==(object)
super || (object.is_a?(Tag) && name == object.name)
end
def to_s
name
end
+ def to_param
+ name
+ end
+
def count
read_attribute(:count).to_i
end
end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
b9128894952ced07729f9f91ac0d526812ca1bcf
|
Pagination roughly in place, and removed make_resourceful
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
index 0da610e..0eb8283 100644
--- a/app/controllers/actions_controller.rb
+++ b/app/controllers/actions_controller.rb
@@ -1,16 +1,19 @@
class ActionsController < ApplicationController
- make_resourceful do
- actions :index, :show
- response_for :index do |format|
+
+ def index
+ @actions = Action.paginate(:all, :page => params[:page], :order => 'created_at DESC')
+ respond_to do |format|
format.html
format.xml
end
- response_for :show do |format|
+
+ end
+
+ def show
+ @action = Action.find(params[:id])
+ respond_to do |format|
format.html
format.xml
- end
+ end
end
-
-
-
end
diff --git a/app/models/action.rb b/app/models/action.rb
index 0d2bd41..1d4ac60 100644
--- a/app/models/action.rb
+++ b/app/models/action.rb
@@ -1,67 +1,71 @@
class Action < ActiveRecord::Base
include GeoKit::Geocoders
belongs_to :feed
delegate :site, :to => :feed
acts_as_taggable
acts_as_mappable :lat_column_name => :latitude, :lng_column_name => :longitude
before_save :look_for_tags, :look_for_location, :geocode_lookup
def update_from_feed_item(item)
puts " -- Action: #{item.title}"
self.title = item.title
self.url = item.link
self.description = item.description
self.created_at = item.pubDate if item.pubDate
figure_out_address_from(item)
end
def description=(new_description)
write_attribute(:description, fix_quoted_html(new_description))
end
+ def self.per_page
+ 10
+ end
+
protected
def fix_quoted_html(text)
text.gsub(/\</, '<').gsub(/\>/, '>')
end
def look_for_location
if feed.location_finder and self.description
match = self.description.match(feed.location_finder.to_s)
self.location = match[1] if match and match[1]
puts " Found Location: #{self.location}"
end
end
def look_for_tags
if feed.tag_finder and description
match = description.match(feed.tag_finder.to_s)
self.tag_list = match[1] if match and match[1]
puts " Found Tags: #{self.tag_list}"
end
end
def figure_out_address_from(item)
if item.geo_lat and item.geo_long
self.latitude = item.geo_lat
self.longitude = item.geo_long
end
end
def geocode_lookup
unless location.nil? or location.empty?
result = MultiGeocoder.geocode(location)
if result.success
self.latitude = result.lat
self.longitude = result.lng
puts " Geocoding Successful - #{result}"
end
end
end
end
diff --git a/app/views/actions/_action.html.haml b/app/views/actions/_action.html.haml
index 403ca18..22b79dd 100644
--- a/app/views/actions/_action.html.haml
+++ b/app/views/actions/_action.html.haml
@@ -1,30 +1,30 @@
%div[action]
- = link_to action.title, object_path(action), :class => 'action-title'
+ = link_to action.title, action_path(action), :class => 'action-title'
.action-source
%span{:class => 'action-byline'}
Created on
= link_to action.site.name, action.site.url
by
= link_to 'TODO', ''
%br/
%span{:class => 'action-created'}
= action.created_at.to_s(:default)
%br/
%span{:class => 'action-type'} TODO
%span{:class => 'action-goal'}
%strong
Goal:
TODO
%br/
%span{:class => 'action-location'}
%strong
Location:
= action.location
%br/
%span{:class => 'action-tags'}
%strong
Tags:
= action.tag_list.to_s
%br/
= link_to action.url, action.url, :class => 'action-url'
diff --git a/app/views/actions/index.html.haml b/app/views/actions/index.html.haml
index 05c5576..f3346f9 100644
--- a/app/views/actions/index.html.haml
+++ b/app/views/actions/index.html.haml
@@ -1,10 +1,11 @@
= render :partial => 'search_form'
#search_results
%h2 Results
- = render :partial => 'action', :collection => current_objects
-
+ = page_entries_info @actions
+ = render :partial => 'action', :collection => @actions
+ = will_paginate @actions
diff --git a/app/views/actions/index.xml.haml b/app/views/actions/index.xml.haml
index c5994ac..87d157f 100644
--- a/app/views/actions/index.xml.haml
+++ b/app/views/actions/index.xml.haml
@@ -1 +1 @@
-= current_objects.to_xml
\ No newline at end of file
+= @actions.to_xml
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index 48d3f1b..a646b96 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,37 +1,38 @@
ActionController::Routing::Routes.draw do |map|
map.resources :actions
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
+ map.connect '', :controller => 'actions', :action => 'index'
end
diff --git a/public/index.html b/public/index.html
deleted file mode 100644
index 84b7b57..0000000
--- a/public/index.html
+++ /dev/null
@@ -1,277 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html>
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <title>Ruby on Rails: Welcome aboard</title>
- <style type="text/css" media="screen">
- body {
- margin: 0;
- margin-bottom: 25px;
- padding: 0;
- background-color: #f0f0f0;
- font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
- font-size: 13px;
- color: #333;
- }
-
- h1 {
- font-size: 28px;
- color: #000;
- }
-
- a {color: #03c}
- a:hover {
- background-color: #03c;
- color: white;
- text-decoration: none;
- }
-
-
- #page {
- background-color: #f0f0f0;
- width: 750px;
- margin: 0;
- margin-left: auto;
- margin-right: auto;
- }
-
- #content {
- float: left;
- background-color: white;
- border: 3px solid #aaa;
- border-top: none;
- padding: 25px;
- width: 500px;
- }
-
- #sidebar {
- float: right;
- width: 175px;
- }
-
- #footer {
- clear: both;
- }
-
-
- #header, #about, #getting-started {
- padding-left: 75px;
- padding-right: 30px;
- }
-
-
- #header {
- background-image: url("images/rails.png");
- background-repeat: no-repeat;
- background-position: top left;
- height: 64px;
- }
- #header h1, #header h2 {margin: 0}
- #header h2 {
- color: #888;
- font-weight: normal;
- font-size: 16px;
- }
-
-
- #about h3 {
- margin: 0;
- margin-bottom: 10px;
- font-size: 14px;
- }
-
- #about-content {
- background-color: #ffd;
- border: 1px solid #fc0;
- margin-left: -11px;
- }
- #about-content table {
- margin-top: 10px;
- margin-bottom: 10px;
- font-size: 11px;
- border-collapse: collapse;
- }
- #about-content td {
- padding: 10px;
- padding-top: 3px;
- padding-bottom: 3px;
- }
- #about-content td.name {color: #555}
- #about-content td.value {color: #000}
-
- #about-content.failure {
- background-color: #fcc;
- border: 1px solid #f00;
- }
- #about-content.failure p {
- margin: 0;
- padding: 10px;
- }
-
-
- #getting-started {
- border-top: 1px solid #ccc;
- margin-top: 25px;
- padding-top: 15px;
- }
- #getting-started h1 {
- margin: 0;
- font-size: 20px;
- }
- #getting-started h2 {
- margin: 0;
- font-size: 14px;
- font-weight: normal;
- color: #333;
- margin-bottom: 25px;
- }
- #getting-started ol {
- margin-left: 0;
- padding-left: 0;
- }
- #getting-started li {
- font-size: 18px;
- color: #888;
- margin-bottom: 25px;
- }
- #getting-started li h2 {
- margin: 0;
- font-weight: normal;
- font-size: 18px;
- color: #333;
- }
- #getting-started li p {
- color: #555;
- font-size: 13px;
- }
-
-
- #search {
- margin: 0;
- padding-top: 10px;
- padding-bottom: 10px;
- font-size: 11px;
- }
- #search input {
- font-size: 11px;
- margin: 2px;
- }
- #search-text {width: 170px}
-
-
- #sidebar ul {
- margin-left: 0;
- padding-left: 0;
- }
- #sidebar ul h3 {
- margin-top: 25px;
- font-size: 16px;
- padding-bottom: 10px;
- border-bottom: 1px solid #ccc;
- }
- #sidebar li {
- list-style-type: none;
- }
- #sidebar ul.links li {
- margin-bottom: 5px;
- }
-
- </style>
- <script type="text/javascript" src="javascripts/prototype.js"></script>
- <script type="text/javascript" src="javascripts/effects.js"></script>
- <script type="text/javascript">
- function about() {
- if (Element.empty('about-content')) {
- new Ajax.Updater('about-content', 'rails/info/properties', {
- method: 'get',
- onFailure: function() {Element.classNames('about-content').add('failure')},
- onComplete: function() {new Effect.BlindDown('about-content', {duration: 0.25})}
- });
- } else {
- new Effect[Element.visible('about-content') ?
- 'BlindUp' : 'BlindDown']('about-content', {duration: 0.25});
- }
- }
-
- window.onload = function() {
- $('search-text').value = '';
- $('search').onsubmit = function() {
- $('search-text').value = 'site:rubyonrails.org ' + $F('search-text');
- }
- }
- </script>
- </head>
- <body>
- <div id="page">
- <div id="sidebar">
- <ul id="sidebar-items">
- <li>
- <form id="search" action="http://www.google.com/search" method="get">
- <input type="hidden" name="hl" value="en" />
- <input type="text" id="search-text" name="q" value="site:rubyonrails.org " />
- <input type="submit" value="Search" /> the Rails site
- </form>
- </li>
-
- <li>
- <h3>Join the community</h3>
- <ul class="links">
- <li><a href="http://www.rubyonrails.org/">Ruby on Rails</a></li>
- <li><a href="http://weblog.rubyonrails.org/">Official weblog</a></li>
- <li><a href="http://lists.rubyonrails.org/">Mailing lists</a></li>
- <li><a href="http://wiki.rubyonrails.org/rails/pages/IRC">IRC channel</a></li>
- <li><a href="http://wiki.rubyonrails.org/">Wiki</a></li>
- <li><a href="http://dev.rubyonrails.org/">Bug tracker</a></li>
- </ul>
- </li>
-
- <li>
- <h3>Browse the documentation</h3>
- <ul class="links">
- <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
- <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
- <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
- </ul>
- </li>
- </ul>
- </div>
-
- <div id="content">
- <div id="header">
- <h1>Welcome aboard</h1>
- <h2>You’re riding Ruby on Rails!</h2>
- </div>
-
- <div id="about">
- <h3><a href="rails/info/properties" onclick="about(); return false">About your application’s environment</a></h3>
- <div id="about-content" style="display: none"></div>
- </div>
-
- <div id="getting-started">
- <h1>Getting started</h1>
- <h2>Here’s how to get rolling:</h2>
-
- <ol>
- <li>
- <h2>Create your databases and edit <tt>config/database.yml</tt></h2>
- <p>Rails needs to know your login and password.</p>
- </li>
-
- <li>
- <h2>Use <tt>script/generate</tt> to create your models and controllers</h2>
- <p>To see all available options, run it without parameters.</p>
- </li>
-
- <li>
- <h2>Set up a default route and remove or rename this file</h2>
- <p>Routes are set up in config/routes.rb.</p>
- </li>
- </ol>
- </div>
- </div>
-
- <div id="footer"> </div>
- </div>
- </body>
-</html>
\ No newline at end of file
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index 549a935..c990e5c 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,85 +1,115 @@
a
:color #3366cc
:text-decoration none
h2
:margin 0px 0px 5px 0px
p
:margin 3px 3px 0px 3px
// Block Elements
#search_results
:width 710px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:padding 10px 10px 0px 10px
// Search box
#search_box
:width 700px
:font-family Arial, Helvetica, sans-serif
:font-size 14px
:color #000
:background-color #e9f3f1
:padding 10px 10px 30px 10px
table
td
:padding-right 5px
:padding-top 10px
.first
td
:padding-top 0
.platform_select
:width 170px
:float left
:margin-top 10px
// Results Elements
.action
:width 700px
:margin-bottom 30px
.action-title
:margin-top 5px
:margin-bottom 5px
:font-size 160%
:display block
.action-source
:width 320px
:float right
:margin-left 25px
:text-align right
.action-goal
.action-location
.action-tags
.action-url
:margin-top 10px
:display block
:color #ff6600
.action-url a
.action-url a:hover
.action-byline
.action-byline a
:font-weight bold
.action-byline a:hover
.action-created
.action-type
:font-style italic
+// Pagination
+.pagination
+ :padding 3px
+ :margin 3px
+
+.pagination a
+ :padding 2px 5px 2px 5px
+ :margin 2px
+ :border 1px solid #3366cc
+ :text-decoration none
+ :color #3366cc
+
+.pagination a:hover, .pagination a:active
+ :border 1px solid #3366cc
+ :color #000
+
+.pagination span.current
+ :padding 2px 5px 2px 5px
+ :margin 2px
+ :border 1px solid #3366cc
+ :font-weight bold
+ :background-color #3366cc
+ :color #FFF
+
+.pagination span.disabled
+ :padding 2px 5px 2px 5px
+ :margin 2px
+ :border 1px solid #eee
+ :color #ddd
+
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
bc5d2dcf2509865c7ddfcc4d2a83a20e96e012d3
|
Adding will_paginate
|
diff --git a/vendor/plugins/will_paginate/.gitignore b/vendor/plugins/will_paginate/.gitignore
new file mode 100644
index 0000000..6ac3a1f
--- /dev/null
+++ b/vendor/plugins/will_paginate/.gitignore
@@ -0,0 +1,2 @@
+/pkg
+/doc
diff --git a/vendor/plugins/will_paginate/LICENSE b/vendor/plugins/will_paginate/LICENSE
new file mode 100644
index 0000000..96a48cb
--- /dev/null
+++ b/vendor/plugins/will_paginate/LICENSE
@@ -0,0 +1,18 @@
+Copyright (c) 2007 PJ Hyett and Mislav MarohniÄ
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/plugins/will_paginate/README b/vendor/plugins/will_paginate/README
new file mode 100644
index 0000000..162c189
--- /dev/null
+++ b/vendor/plugins/will_paginate/README
@@ -0,0 +1,180 @@
+= WillPaginate
+
+Pagination is just limiting the number of records displayed. Why should you let
+it get in your way while developing, then? This plugin makes magic happen. Did
+you ever want to be able to do just this on a model:
+
+ Post.paginate :page => 1, :order => 'created_at DESC'
+
+... and then render the page links with a single view helper? Well, now you
+can.
+
+Ryan Bates made an awesome screencast[http://railscasts.com/episodes/51],
+check it out.
+
+Your mind reels with questions? Join our Google
+group[http://groups.google.com/group/will_paginate].
+
+== Installation
+
+Will Paginate officially supports Rails versions 1.2.6 and 2.0.x.
+
+Previously, the plugin was available on the following SVN location:
+
+ svn://errtheblog.com/svn/plugins/will_paginate
+
+In February 2008, it moved to GitHub[http://github.com/mislav/will_paginate/tree]
+to be tracked with git. The SVN repo continued to have updates, but not
+forever. Therefore you should switch to using the gem:
+
+ gem install will_paginate --no-ri
+
+After that, you can remove the plugin from your applications and add
+a simple require to the end of config/environment.rb:
+
+ require 'will_paginate'
+
+That's it, just remember to install the gem on all machines that
+you are deploying to.
+
+The second option is to download and extract the tarball from GitHub. Here is the
+link for downloading the current state of the master branch:
+http://github.com/mislav/will_paginate/tarball/master
+
+Extract it to <tt>vendor/plugins</tt>. The directory will have a default name
+like "mislav-will_paginate-master"; you can rename it to "will_paginate" for
+simplicity.
+
+== Example usage
+
+Use a paginate finder in the controller:
+
+ @posts = Post.paginate_by_board_id @board.id, :page => params[:page], :order => 'updated_at DESC'
+
+Yeah, +paginate+ works just like +find+ -- it just doesn't fetch all the
+records. Don't forget to tell it which page you want, or it will complain!
+Read more on WillPaginate::Finder::ClassMethods.
+
+Render the posts in your view like you would normally do. When you need to render
+pagination, just stick this in:
+
+ <%= will_paginate @posts %>
+
+You're done. (Copy and paste the example fancy CSS styles from the bottom.) You
+can find the option list at WillPaginate::ViewHelpers.
+
+How does it know how much items to fetch per page? It asks your model by calling
+its <tt>per_page</tt> class method. You can define it like this:
+
+ class Post < ActiveRecord::Base
+ cattr_reader :per_page
+ @@per_page = 50
+ end
+
+... or like this:
+
+ class Post < ActiveRecord::Base
+ def self.per_page
+ 50
+ end
+ end
+
+... or don't worry about it at all. WillPaginate defines it to be <b>30</b> by default.
+But you can always specify the count explicitly when calling +paginate+:
+
+ @posts = Post.paginate :page => params[:page], :per_page => 50
+
+The +paginate+ finder wraps the original finder and returns your resultset that now has
+some new properties. You can use the collection as you would with any ActiveRecord
+resultset. WillPaginate view helpers also need that object to be able to render pagination:
+
+ <ol>
+ <% for post in @posts -%>
+ <li>Render `post` in some nice way.</li>
+ <% end -%>
+ </ol>
+
+ <p>Now let's render us some pagination!</p>
+ <%= will_paginate @posts %>
+
+More detailed documentation:
+
+* WillPaginate::Finder::ClassMethods for pagination on your models;
+* WillPaginate::ViewHelpers for your views.
+
+== Oh noes, a bug!
+
+Tell us what happened so we can fix it, quick! Issues are filed on the Lighthouse project:
+http://err.lighthouseapp.com/projects/466-plugins/tickets?q=tagged:will_paginate
+
+Steps to make an awesome bug report:
+
+1. Run <tt>rake test</tt> in the <i>will_paginate</i> directory. (You will need SQLite3.)
+ Copy the output if there are failing tests.
+2. Register on Lighthouse to create a new ticket.
+3. Write a descriptive, short title. Provide as much info as you can in the body.
+ Assign the ticket to Mislav and tag it with meaningful tags, <tt>"will_paginate"</tt>
+ being among them.
+4. Yay! You will be notified on updates automatically.
+
+Here is an example of a great bug report and patch:
+http://err.lighthouseapp.com/projects/466/tickets/172-total_entries-ignored-in-paginate_by_sql
+
+== Authors, credits, contact
+
+Want to discuss, request features, ask questions? Join the Google group:
+http://groups.google.com/group/will_paginate
+
+Authors:: Mislav MarohniÄ, PJ Hyett
+Original announcement:: http://errtheblog.com/post/929
+Original PHP source:: http://www.strangerstudios.com/sandbox/pagination/diggstyle.php
+
+All these people helped making will_paginate what it is now with their code
+contributions or simply awesome ideas:
+
+Chris Wanstrath, Dr. Nic Williams, K. Adam Christensen, Mike Garey, Bence
+Golda, Matt Aimonetti, Charles Brian Quinn, Desi McAdam, James Coglan, Matijs
+van Zuijlen, Maria, Brendan Ribera, Todd Willey, Bryan Helmkamp, Jan Berkel.
+
+== Usable pagination in the UI
+
+Copy the following CSS into your stylesheet for a good start:
+
+ .pagination {
+ padding: 3px;
+ margin: 3px;
+ }
+ .pagination a {
+ padding: 2px 5px 2px 5px;
+ margin: 2px;
+ border: 1px solid #aaaadd;
+ text-decoration: none;
+ color: #000099;
+ }
+ .pagination a:hover, .pagination a:active {
+ border: 1px solid #000099;
+ color: #000;
+ }
+ .pagination span.current {
+ padding: 2px 5px 2px 5px;
+ margin: 2px;
+ border: 1px solid #000099;
+ font-weight: bold;
+ background-color: #000099;
+ color: #FFF;
+ }
+ .pagination span.disabled {
+ padding: 2px 5px 2px 5px;
+ margin: 2px;
+ border: 1px solid #eee;
+ color: #ddd;
+ }
+
+More reading about pagination as design pattern:
+
+* Pagination 101:
+ http://kurafire.net/log/archive/2007/06/22/pagination-101
+* Pagination gallery:
+ http://www.smashingmagazine.com/2007/11/16/pagination-gallery-examples-and-good-practices/
+* Pagination on Yahoo Design Pattern Library:
+ http://developer.yahoo.com/ypatterns/parent.php?pattern=pagination
diff --git a/vendor/plugins/will_paginate/Rakefile b/vendor/plugins/will_paginate/Rakefile
new file mode 100644
index 0000000..e21df94
--- /dev/null
+++ b/vendor/plugins/will_paginate/Rakefile
@@ -0,0 +1,65 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the will_paginate plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+# I want to specify environment variables at call time
+class EnvTestTask < Rake::TestTask
+ attr_accessor :env
+
+ def ruby(*args)
+ env.each { |key, value| ENV[key] = value } if env
+ super
+ env.keys.each { |key| ENV.delete key } if env
+ end
+end
+
+for configuration in %w( sqlite3 mysql postgres )
+ EnvTestTask.new("test_#{configuration}") do |t|
+ t.pattern = 'test/finder_test.rb'
+ t.verbose = true
+ t.env = { 'DB' => configuration }
+ end
+end
+
+task :test_databases => %w(test_mysql test_sqlite3 test_postgres)
+
+desc %{Test everything on SQLite3, MySQL and PostgreSQL}
+task :test_full => %w(test test_mysql test_postgres)
+
+desc %{Test everything with Rails 1.2.x and 2.0.x gems}
+task :test_all do
+ all = Rake::Task['test_full']
+ ENV['RAILS_VERSION'] = '~>1.2.6'
+ all.invoke
+ # reset the invoked flag
+ %w( test_full test test_mysql test_postgres ).each do |name|
+ Rake::Task[name].instance_variable_set '@already_invoked', false
+ end
+ # do it again
+ ENV['RAILS_VERSION'] = '~>2.0.2'
+ all.invoke
+end
+
+desc 'Generate RDoc documentation for the will_paginate plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ files = ['README', 'LICENSE', 'lib/**/*.rb']
+ rdoc.rdoc_files.add(files)
+ rdoc.main = "README" # page to start on
+ rdoc.title = "will_paginate"
+
+ templates = %w[/Users/chris/ruby/projects/err/rock/template.rb /var/www/rock/template.rb]
+ rdoc.template = templates.find { |t| File.exists? t }
+
+ rdoc.rdoc_dir = 'doc' # rdoc output folder
+ rdoc.options << '--inline-source'
+ rdoc.options << '--charset=UTF-8'
+end
diff --git a/vendor/plugins/will_paginate/init.rb b/vendor/plugins/will_paginate/init.rb
new file mode 100644
index 0000000..dc0572d
--- /dev/null
+++ b/vendor/plugins/will_paginate/init.rb
@@ -0,0 +1,2 @@
+require 'will_paginate'
+WillPaginate.enable
diff --git a/vendor/plugins/will_paginate/lib/will_paginate.rb b/vendor/plugins/will_paginate/lib/will_paginate.rb
new file mode 100644
index 0000000..c0a5ce1
--- /dev/null
+++ b/vendor/plugins/will_paginate/lib/will_paginate.rb
@@ -0,0 +1,65 @@
+require 'active_support'
+
+# = You *will* paginate!
+#
+# First read about WillPaginate::Finder::ClassMethods, then see
+# WillPaginate::ViewHelpers. The magical array you're handling in-between is
+# WillPaginate::Collection.
+#
+# Happy paginating!
+module WillPaginate
+ class << self
+ # shortcut for <tt>enable_actionpack; enable_activerecord</tt>
+ def enable
+ enable_actionpack
+ enable_activerecord
+ end
+
+ # mixes in WillPaginate::ViewHelpers in ActionView::Base
+ def enable_actionpack
+ return if ActionView::Base.instance_methods.include? 'will_paginate'
+ require 'will_paginate/view_helpers'
+ ActionView::Base.class_eval { include ViewHelpers }
+
+ if ActionController::Base.respond_to? :rescue_responses
+ ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found
+ end
+ end
+
+ # mixes in WillPaginate::Finder in ActiveRecord::Base and classes that deal
+ # with associations
+ def enable_activerecord
+ return if ActiveRecord::Base.respond_to? :paginate
+ require 'will_paginate/finder'
+ ActiveRecord::Base.class_eval { include Finder }
+
+ associations = ActiveRecord::Associations
+ collection = associations::AssociationCollection
+
+ # to support paginating finders on associations, we have to mix in the
+ # method_missing magic from WillPaginate::Finder::ClassMethods to AssociationProxy
+ # subclasses, but in a different way for Rails 1.2.x and 2.0
+ (collection.instance_methods.include?(:create!) ?
+ collection : collection.subclasses.map(&:constantize)
+ ).push(associations::HasManyThroughAssociation).each do |klass|
+ klass.class_eval do
+ include Finder::ClassMethods
+ alias_method_chain :method_missing, :paginate
+ end
+ end
+ end
+ end
+
+ module Deprecation #:nodoc:
+ extend ActiveSupport::Deprecation
+
+ def self.warn(message, callstack = caller)
+ message = 'WillPaginate: ' + message.strip.gsub(/ {3,}/, ' ')
+ behavior.call(message, callstack) if behavior && !silenced?
+ end
+
+ def self.silenced?
+ ActiveSupport::Deprecation.silenced?
+ end
+ end
+end
diff --git a/vendor/plugins/will_paginate/lib/will_paginate/collection.rb b/vendor/plugins/will_paginate/lib/will_paginate/collection.rb
new file mode 100644
index 0000000..f796131
--- /dev/null
+++ b/vendor/plugins/will_paginate/lib/will_paginate/collection.rb
@@ -0,0 +1,132 @@
+require 'will_paginate'
+
+module WillPaginate
+ # = OMG, invalid page number!
+ # This is an ArgumentError raised in case a page was requested that is either
+ # zero or negative number. You should decide how do deal with such errors in
+ # the controller.
+ #
+ # This error is *not* raised when a page further than the last page is
+ # requested. Use <tt>WillPaginate::Collection#out_of_bounds?</tt> method to
+ # check for those cases and manually deal with them as you see fit.
+ class InvalidPage < ArgumentError
+ def initialize(page, page_num)
+ super "#{page.inspect} given as value, which translates to '#{page_num}' as page number"
+ end
+ end
+
+ # Arrays returned from paginating finds are, in fact, instances of this.
+ # You may think of WillPaginate::Collection as an ordinary array with some
+ # extra properties. Those properties are used by view helpers to generate
+ # correct page links.
+ #
+ # WillPaginate::Collection also assists in rolling out your own pagination
+ # solutions: see +create+.
+ #
+ class Collection < Array
+ attr_reader :current_page, :per_page, :total_entries
+
+ # Arguments to this constructor are the current page number, per-page limit
+ # and the total number of entries. The last argument is optional because it
+ # is best to do lazy counting; in other words, count *conditionally* after
+ # populating the collection using the +replace+ method.
+ #
+ def initialize(page, per_page, total = nil)
+ @current_page = page.to_i
+ raise InvalidPage.new(page, @current_page) if @current_page < 1
+ @per_page = per_page.to_i
+ raise ArgumentError, "`per_page` setting cannot be less than 1 (#{@per_page} given)" if @per_page < 1
+
+ self.total_entries = total if total
+ end
+
+ # Just like +new+, but yields the object after instantiation and returns it
+ # afterwards. This is very useful for manual pagination:
+ #
+ # @entries = WillPaginate::Collection.create(1, 10) do |pager|
+ # result = Post.find(:all, :limit => pager.per_page, :offset => pager.offset)
+ # # inject the result array into the paginated collection:
+ # pager.replace(result)
+ #
+ # unless pager.total_entries
+ # # the pager didn't manage to guess the total count, do it manually
+ # pager.total_entries = Post.count
+ # end
+ # end
+ #
+ # The possibilities with this are endless. For another example, here is how
+ # WillPaginate used to define pagination for Array instances:
+ #
+ # Array.class_eval do
+ # def paginate(page = 1, per_page = 15)
+ # WillPaginate::Collection.create(page, per_page, size) do |pager|
+ # pager.replace self[pager.offset, pager.per_page].to_a
+ # end
+ # end
+ # end
+ #
+ def self.create(page, per_page, total = nil, &block)
+ pager = new(page, per_page, total)
+ yield pager
+ pager
+ end
+
+ # The total number of pages.
+ def page_count
+ @total_pages
+ end
+
+ # Helper method that is true when someone tries to fetch a page with a
+ # larger number than the last page. Can be used in combination with flashes
+ # and redirecting.
+ def out_of_bounds?
+ current_page > page_count
+ end
+
+ # Current offset of the paginated collection. If we're on the first page,
+ # it is always 0. If we're on the 2nd page and there are 30 entries per page,
+ # the offset is 30. This property is useful if you want to render ordinals
+ # besides your records: simply start with offset + 1.
+ #
+ def offset
+ (current_page - 1) * per_page
+ end
+
+ # current_page - 1 or nil if there is no previous page
+ def previous_page
+ current_page > 1 ? (current_page - 1) : nil
+ end
+
+ # current_page + 1 or nil if there is no next page
+ def next_page
+ current_page < page_count ? (current_page + 1) : nil
+ end
+
+ def total_entries=(number)
+ @total_entries = number.to_i
+ @total_pages = (@total_entries / per_page.to_f).ceil
+ end
+
+ # This is a magic wrapper for the original Array#replace method. It serves
+ # for populating the paginated collection after initialization.
+ #
+ # Why magic? Because it tries to guess the total number of entries judging
+ # by the size of given array. If it is shorter than +per_page+ limit, then we
+ # know we're on the last page. This trick is very useful for avoiding
+ # unnecessary hits to the database to do the counting after we fetched the
+ # data for the current page.
+ #
+ # However, after using +replace+ you should always test the value of
+ # +total_entries+ and set it to a proper value if it's +nil+. See the example
+ # in +create+.
+ def replace(array)
+ returning super do
+ # The collection is shorter then page limit? Rejoice, because
+ # then we know that we are on the last page!
+ if total_entries.nil? and length > 0 and length < per_page
+ self.total_entries = offset + length
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb b/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb
new file mode 100644
index 0000000..461153f
--- /dev/null
+++ b/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb
@@ -0,0 +1,80 @@
+require 'will_paginate'
+require 'set'
+
+unless Hash.instance_methods.include? 'except'
+ Hash.class_eval do
+ # Returns a new hash without the given keys.
+ def except(*keys)
+ rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
+ reject { |key,| rejected.include?(key) }
+ end
+
+ # Replaces the hash without only the given keys.
+ def except!(*keys)
+ replace(except(*keys))
+ end
+ end
+end
+
+unless Hash.instance_methods.include? 'slice'
+ Hash.class_eval do
+ # Returns a new hash with only the given keys.
+ def slice(*keys)
+ allowed = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
+ reject { |key,| !allowed.include?(key) }
+ end
+
+ # Replaces the hash with only the given keys.
+ def slice!(*keys)
+ replace(slice(*keys))
+ end
+ end
+end
+
+unless Hash.instance_methods.include? 'rec_merge!'
+ Hash.class_eval do
+ # Same as Hash#merge!, but recursively merges sub-hashes
+ # (stolen from Haml)
+ def rec_merge!(other)
+ other.each do |key, other_value|
+ value = self[key]
+ if value.is_a?(Hash) and other_value.is_a?(Hash)
+ value.rec_merge! other_value
+ else
+ self[key] = other_value
+ end
+ end
+ self
+ end
+ end
+end
+
+require 'will_paginate/collection'
+
+unless Array.instance_methods.include? 'paginate'
+ # http://www.desimcadam.com/archives/8
+ Array.class_eval do
+ def paginate(options_or_page = {}, per_page = nil)
+ if options_or_page.nil? or Fixnum === options_or_page
+ if defined? WillPaginate::Deprecation
+ WillPaginate::Deprecation.warn <<-DEPR
+ Array#paginate now conforms to the main, ActiveRecord::Base#paginate API. You should \
+ call it with a parameters hash (:page, :per_page). The old API (numbers as arguments) \
+ has been deprecated and is going to be unsupported in future versions of will_paginate.
+ DEPR
+ end
+ page = options_or_page
+ options = {}
+ else
+ options = options_or_page
+ page = options[:page]
+ raise ArgumentError, "wrong number of arguments (1 hash or 2 Fixnums expected)" if per_page
+ per_page = options[:per_page]
+ end
+
+ WillPaginate::Collection.create(page || 1, per_page || 30, options[:total_entries] || size) do |pager|
+ pager.replace self[pager.offset, pager.per_page].to_a
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/will_paginate/lib/will_paginate/finder.rb b/vendor/plugins/will_paginate/lib/will_paginate/finder.rb
new file mode 100644
index 0000000..5d2d73c
--- /dev/null
+++ b/vendor/plugins/will_paginate/lib/will_paginate/finder.rb
@@ -0,0 +1,214 @@
+require 'will_paginate/core_ext'
+
+module WillPaginate
+ # A mixin for ActiveRecord::Base. Provides +per_page+ class method
+ # and makes +paginate+ finders possible with some method_missing magic.
+ #
+ # Find out more in WillPaginate::Finder::ClassMethods
+ #
+ module Finder
+ def self.included(base)
+ base.extend ClassMethods
+ class << base
+ alias_method_chain :method_missing, :paginate
+ # alias_method_chain :find_every, :paginate
+ define_method(:per_page) { 30 } unless respond_to?(:per_page)
+ end
+ end
+
+ # = Paginating finders for ActiveRecord models
+ #
+ # WillPaginate adds +paginate+ and +per_page+ methods to ActiveRecord::Base
+ # class methods and associations. It also hooks into +method_missing+ to
+ # intercept pagination calls to dynamic finders such as
+ # +paginate_by_user_id+ and translate them to ordinary finders
+ # (+find_all_by_user_id+ in this case).
+ #
+ # In short, paginating finders are equivalent to ActiveRecord finders; the
+ # only difference is that we start with "paginate" instead of "find" and
+ # that <tt>:page</tt> is required parameter:
+ #
+ # @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC'
+ #
+ # In paginating finders, "all" is implicit. There is no sense in paginating
+ # a single record, right? So, you can drop the <tt>:all</tt> argument:
+ #
+ # Post.paginate(...) => Post.find :all
+ # Post.paginate_all_by_something => Post.find_all_by_something
+ # Post.paginate_by_something => Post.find_all_by_something
+ #
+ # == The importance of the <tt>:order</tt> parameter
+ #
+ # In ActiveRecord finders, <tt>:order</tt> parameter specifies columns for
+ # the <tt>ORDER BY</tt> clause in SQL. It is important to have it, since
+ # pagination only makes sense with ordered sets. Without the <tt>ORDER
+ # BY</tt> clause, databases aren't required to do consistent ordering when
+ # performing <tt>SELECT</tt> queries; this is especially true for
+ # PostgreSQL.
+ #
+ # Therefore, make sure you are doing ordering on a column that makes the
+ # most sense in the current context. Make that obvious to the user, also.
+ # For perfomance reasons you will also want to add an index to that column.
+ module ClassMethods
+ # This is the main paginating finder.
+ #
+ # == Special parameters for paginating finders
+ # * <tt>:page</tt> -- REQUIRED, but defaults to 1 if false or nil
+ # * <tt>:per_page</tt> -- defaults to <tt>CurrentModel.per_page</tt> (which is 30 if not overridden)
+ # * <tt>:total_entries</tt> -- use only if you manually count total entries
+ # * <tt>:count</tt> -- additional options that are passed on to +count+
+ # * <tt>:finder</tt> -- name of the ActiveRecord finder used (default: "find")
+ #
+ # All other options (+conditions+, +order+, ...) are forwarded to +find+
+ # and +count+ calls.
+ def paginate(*args, &block)
+ options = args.pop
+ page, per_page, total_entries = wp_parse_options(options)
+ finder = (options[:finder] || 'find').to_s
+
+ if finder == 'find'
+ # an array of IDs may have been given:
+ total_entries ||= (Array === args.first and args.first.size)
+ # :all is implicit
+ args.unshift(:all) if args.empty?
+ end
+
+ WillPaginate::Collection.create(page, per_page, total_entries) do |pager|
+ count_options = options.except :page, :per_page, :total_entries, :finder
+ find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page)
+
+ args << find_options
+ # @options_from_last_find = nil
+ pager.replace send(finder, *args, &block)
+
+ # magic counting for user convenience:
+ pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries
+ end
+ end
+
+ # Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string
+ # based on the params otherwise used by paginating finds: +page+ and
+ # +per_page+.
+ #
+ # Example:
+ #
+ # @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000],
+ # :page => params[:page], :per_page => 3
+ #
+ # A query for counting rows will automatically be generated if you don't
+ # supply <tt>:total_entries</tt>. If you experience problems with this
+ # generated SQL, you might want to perform the count manually in your
+ # application.
+ #
+ def paginate_by_sql(sql, options)
+ WillPaginate::Collection.create(*wp_parse_options(options)) do |pager|
+ query = sanitize_sql(sql)
+ original_query = query.dup
+ # add limit, offset
+ add_limit! query, :offset => pager.offset, :limit => pager.per_page
+ # perfom the find
+ pager.replace find_by_sql(query)
+
+ unless pager.total_entries
+ count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s]+$/mi, ''
+ count_query = "SELECT COUNT(*) FROM (#{count_query})"
+
+ unless ['oracle', 'oci'].include?(self.connection.adapter_name.downcase)
+ count_query << ' AS count_table'
+ end
+ # perform the count query
+ pager.total_entries = count_by_sql(count_query)
+ end
+ end
+ end
+
+ def respond_to?(method, include_priv = false) #:nodoc:
+ case method.to_sym
+ when :paginate, :paginate_by_sql
+ true
+ else
+ super(method.to_s.sub(/^paginate/, 'find'), include_priv)
+ end
+ end
+
+ protected
+
+ def method_missing_with_paginate(method, *args, &block) #:nodoc:
+ # did somebody tried to paginate? if not, let them be
+ unless method.to_s.index('paginate') == 0
+ return method_missing_without_paginate(method, *args, &block)
+ end
+
+ # paginate finders are really just find_* with limit and offset
+ finder = method.to_s.sub('paginate', 'find')
+ finder.sub!('find', 'find_all') if finder.index('find_by_') == 0
+
+ options = args.pop
+ raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys
+ options = options.dup
+ options[:finder] = finder
+ args << options
+
+ paginate(*args, &block)
+ end
+
+ # Does the not-so-trivial job of finding out the total number of entries
+ # in the database. It relies on the ActiveRecord +count+ method.
+ def wp_count(options, args, finder)
+ excludees = [:count, :order, :limit, :offset, :readonly]
+ unless options[:select] and options[:select] =~ /^\s*DISTINCT\b/i
+ excludees << :select # only exclude the select param if it doesn't begin with DISTINCT
+ end
+ # count expects (almost) the same options as find
+ count_options = options.except *excludees
+
+ # merge the hash found in :count
+ # this allows you to specify :select, :order, or anything else just for the count query
+ count_options.update options[:count] if options[:count]
+
+ # we may have to scope ...
+ counter = Proc.new { count(count_options) }
+
+ # we may be in a model or an association proxy!
+ klass = (@owner and @reflection) ? @reflection.klass : self
+
+ count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with'))
+ # scope_out adds a 'with_finder' method which acts like with_scope, if it's present
+ # then execute the count with the scoping provided by the with_finder
+ send(scoper, &counter)
+ elsif match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(finder)
+ # extract conditions from calls like "paginate_by_foo_and_bar"
+ attribute_names = extract_attribute_names_from_match(match)
+ conditions = construct_attributes_from_arguments(attribute_names, args)
+ with_scope(:find => { :conditions => conditions }, &counter)
+ else
+ counter.call
+ end
+
+ count.respond_to?(:length) ? count.length : count
+ end
+
+ def wp_parse_options(options) #:nodoc:
+ raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys
+ options = options.symbolize_keys
+ raise ArgumentError, ':page parameter required' unless options.key? :page
+
+ if options[:count] and options[:total_entries]
+ raise ArgumentError, ':count and :total_entries are mutually exclusive'
+ end
+
+ page = options[:page] || 1
+ per_page = options[:per_page] || self.per_page
+ total = options[:total_entries]
+ [page, per_page, total]
+ end
+
+ private
+
+ # def find_every_with_paginate(options)
+ # @options_from_last_find = options
+ # find_every_without_paginate(options)
+ # end
+ end
+ end
+end
diff --git a/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb b/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb
new file mode 100644
index 0000000..34e2ff0
--- /dev/null
+++ b/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb
@@ -0,0 +1,226 @@
+require 'will_paginate/core_ext'
+
+module WillPaginate
+ # = Will Paginate view helpers
+ #
+ # Currently there is only one view helper: +will_paginate+. It renders the
+ # pagination links for the given collection. The helper itself is lightweight
+ # and serves only as a wrapper around link renderer instantiation; the
+ # renderer then does all the hard work of generating the HTML.
+ #
+ # == Global options for helpers
+ #
+ # Options for pagination helpers are optional and get their default values from the
+ # WillPaginate::ViewHelpers.pagination_options hash. You can write to this hash to
+ # override default options on the global level:
+ #
+ # WillPaginate::ViewHelpers.pagination_options[:prev_label] = 'Previous page'
+ #
+ # By putting this into your environment.rb you can easily translate link texts to previous
+ # and next pages, as well as override some other defaults to your liking.
+ module ViewHelpers
+ # default options that can be overridden on the global level
+ @@pagination_options = {
+ :class => 'pagination',
+ :prev_label => '« Previous',
+ :next_label => 'Next »',
+ :inner_window => 4, # links around the current page
+ :outer_window => 1, # links around beginning and end
+ :separator => ' ', # single space is friendly to spiders and non-graphic browsers
+ :param_name => :page,
+ :params => nil,
+ :renderer => 'WillPaginate::LinkRenderer',
+ :page_links => true,
+ :container => true
+ }
+ mattr_reader :pagination_options
+
+ # Renders Digg/Flickr-style pagination for a WillPaginate::Collection
+ # object. Nil is returned if there is only one page in total; no point in
+ # rendering the pagination in that case...
+ #
+ # ==== Options
+ # * <tt>:class</tt> -- CSS class name for the generated DIV (default: "pagination")
+ # * <tt>:prev_label</tt> -- default: "« Previous"
+ # * <tt>:next_label</tt> -- default: "Next »"
+ # * <tt>:inner_window</tt> -- how many links are shown around the current page (default: 4)
+ # * <tt>:outer_window</tt> -- how many links are around the first and the last page (default: 1)
+ # * <tt>:separator</tt> -- string separator for page HTML elements (default: single space)
+ # * <tt>:param_name</tt> -- parameter name for page number in URLs (default: <tt>:page</tt>)
+ # * <tt>:params</tt> -- additional parameters when generating pagination links
+ # (eg. <tt>:controller => "foo", :action => nil</tt>)
+ # * <tt>:renderer</tt> -- class name of the link renderer (default: WillPaginate::LinkRenderer)
+ # * <tt>:page_links</tt> -- when false, only previous/next links are rendered (default: true)
+ # * <tt>:container</tt> -- toggles rendering of the DIV container for pagination links, set to
+ # false only when you are rendering your own pagination markup (default: true)
+ # * <tt>:id</tt> -- HTML ID for the container (default: nil). Pass +true+ to have the ID automatically
+ # generated from the class name of objects in collection: for example, paginating
+ # ArticleComment models would yield an ID of "article_comments_pagination".
+ #
+ # All options beside listed ones are passed as HTML attributes to the container
+ # element for pagination links (the DIV). For example:
+ #
+ # <%= will_paginate @posts, :id => 'wp_posts' %>
+ #
+ # ... will result in:
+ #
+ # <div class="pagination" id="wp_posts"> ... </div>
+ #
+ # ==== Using the helper without arguments
+ # If the helper is called without passing in the collection object, it will
+ # try to read from the instance variable inferred by the controller name.
+ # For example, calling +will_paginate+ while the current controller is
+ # PostsController will result in trying to read from the <tt>@posts</tt>
+ # variable. Example:
+ #
+ # <%= will_paginate :id => true %>
+ #
+ # ... will result in <tt>@post</tt> collection getting paginated:
+ #
+ # <div class="pagination" id="posts_pagination"> ... </div>
+ #
+ def will_paginate(collection = nil, options = {})
+ options, collection = collection, nil if collection.is_a? Hash
+ unless collection or !controller
+ collection_name = "@#{controller.controller_name}"
+ collection = instance_variable_get(collection_name)
+ raise ArgumentError, "The #{collection_name} variable appears to be empty. Did you " +
+ "forget to specify the collection object for will_paginate?" unless collection
+ end
+ # early exit if there is nothing to render
+ return nil unless collection.page_count > 1
+ options = options.symbolize_keys.reverse_merge WillPaginate::ViewHelpers.pagination_options
+ # create the renderer instance
+ renderer_class = options[:renderer].to_s.constantize
+ renderer = renderer_class.new collection, options, self
+ # render HTML for pagination
+ renderer.to_html
+ end
+
+ # Renders a helpful message with numbers of displayed vs. total entries.
+ # You can use this as a blueprint for your own, similar helpers.
+ #
+ # <%= page_entries_info @posts %>
+ # #-> Displaying entries 6 - 10 of 26 in total
+ def page_entries_info(collection)
+ %{Displaying entries <b>%d - %d</b> of <b>%d</b> in total} % [
+ collection.offset + 1,
+ collection.offset + collection.length,
+ collection.total_entries
+ ]
+ end
+ end
+
+ # This class does the heavy lifting of actually building the pagination
+ # links. It is used by +will_paginate+ helper internally.
+ class LinkRenderer
+
+ def initialize(collection, options, template)
+ @collection = collection
+ @options = options
+ @template = template
+ end
+
+ def to_html
+ links = @options[:page_links] ? windowed_links : []
+ # previous/next buttons
+ links.unshift page_link_or_span(@collection.previous_page, 'disabled', @options[:prev_label])
+ links.push page_link_or_span(@collection.next_page, 'disabled', @options[:next_label])
+
+ html = links.join(@options[:separator])
+ @options[:container] ? @template.content_tag(:div, html, html_attributes) : html
+ end
+
+ def html_attributes
+ return @html_attributes if @html_attributes
+ @html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class])
+ # pagination of Post models will have the ID of "posts_pagination"
+ if @options[:container] and @options[:id] === true
+ @html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination'
+ end
+ @html_attributes
+ end
+
+ protected
+
+ def gap_marker; '...'; end
+
+ def windowed_links
+ prev = nil
+
+ visible_page_numbers.inject [] do |links, n|
+ # detect gaps:
+ links << gap_marker if prev and n > prev + 1
+ links << page_link_or_span(n)
+ prev = n
+ links
+ end
+ end
+
+ def visible_page_numbers
+ inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i
+ window_from = current_page - inner_window
+ window_to = current_page + inner_window
+
+ # adjust lower or upper limit if other is out of bounds
+ if window_to > total_pages
+ window_from -= window_to - total_pages
+ window_to = total_pages
+ elsif window_from < 1
+ window_to += 1 - window_from
+ window_from = 1
+ end
+
+ visible = (1..total_pages).to_a
+ left_gap = (2 + outer_window)...window_from
+ right_gap = (window_to + 1)...(total_pages - outer_window)
+ visible -= left_gap.to_a if left_gap.last - left_gap.first > 1
+ visible -= right_gap.to_a if right_gap.last - right_gap.first > 1
+
+ visible
+ end
+
+ def page_link_or_span(page, span_class = 'current', text = nil)
+ text ||= page.to_s
+ if page and page != current_page
+ @template.link_to text, url_options(page), :rel => rel_value(page)
+ else
+ @template.content_tag :span, text, :class => span_class
+ end
+ end
+
+ def url_options(page)
+ options = { param_name => page }
+ # page links should preserve GET parameters
+ options = params.merge(options) if @template.request.get?
+ options.rec_merge!(@options[:params]) if @options[:params]
+ return options
+ end
+
+ private
+
+ def rel_value(page)
+ case page
+ when @collection.previous_page; 'prev' + (page == 1 ? ' start' : '')
+ when @collection.next_page; 'next'
+ when 1; 'start'
+ end
+ end
+
+ def current_page
+ @collection.current_page
+ end
+
+ def total_pages
+ @collection.page_count
+ end
+
+ def param_name
+ @param_name ||= @options[:param_name].to_sym
+ end
+
+ def params
+ @params ||= @template.params.to_hash.symbolize_keys
+ end
+ end
+end
diff --git a/vendor/plugins/will_paginate/test/array_pagination_test.rb b/vendor/plugins/will_paginate/test/array_pagination_test.rb
new file mode 100644
index 0000000..0aad4c8
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/array_pagination_test.rb
@@ -0,0 +1,131 @@
+require File.dirname(__FILE__) + '/helper'
+require 'will_paginate/core_ext'
+
+class ArrayPaginationTest < Test::Unit::TestCase
+ def test_simple
+ collection = ('a'..'e').to_a
+
+ [{ :page => 1, :per_page => 3, :expected => %w( a b c ) },
+ { :page => 2, :per_page => 3, :expected => %w( d e ) },
+ { :page => 1, :per_page => 5, :expected => %w( a b c d e ) },
+ { :page => 3, :per_page => 5, :expected => [] },
+ ].
+ each do |conditions|
+ assert_equal conditions[:expected], collection.paginate(conditions.slice(:page, :per_page))
+ end
+ end
+
+ def test_defaults
+ result = (1..50).to_a.paginate
+ assert_equal 1, result.current_page
+ assert_equal 30, result.size
+ end
+
+ def test_deprecated_api
+ assert_deprecated 'paginate API' do
+ result = (1..50).to_a.paginate(2, 10)
+ assert_equal 2, result.current_page
+ assert_equal (11..20).to_a, result
+ assert_equal 50, result.total_entries
+ end
+
+ assert_deprecated { [].paginate nil }
+ end
+
+ def test_total_entries_has_precedence
+ result = %w(a b c).paginate :total_entries => 5
+ assert_equal 5, result.total_entries
+ end
+
+ def test_argument_error_with_params_and_another_argument
+ assert_raise ArgumentError do
+ [].paginate({}, 5)
+ end
+ end
+
+ def test_paginated_collection
+ entries = %w(a b c)
+ collection = create(2, 3, 10) do |pager|
+ assert_equal entries, pager.replace(entries)
+ end
+
+ assert_equal entries, collection
+ assert_respond_to_all collection, %w(page_count each offset size current_page per_page total_entries)
+ assert_kind_of Array, collection
+ assert_instance_of Array, collection.entries
+ assert_equal 3, collection.offset
+ assert_equal 4, collection.page_count
+ assert !collection.out_of_bounds?
+ end
+
+ def test_out_of_bounds
+ entries = create(2, 3, 2){}
+ assert entries.out_of_bounds?
+
+ entries = create(1, 3, 2){}
+ assert !entries.out_of_bounds?
+ end
+
+ def test_guessing_total_count
+ entries = create do |pager|
+ # collection is shorter than limit
+ pager.replace array
+ end
+ assert_equal 8, entries.total_entries
+
+ entries = create(2, 5, 10) do |pager|
+ # collection is shorter than limit, but we have an explicit count
+ pager.replace array
+ end
+ assert_equal 10, entries.total_entries
+
+ entries = create do |pager|
+ # collection is the same as limit; we can't guess
+ pager.replace array(5)
+ end
+ assert_equal nil, entries.total_entries
+
+ entries = create do |pager|
+ # collection is empty; we can't guess
+ pager.replace array(0)
+ end
+ assert_equal nil, entries.total_entries
+ end
+
+ def test_invalid_page
+ bad_input = [0, -1, nil, '', 'Schnitzel']
+
+ bad_input.each do |bad|
+ assert_raise(WillPaginate::InvalidPage) { create(bad) }
+ end
+ end
+
+ def test_invalid_per_page_setting
+ assert_raise(ArgumentError) { create(1, -1) }
+ end
+
+ private
+ def create(page = 2, limit = 5, total = nil, &block)
+ if block_given?
+ WillPaginate::Collection.create(page, limit, total, &block)
+ else
+ WillPaginate::Collection.new(page, limit, total)
+ end
+ end
+
+ def array(size = 3)
+ Array.new(size)
+ end
+
+ def collect_deprecations
+ old_behavior = WillPaginate::Deprecation.behavior
+ deprecations = []
+ WillPaginate::Deprecation.behavior = Proc.new do |message, callstack|
+ deprecations << message
+ end
+ result = yield
+ [result, deprecations]
+ ensure
+ WillPaginate::Deprecation.behavior = old_behavior
+ end
+end
diff --git a/vendor/plugins/will_paginate/test/boot.rb b/vendor/plugins/will_paginate/test/boot.rb
new file mode 100644
index 0000000..f1bd72b
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/boot.rb
@@ -0,0 +1,23 @@
+plugin_root = File.join(File.dirname(__FILE__), '..')
+version = ENV['RAILS_VERSION']
+version = nil if version and version == ""
+
+# first look for a symlink to a copy of the framework
+if !version and framework_root = ["#{plugin_root}/rails", "#{plugin_root}/../../rails"].find { |p| File.directory? p }
+ puts "found framework root: #{framework_root}"
+ # this allows for a plugin to be tested outside of an app and without Rails gems
+ $:.unshift "#{framework_root}/activesupport/lib", "#{framework_root}/activerecord/lib", "#{framework_root}/actionpack/lib"
+else
+ # simply use installed gems if available
+ puts "using Rails#{version ? ' ' + version : nil} gems"
+ require 'rubygems'
+
+ if version
+ gem 'rails', version
+ else
+ gem 'actionpack'
+ gem 'activerecord'
+ end
+end
+
+$:.unshift "#{plugin_root}/lib"
diff --git a/vendor/plugins/will_paginate/test/console b/vendor/plugins/will_paginate/test/console
new file mode 100755
index 0000000..53b8de4
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/console
@@ -0,0 +1,9 @@
+#!/usr/bin/env ruby
+irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
+libs = []
+dirname = File.dirname(__FILE__)
+
+libs << 'irb/completion'
+libs << File.join(dirname, 'lib', 'load_fixtures')
+
+exec "#{irb}#{libs.map{ |l| " -r #{l}" }.join} --simple-prompt"
diff --git a/vendor/plugins/will_paginate/test/database.yml b/vendor/plugins/will_paginate/test/database.yml
new file mode 100644
index 0000000..7ef1e73
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/database.yml
@@ -0,0 +1,22 @@
+sqlite3:
+ database: ":memory:"
+ adapter: sqlite3
+ timeout: 500
+
+sqlite2:
+ database: ":memory:"
+ adapter: sqlite2
+
+mysql:
+ adapter: mysql
+ username: rails
+ password: mislav
+ encoding: utf8
+ database: will_paginate_unittest
+
+postgres:
+ adapter: postgresql
+ username: mislav
+ password: mislav
+ database: will_paginate_unittest
+ min_messages: warning
diff --git a/vendor/plugins/will_paginate/test/finder_test.rb b/vendor/plugins/will_paginate/test/finder_test.rb
new file mode 100644
index 0000000..b272341
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/finder_test.rb
@@ -0,0 +1,322 @@
+require File.dirname(__FILE__) + '/helper'
+require File.dirname(__FILE__) + '/lib/activerecord_test_case'
+
+require 'will_paginate'
+WillPaginate.enable_activerecord
+
+class FinderTest < ActiveRecordTestCase
+ fixtures :topics, :replies, :users, :projects, :developers_projects
+
+ def test_new_methods_presence
+ assert_respond_to_all Topic, %w(per_page paginate paginate_by_sql)
+ end
+
+ def test_simple_paginate
+ entries = Topic.paginate :page => nil
+ assert_equal 1, entries.current_page
+ assert_nil entries.previous_page
+ assert_nil entries.next_page
+ assert_equal 1, entries.page_count
+ assert_equal 4, entries.size
+
+ entries = Topic.paginate :page => 2
+ assert_equal 2, entries.current_page
+ assert_equal 1, entries.previous_page
+ assert_equal 1, entries.page_count
+ assert entries.empty?
+ end
+
+ def test_parameter_api
+ # :page parameter in options is required!
+ assert_raise(ArgumentError){ Topic.paginate }
+ assert_raise(ArgumentError){ Topic.paginate({}) }
+
+ # explicit :all should not break anything
+ assert_equal Topic.paginate(:page => nil), Topic.paginate(:all, :page => 1)
+
+ # :count could be nil and we should still not cry
+ assert_nothing_raised { Topic.paginate :page => 1, :count => nil }
+ end
+
+ def test_paginate_with_per_page
+ entries = Topic.paginate :page => 1, :per_page => 1
+ assert_equal 1, entries.size
+ assert_equal 4, entries.page_count
+
+ # Developer class has explicit per_page at 10
+ entries = Developer.paginate :page => 1
+ assert_equal 10, entries.size
+ assert_equal 2, entries.page_count
+
+ entries = Developer.paginate :page => 1, :per_page => 5
+ assert_equal 11, entries.total_entries
+ assert_equal 5, entries.size
+ assert_equal 3, entries.page_count
+ end
+
+ def test_paginate_with_order
+ entries = Topic.paginate :page => 1, :order => 'created_at desc'
+ expected = [topics(:futurama), topics(:harvey_birdman), topics(:rails), topics(:ar)].reverse
+ assert_equal expected, entries.to_a
+ assert_equal 1, entries.page_count
+ end
+
+ def test_paginate_with_conditions
+ entries = Topic.paginate :page => 1, :conditions => ["created_at > ?", 30.minutes.ago]
+ expected = [topics(:rails), topics(:ar)]
+ assert_equal expected, entries.to_a
+ assert_equal 1, entries.page_count
+ end
+
+ def test_paginate_with_include_and_conditions
+ entries = Topic.paginate \
+ :page => 1,
+ :include => :replies,
+ :conditions => "replies.content LIKE 'Bird%' ",
+ :per_page => 10
+
+ expected = Topic.find :all,
+ :include => 'replies',
+ :conditions => "replies.content LIKE 'Bird%' ",
+ :limit => 10
+
+ assert_equal expected, entries.to_a
+ assert_equal 1, entries.total_entries
+ end
+
+ def test_paginate_with_include_and_order
+ entries = Topic.paginate \
+ :page => 1,
+ :include => :replies,
+ :order => 'replies.created_at asc, topics.created_at asc',
+ :per_page => 10
+
+ expected = Topic.find :all,
+ :include => 'replies',
+ :order => 'replies.created_at asc, topics.created_at asc',
+ :limit => 10
+
+ assert_equal expected, entries.to_a
+ assert_equal 4, entries.total_entries
+ end
+
+ def test_paginate_associations_with_include
+ entries, project = nil, projects(:active_record)
+
+ assert_nothing_raised "THIS IS A BUG in Rails 1.2.3 that was fixed in [7326]. " +
+ "Please upgrade to the 1-2-stable branch or edge Rails." do
+ entries = project.topics.paginate \
+ :page => 1,
+ :include => :replies,
+ :conditions => "replies.content LIKE 'Nice%' ",
+ :per_page => 10
+ end
+
+ expected = Topic.find :all,
+ :include => 'replies',
+ :conditions => "project_id = #{project.id} AND replies.content LIKE 'Nice%' ",
+ :limit => 10
+
+ assert_equal expected, entries.to_a
+ end
+
+ def test_paginate_associations
+ dhh = users :david
+ expected_name_ordered = [projects(:action_controller), projects(:active_record)]
+ expected_id_ordered = [projects(:active_record), projects(:action_controller)]
+
+ # with association-specified order
+ entries = dhh.projects.paginate(:page => 1)
+ assert_equal expected_name_ordered, entries
+ assert_equal 2, entries.total_entries
+
+ # with explicit order
+ entries = dhh.projects.paginate(:page => 1, :order => 'projects.id')
+ assert_equal expected_id_ordered, entries
+ assert_equal 2, entries.total_entries
+
+ assert_nothing_raised { dhh.projects.find(:all, :order => 'projects.id', :limit => 4) }
+ entries = dhh.projects.paginate(:page => 1, :order => 'projects.id', :per_page => 4)
+ assert_equal expected_id_ordered, entries
+
+ # has_many with implicit order
+ topic = Topic.find(1)
+ expected = [replies(:spam), replies(:witty_retort)]
+ assert_equal expected.map(&:id).sort, topic.replies.paginate(:page => 1).map(&:id).sort
+ assert_equal expected.reverse, topic.replies.paginate(:page => 1, :order => 'replies.id ASC')
+ end
+
+ def test_paginate_association_extension
+ project = Project.find(:first)
+ entries = project.replies.paginate_recent :page => 1
+ assert_equal [replies(:brave)], entries
+ end
+
+ def test_paginate_with_joins
+ entries = Developer.paginate :page => 1,
+ :joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
+ :conditions => 'project_id = 1'
+ assert_equal 2, entries.size
+ developer_names = entries.map { |d| d.name }
+ assert developer_names.include?('David')
+ assert developer_names.include?('Jamis')
+
+ expected = entries.to_a
+ entries = Developer.paginate :page => 1,
+ :joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
+ :conditions => 'project_id = 1', :count => { :select => "users.id" }
+ assert_equal expected, entries.to_a
+ end
+
+ def test_paginate_with_group
+ entries = Developer.paginate :page => 1, :per_page => 10,
+ :group => 'salary', :select => 'salary', :order => 'salary'
+ expected = [ users(:david), users(:jamis), users(:dev_10), users(:poor_jamis) ].map(&:salary).sort
+ assert_equal expected, entries.map(&:salary)
+ end
+
+ def test_paginate_with_dynamic_finder
+ expected = [replies(:witty_retort), replies(:spam)]
+ assert_equal expected, Reply.paginate_by_topic_id(1, :page => 1)
+
+ entries = Developer.paginate :conditions => { :salary => 100000 }, :page => 1, :per_page => 5
+ assert_equal 8, entries.total_entries
+ assert_equal entries, Developer.paginate_by_salary(100000, :page => 1, :per_page => 5)
+
+ # dynamic finder + conditions
+ entries = Developer.paginate_by_salary(100000, :page => 1,
+ :conditions => ['id > ?', 6])
+ assert_equal 4, entries.total_entries
+ assert_equal (7..10).to_a, entries.map(&:id)
+
+ assert_raises NoMethodError do
+ Developer.paginate_by_inexistent_attribute 100000, :page => 1
+ end
+ end
+
+ def test_scoped_paginate
+ entries = Developer.with_poor_ones { Developer.paginate :page => 1 }
+
+ assert_equal 2, entries.size
+ assert_equal 2, entries.total_entries
+ end
+
+ def test_readonly
+ assert_nothing_raised { Developer.paginate :readonly => true, :page => 1 }
+ end
+
+ # this functionality is temporarily removed
+ def xtest_pagination_defines_method
+ pager = "paginate_by_created_at"
+ assert !User.methods.include?(pager), "User methods should not include `#{pager}` method"
+ # paginate!
+ assert 0, User.send(pager, nil, :page => 1).total_entries
+ # the paging finder should now be defined
+ assert User.methods.include?(pager), "`#{pager}` method should be defined on User"
+ end
+
+ # Is this Rails 2.0? Find out by testing find_all which was removed in [6998]
+ unless Developer.respond_to? :find_all
+ def test_paginate_array_of_ids
+ # AR finders also accept arrays of IDs
+ # (this was broken in Rails before [6912])
+ entries = Developer.paginate((1..8).to_a, :per_page => 3, :page => 2, :order => 'id')
+ assert_equal (4..6).to_a, entries.map(&:id)
+ assert_equal 8, entries.total_entries
+ end
+ end
+
+ uses_mocha 'internals' do
+ def test_implicit_all_with_dynamic_finders
+ Topic.expects(:find_all_by_foo).returns([])
+ Topic.expects(:count).returns(0)
+ Topic.paginate_by_foo :page => 1
+ end
+
+ def test_guessing_the_total_count
+ Topic.expects(:find).returns(Array.new(2))
+ Topic.expects(:count).never
+
+ entries = Topic.paginate :page => 2, :per_page => 4
+ assert_equal 6, entries.total_entries
+ end
+
+ def test_extra_parameters_stay_untouched
+ Topic.expects(:find).with(:all, {:foo => 'bar', :limit => 4, :offset => 0 }).returns(Array.new(5))
+ Topic.expects(:count).with({:foo => 'bar'}).returns(1)
+
+ Topic.paginate :foo => 'bar', :page => 1, :per_page => 4
+ end
+
+ def test_count_skips_select
+ Developer.stubs(:find).returns([])
+ Developer.expects(:count).with({}).returns(0)
+ Developer.paginate :select => 'salary', :page => 1
+ end
+
+ def test_count_select_when_distinct
+ Developer.stubs(:find).returns([])
+ Developer.expects(:count).with(:select => 'DISTINCT salary').returns(0)
+ Developer.paginate :select => 'DISTINCT salary', :page => 1
+ end
+
+ def test_should_use_scoped_finders_if_present
+ # scope-out compatibility
+ Topic.expects(:find_best).returns(Array.new(5))
+ Topic.expects(:with_best).returns(1)
+
+ Topic.paginate_best :page => 1, :per_page => 4
+ end
+
+ def test_paginate_by_sql
+ assert_respond_to Developer, :paginate_by_sql
+ Developer.expects(:find_by_sql).with(regexp_matches(/sql LIMIT 3(,| OFFSET) 3/)).returns([])
+ Developer.expects(:count_by_sql).with('SELECT COUNT(*) FROM (sql) AS count_table').returns(0)
+
+ entries = Developer.paginate_by_sql 'sql', :page => 2, :per_page => 3
+ end
+
+ def test_paginate_by_sql_respects_total_entries_setting
+ Developer.expects(:find_by_sql).returns([])
+ Developer.expects(:count_by_sql).never
+
+ entries = Developer.paginate_by_sql 'sql', :page => 1, :total_entries => 999
+ assert_equal 999, entries.total_entries
+ end
+
+ def test_paginate_by_sql_strips_order_by_when_counting
+ Developer.expects(:find_by_sql).returns([])
+ Developer.expects(:count_by_sql).with("SELECT COUNT(*) FROM (sql\n ) AS count_table").returns(0)
+
+ entries = Developer.paginate_by_sql "sql\n ORDER\nby foo, bar, `baz` ASC", :page => 1
+ end
+
+ # TODO: counts are still wrong
+ def test_ability_to_use_with_custom_finders
+ # acts_as_taggable defines find_tagged_with(tag, options)
+ Topic.expects(:find_tagged_with).with('will_paginate', :offset => 0, :limit => 5).returns([])
+ Topic.expects(:count).with({}).returns(0)
+
+ Topic.paginate_tagged_with 'will_paginate', :page => 1, :per_page => 5
+ end
+
+ def test_array_argument_doesnt_eliminate_count
+ ids = (1..8).to_a
+ Developer.expects(:find_all_by_id).returns([])
+ Developer.expects(:count).returns(0)
+
+ Developer.paginate_by_id(ids, :per_page => 3, :page => 2, :order => 'id')
+ end
+
+ def test_paginating_finder_doesnt_mangle_options
+ Developer.expects(:find).returns([])
+ Developer.expects(:count).returns(0)
+ options = { :page => 1 }
+ options.expects(:delete).never
+ options_before = options.dup
+
+ Developer.paginate(options)
+ assert_equal options, options_before
+ end
+ end
+end
diff --git a/vendor/plugins/will_paginate/test/fixtures/admin.rb b/vendor/plugins/will_paginate/test/fixtures/admin.rb
new file mode 100644
index 0000000..1d5e7f3
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/admin.rb
@@ -0,0 +1,3 @@
+class Admin < User
+ has_many :companies, :finder_sql => 'SELECT * FROM companies'
+end
diff --git a/vendor/plugins/will_paginate/test/fixtures/developer.rb b/vendor/plugins/will_paginate/test/fixtures/developer.rb
new file mode 100644
index 0000000..6650a98
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/developer.rb
@@ -0,0 +1,11 @@
+class Developer < User
+ has_and_belongs_to_many :projects, :include => :topics, :order => 'projects.name'
+
+ def self.with_poor_ones(&block)
+ with_scope :find => { :conditions => ['salary <= ?', 80000], :order => 'salary' } do
+ yield
+ end
+ end
+
+ def self.per_page() 10 end
+end
diff --git a/vendor/plugins/will_paginate/test/fixtures/developers_projects.yml b/vendor/plugins/will_paginate/test/fixtures/developers_projects.yml
new file mode 100644
index 0000000..cee359c
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/developers_projects.yml
@@ -0,0 +1,13 @@
+david_action_controller:
+ developer_id: 1
+ project_id: 2
+ joined_on: 2004-10-10
+
+david_active_record:
+ developer_id: 1
+ project_id: 1
+ joined_on: 2004-10-10
+
+jamis_active_record:
+ developer_id: 2
+ project_id: 1
\ No newline at end of file
diff --git a/vendor/plugins/will_paginate/test/fixtures/project.rb b/vendor/plugins/will_paginate/test/fixtures/project.rb
new file mode 100644
index 0000000..0f85ef5
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/project.rb
@@ -0,0 +1,15 @@
+class Project < ActiveRecord::Base
+ has_and_belongs_to_many :developers, :uniq => true
+
+ has_many :topics
+ # :finder_sql => 'SELECT * FROM topics WHERE (topics.project_id = #{id})',
+ # :counter_sql => 'SELECT COUNT(*) FROM topics WHERE (topics.project_id = #{id})'
+
+ has_many :replies, :through => :topics do
+ def find_recent(params = {})
+ with_scope :find => { :conditions => ['replies.created_at > ?', 15.minutes.ago] } do
+ find :all, params
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/will_paginate/test/fixtures/projects.yml b/vendor/plugins/will_paginate/test/fixtures/projects.yml
new file mode 100644
index 0000000..02800c7
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/projects.yml
@@ -0,0 +1,7 @@
+action_controller:
+ id: 2
+ name: Active Controller
+
+active_record:
+ id: 1
+ name: Active Record
diff --git a/vendor/plugins/will_paginate/test/fixtures/replies.yml b/vendor/plugins/will_paginate/test/fixtures/replies.yml
new file mode 100644
index 0000000..9a83c00
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/replies.yml
@@ -0,0 +1,29 @@
+witty_retort:
+ id: 1
+ topic_id: 1
+ content: Birdman is better!
+ created_at: <%= 6.hours.ago.to_s(:db) %>
+
+another:
+ id: 2
+ topic_id: 2
+ content: Nuh uh!
+ created_at: <%= 1.hour.ago.to_s(:db) %>
+
+spam:
+ id: 3
+ topic_id: 1
+ content: Nice site!
+ created_at: <%= 1.hour.ago.to_s(:db) %>
+
+decisive:
+ id: 4
+ topic_id: 4
+ content: "I'm getting to the bottom of this"
+ created_at: <%= 30.minutes.ago.to_s(:db) %>
+
+brave:
+ id: 5
+ topic_id: 4
+ content: "AR doesn't scare me a bit"
+ created_at: <%= 10.minutes.ago.to_s(:db) %>
diff --git a/vendor/plugins/will_paginate/test/fixtures/reply.rb b/vendor/plugins/will_paginate/test/fixtures/reply.rb
new file mode 100644
index 0000000..ea84042
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/reply.rb
@@ -0,0 +1,5 @@
+class Reply < ActiveRecord::Base
+ belongs_to :topic, :include => [:replies]
+
+ validates_presence_of :content
+end
diff --git a/vendor/plugins/will_paginate/test/fixtures/schema.rb b/vendor/plugins/will_paginate/test/fixtures/schema.rb
new file mode 100644
index 0000000..8831aad
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/schema.rb
@@ -0,0 +1,38 @@
+ActiveRecord::Schema.define do
+
+ create_table "users", :force => true do |t|
+ t.column "name", :text
+ t.column "salary", :integer, :default => 70000
+ t.column "created_at", :datetime
+ t.column "updated_at", :datetime
+ t.column "type", :text
+ end
+
+ create_table "projects", :force => true do |t|
+ t.column "name", :text
+ end
+
+ create_table "developers_projects", :id => false, :force => true do |t|
+ t.column "developer_id", :integer, :null => false
+ t.column "project_id", :integer, :null => false
+ t.column "joined_on", :date
+ t.column "access_level", :integer, :default => 1
+ end
+
+ create_table "topics", :force => true do |t|
+ t.column "project_id", :integer
+ t.column "title", :string
+ t.column "subtitle", :string
+ t.column "content", :text
+ t.column "created_at", :datetime
+ t.column "updated_at", :datetime
+ end
+
+ create_table "replies", :force => true do |t|
+ t.column "content", :text
+ t.column "created_at", :datetime
+ t.column "updated_at", :datetime
+ t.column "topic_id", :integer
+ end
+
+end
diff --git a/vendor/plugins/will_paginate/test/fixtures/topic.rb b/vendor/plugins/will_paginate/test/fixtures/topic.rb
new file mode 100644
index 0000000..12b8747
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/topic.rb
@@ -0,0 +1,4 @@
+class Topic < ActiveRecord::Base
+ has_many :replies, :dependent => :destroy, :order => 'replies.created_at DESC'
+ belongs_to :project
+end
diff --git a/vendor/plugins/will_paginate/test/fixtures/topics.yml b/vendor/plugins/will_paginate/test/fixtures/topics.yml
new file mode 100644
index 0000000..0a26904
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/topics.yml
@@ -0,0 +1,30 @@
+futurama:
+ id: 1
+ title: Isnt futurama awesome?
+ subtitle: It really is, isnt it.
+ content: I like futurama
+ created_at: <%= 1.day.ago.to_s(:db) %>
+ updated_at:
+
+harvey_birdman:
+ id: 2
+ title: Harvey Birdman is the king of all men
+ subtitle: yup
+ content: He really is
+ created_at: <%= 2.hours.ago.to_s(:db) %>
+ updated_at:
+
+rails:
+ id: 3
+ project_id: 1
+ title: Rails is nice
+ subtitle: It makes me happy
+ content: except when I have to hack internals to fix pagination. even then really.
+ created_at: <%= 20.minutes.ago.to_s(:db) %>
+
+ar:
+ id: 4
+ project_id: 1
+ title: ActiveRecord sometimes freaks me out
+ content: "I mean, what's the deal with eager loading?"
+ created_at: <%= 15.minutes.ago.to_s(:db) %>
diff --git a/vendor/plugins/will_paginate/test/fixtures/user.rb b/vendor/plugins/will_paginate/test/fixtures/user.rb
new file mode 100644
index 0000000..4a57cf0
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/user.rb
@@ -0,0 +1,2 @@
+class User < ActiveRecord::Base
+end
diff --git a/vendor/plugins/will_paginate/test/fixtures/users.yml b/vendor/plugins/will_paginate/test/fixtures/users.yml
new file mode 100644
index 0000000..ed2c03a
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/fixtures/users.yml
@@ -0,0 +1,35 @@
+david:
+ id: 1
+ name: David
+ salary: 80000
+ type: Developer
+
+jamis:
+ id: 2
+ name: Jamis
+ salary: 150000
+ type: Developer
+
+<% for digit in 3..10 %>
+dev_<%= digit %>:
+ id: <%= digit %>
+ name: fixture_<%= digit %>
+ salary: 100000
+ type: Developer
+<% end %>
+
+poor_jamis:
+ id: 11
+ name: Jamis
+ salary: 9000
+ type: Developer
+
+admin:
+ id: 12
+ name: admin
+ type: Admin
+
+goofy:
+ id: 13
+ name: Goofy
+ type: Admin
diff --git a/vendor/plugins/will_paginate/test/helper.rb b/vendor/plugins/will_paginate/test/helper.rb
new file mode 100644
index 0000000..b8683ce
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/helper.rb
@@ -0,0 +1,25 @@
+require 'test/unit'
+require 'rubygems'
+
+# gem install redgreen for colored test output
+begin require 'redgreen'; rescue LoadError; end
+
+require File.join(File.dirname(__FILE__), 'boot') unless defined?(ActiveRecord)
+
+class Test::Unit::TestCase
+ protected
+ def assert_respond_to_all object, methods
+ methods.each do |method|
+ [method.to_s, method.to_sym].each { |m| assert_respond_to object, m }
+ end
+ end
+end
+
+# Wrap tests that use Mocha and skip if unavailable.
+def uses_mocha(test_name)
+ require 'mocha' unless Object.const_defined?(:Mocha)
+rescue LoadError => load_error
+ $stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
+else
+ yield
+end
diff --git a/vendor/plugins/will_paginate/test/lib/activerecord_test_case.rb b/vendor/plugins/will_paginate/test/lib/activerecord_test_case.rb
new file mode 100644
index 0000000..a39b4a5
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/lib/activerecord_test_case.rb
@@ -0,0 +1,23 @@
+require File.join(File.dirname(__FILE__), 'activerecord_test_connector')
+
+class ActiveRecordTestCase < Test::Unit::TestCase
+ # Set our fixture path
+ if ActiveRecordTestConnector.able_to_connect
+ self.fixture_path = File.join(File.dirname(__FILE__), '..', 'fixtures')
+ self.use_transactional_fixtures = true
+ end
+
+ def self.fixtures(*args)
+ super if ActiveRecordTestConnector.connected
+ end
+
+ def run(*args)
+ super if ActiveRecordTestConnector.connected
+ end
+
+ # Default so Test::Unit::TestCase doesn't complain
+ def test_truth
+ end
+end
+
+ActiveRecordTestConnector.setup
diff --git a/vendor/plugins/will_paginate/test/lib/activerecord_test_connector.rb b/vendor/plugins/will_paginate/test/lib/activerecord_test_connector.rb
new file mode 100644
index 0000000..35fde8e
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/lib/activerecord_test_connector.rb
@@ -0,0 +1,60 @@
+require 'active_record'
+require 'active_record/version'
+require 'active_record/fixtures'
+
+class ActiveRecordTestConnector
+ cattr_accessor :able_to_connect
+ cattr_accessor :connected
+
+ # Set our defaults
+ self.connected = false
+ self.able_to_connect = true
+
+ def self.setup
+ unless self.connected || !self.able_to_connect
+ setup_connection
+ load_schema
+ # require_fixture_models
+ Dependencies.load_paths.unshift(File.dirname(__FILE__) + "/../fixtures")
+ self.connected = true
+ end
+ rescue Exception => e # errors from ActiveRecord setup
+ $stderr.puts "\nSkipping ActiveRecord assertion tests: #{e}"
+ #$stderr.puts " #{e.backtrace.join("\n ")}\n"
+ self.able_to_connect = false
+ end
+
+ private
+
+ def self.setup_connection
+ db = ENV['DB'].blank?? 'sqlite3' : ENV['DB']
+
+ configurations = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'database.yml'))
+ raise "no configuration for '#{db}'" unless configurations.key? db
+ configuration = configurations[db]
+
+ ActiveRecord::Base.logger = Logger.new(STDOUT) if $0 == 'irb'
+ puts "using #{configuration['adapter']} adapter" unless ENV['DB'].blank?
+
+ ActiveRecord::Base.establish_connection(configuration)
+ ActiveRecord::Base.configurations = { db => configuration }
+ ActiveRecord::Base.connection
+
+ unless Object.const_defined?(:QUOTED_TYPE)
+ Object.send :const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')
+ end
+ end
+
+ def self.load_schema
+ ActiveRecord::Base.silence do
+ ActiveRecord::Migration.verbose = false
+ load File.dirname(__FILE__) + "/../fixtures/schema.rb"
+ end
+ end
+
+ def self.require_fixture_models
+ models = Dir.glob(File.dirname(__FILE__) + "/../fixtures/*.rb")
+ models = (models.grep(/user.rb/) + models).uniq
+ models.each { |f| require f }
+ end
+end
diff --git a/vendor/plugins/will_paginate/test/lib/html_inner_text.rb b/vendor/plugins/will_paginate/test/lib/html_inner_text.rb
new file mode 100644
index 0000000..7bb6246
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/lib/html_inner_text.rb
@@ -0,0 +1,21 @@
+require 'action_controller/test_process'
+
+module HTML
+ class Node
+ def inner_text
+ children.map(&:inner_text).join('')
+ end
+ end
+
+ class Text
+ def inner_text
+ self.to_s
+ end
+ end
+
+ class Tag
+ def inner_text
+ childless?? '' : super
+ end
+ end
+end
diff --git a/vendor/plugins/will_paginate/test/lib/load_fixtures.rb b/vendor/plugins/will_paginate/test/lib/load_fixtures.rb
new file mode 100644
index 0000000..c9f4d1f
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/lib/load_fixtures.rb
@@ -0,0 +1,13 @@
+dirname = File.dirname(__FILE__)
+require File.join(dirname, '..', 'boot')
+require File.join(dirname, 'activerecord_test_connector')
+
+# setup the connection
+ActiveRecordTestConnector.setup
+
+# load all fixtures
+fixture_path = File.join(dirname, '..', 'fixtures')
+Fixtures.create_fixtures(fixture_path, ActiveRecord::Base.connection.tables)
+
+require 'will_paginate'
+WillPaginate.enable_activerecord
diff --git a/vendor/plugins/will_paginate/test/pagination_test.rb b/vendor/plugins/will_paginate/test/pagination_test.rb
new file mode 100644
index 0000000..f116391
--- /dev/null
+++ b/vendor/plugins/will_paginate/test/pagination_test.rb
@@ -0,0 +1,272 @@
+require File.dirname(__FILE__) + '/helper'
+require 'action_controller'
+require File.dirname(__FILE__) + '/lib/html_inner_text'
+
+ActionController::Routing::Routes.draw do |map|
+ map.connect ':controller/:action/:id'
+end
+
+ActionController::Base.perform_caching = false
+
+require 'will_paginate'
+WillPaginate.enable_actionpack
+
+class PaginationTest < Test::Unit::TestCase
+
+ class DevelopersController < ActionController::Base
+ def list_developers
+ @options = session[:wp] || {}
+
+ @developers = (1..11).to_a.paginate(
+ :page => params[@options[:param_name] || :page] || 1,
+ :per_page => params[:per_page] || 4
+ )
+
+ render :inline => '<%= will_paginate @developers, @options %>'
+ end
+
+ def guess_collection_name
+ @developers = session[:wp]
+ @options = session[:wp_options]
+ render :inline => '<%= will_paginate @options %>'
+ end
+
+ protected
+ def rescue_errors(e) raise e end
+ def rescue_action(e) raise e end
+ end
+
+ def setup
+ @controller = DevelopersController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ super
+ end
+
+ def test_will_paginate
+ get :list_developers
+
+ entries = assigns :developers
+ assert entries
+ assert_equal 4, entries.size
+
+ assert_select 'div.pagination', 1, 'no main DIV' do |pagination|
+ assert_select 'a[href]', 3 do |elements|
+ validate_page_numbers [2,3,2], elements
+ assert_select elements.last, ':last-child', "Next »"
+ end
+ assert_select 'span', 2
+ assert_select 'span.disabled:first-child', "« Previous"
+ assert_select 'span.current', entries.current_page.to_s
+ assert_equal '« Previous 1 2 3 Next »', pagination.first.inner_text
+ end
+ end
+
+ def test_will_paginate_with_options
+ get :list_developers, { :page => 2 }, :wp => {
+ :class => 'will_paginate', :prev_label => 'Prev', :next_label => 'Next'
+ }
+ assert_response :success
+
+ entries = assigns :developers
+ assert entries
+ assert_equal 4, entries.size
+
+ assert_select 'div.will_paginate', 1, 'no main DIV' do
+ assert_select 'a[href]', 4 do |elements|
+ validate_page_numbers [1,1,3,3], elements
+ # test rel attribute values:
+ assert_select elements[1], 'a', '1' do |link|
+ assert_equal 'prev start', link.first['rel']
+ end
+ assert_select elements.first, 'a', "Prev" do |link|
+ assert_equal 'prev start', link.first['rel']
+ end
+ assert_select elements.last, 'a', "Next" do |link|
+ assert_equal 'next', link.first['rel']
+ end
+ end
+ assert_select 'span.current', entries.current_page.to_s
+ end
+ end
+
+ def test_will_paginate_without_container
+ get :list_developers, {}, :wp => { :container => false }
+ assert_select 'div.pagination', 0, 'no main DIV'
+ assert_select 'a[href]', 3
+ end
+
+ def test_will_paginate_without_page_links
+ get :list_developers, { :page => 2 }, :wp => { :page_links => false }
+ assert_select 'a[href]', 2 do |elements|
+ validate_page_numbers [1,3], elements
+ end
+ end
+
+ def test_will_paginate_preserves_parameters_on_get
+ get :list_developers, :foo => { :bar => 'baz' }
+ assert_links_match /foo%5Bbar%5D=baz/
+ end
+
+ def test_will_paginate_doesnt_preserve_parameters_on_post
+ post :list_developers, :foo => 'bar'
+ assert_no_links_match /foo=bar/
+ end
+
+ def test_adding_additional_parameters
+ get :list_developers, {}, :wp => { :params => { :foo => 'bar' } }
+ assert_links_match /foo=bar/
+ end
+
+ def test_removing_arbitrary_parameters
+ get :list_developers, { :foo => 'bar' }, :wp => { :params => { :foo => nil } }
+ assert_no_links_match /foo=bar/
+ end
+
+ def test_adding_additional_route_parameters
+ get :list_developers, {}, :wp => { :params => { :controller => 'baz' } }
+ assert_links_match %r{\Wbaz/list_developers\W}
+ end
+
+ def test_will_paginate_with_custom_page_param
+ get :list_developers, { :developers_page => 2 }, :wp => { :param_name => :developers_page }
+ assert_response :success
+
+ entries = assigns :developers
+ assert entries
+ assert_equal 4, entries.size
+
+ assert_select 'div.pagination', 1, 'no main DIV' do
+ assert_select 'a[href]', 4 do |elements|
+ validate_page_numbers [1,1,3,3], elements, :developers_page
+ end
+ assert_select 'span.current', entries.current_page.to_s
+ end
+ end
+
+ def test_will_paginate_windows
+ get :list_developers, { :page => 6, :per_page => 1 }, :wp => { :inner_window => 1 }
+ assert_response :success
+
+ entries = assigns :developers
+ assert entries
+ assert_equal 1, entries.size
+
+ assert_select 'div.pagination', 1, 'no main DIV' do |pagination|
+ assert_select 'a[href]', 8 do |elements|
+ validate_page_numbers [5,1,2,5,7,10,11,7], elements
+ assert_select elements.first, 'a', "« Previous"
+ assert_select elements.last, 'a', "Next »"
+ end
+ assert_select 'span.current', entries.current_page.to_s
+ assert_equal '« Previous 1 2 ... 5 6 7 ... 10 11 Next »', pagination.first.inner_text
+ end
+ end
+
+ def test_will_paginate_eliminates_small_gaps
+ get :list_developers, { :page => 6, :per_page => 1 }, :wp => { :inner_window => 2 }
+ assert_response :success
+
+ assert_select 'div.pagination', 1, 'no main DIV' do
+ assert_select 'a[href]', 12 do |elements|
+ validate_page_numbers [5,1,2,3,4,5,7,8,9,10,11,7], elements
+ end
+ end
+ end
+
+ def test_no_pagination
+ get :list_developers, :per_page => 12
+ entries = assigns :developers
+ assert_equal 1, entries.page_count
+ assert_equal 11, entries.size
+
+ assert_equal '', @response.body
+ end
+
+ def test_faulty_input_raises_error
+ assert_raise WillPaginate::InvalidPage do
+ get :list_developers, :page => 'foo'
+ end
+ end
+
+ uses_mocha 'helper internals' do
+ def test_collection_name_can_be_guessed
+ collection = mock
+ collection.expects(:page_count).returns(1)
+ get :guess_collection_name, {}, :wp => collection
+ end
+ end
+
+ def test_inferred_collection_name_raises_error_when_nil
+ ex = assert_raise ArgumentError do
+ get :guess_collection_name, {}, :wp => nil
+ end
+ assert ex.message.include?('@developers')
+ end
+
+ def test_setting_id_for_container
+ get :list_developers
+ assert_select 'div.pagination', 1 do |div|
+ assert_nil div.first['id']
+ end
+ # magic ID
+ get :list_developers, {}, :wp => { :id => true }
+ assert_select 'div.pagination', 1 do |div|
+ assert_equal 'fixnums_pagination', div.first['id']
+ end
+ # explicit ID
+ get :list_developers, {}, :wp => { :id => 'custom_id' }
+ assert_select 'div.pagination', 1 do |div|
+ assert_equal 'custom_id', div.first['id']
+ end
+ end
+
+ if ActionController::Base.respond_to? :rescue_responses
+ def test_rescue_response_hook_presence
+ assert_equal :not_found,
+ DevelopersController.rescue_responses['WillPaginate::InvalidPage']
+ end
+ end
+
+protected
+
+ def validate_page_numbers expected, links, param_name = :page
+ param_pattern = /\W#{param_name}=([^&]*)/
+
+ assert_equal(expected, links.map { |e|
+ e['href'] =~ param_pattern
+ $1 ? $1.to_i : $1
+ })
+ end
+
+ def assert_links_match pattern
+ assert_select 'div.pagination a[href]' do |elements|
+ elements.each do |el|
+ assert_match pattern, el['href']
+ end
+ end
+ end
+
+ def assert_no_links_match pattern
+ assert_select 'div.pagination a[href]' do |elements|
+ elements.each do |el|
+ assert_no_match pattern, el['href']
+ end
+ end
+ end
+end
+
+class ViewHelpersTest < Test::Unit::TestCase
+ include WillPaginate::ViewHelpers
+
+ def test_page_entries_info
+ arr = ('a'..'z').to_a
+ collection = arr.paginate :page => 2, :per_page => 5
+ assert_equal %{Displaying entries <b>6 - 10</b> of <b>26</b> in total},
+ page_entries_info(collection)
+
+ collection = arr.paginate :page => 7, :per_page => 4
+ assert_equal %{Displaying entries <b>25 - 26</b> of <b>26</b> in total},
+ page_entries_info(collection)
+ end
+end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
aa43fec0db7b24e1076f1290b05e46712cd14a91
|
Basic styling in place now part 2
|
diff --git a/app/views/actions/_search_form.html.haml b/app/views/actions/_search_form.html.haml
new file mode 100644
index 0000000..b25221d
--- /dev/null
+++ b/app/views/actions/_search_form.html.haml
@@ -0,0 +1,33 @@
+#search_box
+ %h2 Find an Action
+
+ %form
+
+ %table{ :border=>"0", :cellpadding=>"0", :cellspacing=>"0" }
+ %tr.first
+ %td Search Term:
+ %td= text_field_tag 'search_term', nil, :size => 22
+ %td
+ = submit_tag 'Search'
+
+ = submit_tag 'Google Map'
+
+ = submit_tag 'Tag Cloud'
+
+ = submit_tag 'Random'
+ %tr
+ %td Type of Action:
+ %td= select_tag 'action_type', options_for_action_type_select
+ %td
+ Created:
+ = select_tag 'create', options_for_created_select
+
+ - Site.find(:all, :order => :name).each_slice(4) do |sites|
+ .platform_select
+ - sites.each do |site|
+ = check_box_tag site.id, site.name, true
+ = site.name
+ %br/
+
+ %br{:clear => 'all'}/
+
\ No newline at end of file
diff --git a/config/initializers/datetime_formats.rb b/config/initializers/datetime_formats.rb
new file mode 100644
index 0000000..d187dc9
--- /dev/null
+++ b/config/initializers/datetime_formats.rb
@@ -0,0 +1,3 @@
+ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
+ :default => '%B %d, %Y'
+)
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
5793f4810132ca149f589212b93c877f65d0e2d5
|
Basic styling in place now
|
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index f11852c..75aa4ad 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,10 +1,32 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def map_loader
if [email protected]? && @gmap.onload
{:onload => @gmap.onload_func_name + '()', :onunload => 'GUnload'}
else
{}
end
end
+
+ def options_for_action_type_select
+ options_for_select([
+ ['All actions', "all"],
+ ['Group fundraising', "fundraiser"],
+ ['Grassroots petition', "petitions"],
+ ['Volunteer opportunity', "volunteer"],
+ ['Collective action', "pledge"],
+ ['Affinity group', "affinitygroup"]
+ ])
+ end
+
+ def options_for_created_select
+ options_for_select([
+ ['Last 30 days', "last30days"],
+ ['Last 14 days',"last14days"],
+ ['Last week', "lastweek"],
+ ['Yesterday', "yesterday"],
+ ['Today', "today"]
+ ])
+ end
+
end
diff --git a/app/views/actions/_action.html.haml b/app/views/actions/_action.html.haml
index 92e0587..403ca18 100644
--- a/app/views/actions/_action.html.haml
+++ b/app/views/actions/_action.html.haml
@@ -1,7 +1,30 @@
%div[action]
-
- .name
- = action.title
-
- .links
- = link_to 'Show', object_path(action)
+ = link_to action.title, object_path(action), :class => 'action-title'
+
+ .action-source
+ %span{:class => 'action-byline'}
+ Created on
+ = link_to action.site.name, action.site.url
+ by
+ = link_to 'TODO', ''
+ %br/
+ %span{:class => 'action-created'}
+ = action.created_at.to_s(:default)
+ %br/
+ %span{:class => 'action-type'} TODO
+ %span{:class => 'action-goal'}
+ %strong
+ Goal:
+ TODO
+ %br/
+ %span{:class => 'action-location'}
+ %strong
+ Location:
+ = action.location
+ %br/
+ %span{:class => 'action-tags'}
+ %strong
+ Tags:
+ = action.tag_list.to_s
+ %br/
+ = link_to action.url, action.url, :class => 'action-url'
diff --git a/app/views/actions/index.html.haml b/app/views/actions/index.html.haml
index 3aefa70..05c5576 100644
--- a/app/views/actions/index.html.haml
+++ b/app/views/actions/index.html.haml
@@ -1,4 +1,10 @@
-%h1 Listing actions
+= render :partial => 'search_form'
+
+#search_results
+ %h2 Results
+ = render :partial => 'action', :collection => current_objects
+
+
+
-= render :partial => 'action', :collection => current_objects
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index c910bb5..9454fe1 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,15 +1,11 @@
-!!! 1.1
+!!! 1.0
%html{"xmlns"=>"http://www.w3.org/1999/xhtml", "xml:lang"=>"en"}
%head
%meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}/
- %title= 'Social Actions'
+ %title A Mashup of 29+ Social Action Platforms
= stylesheet_link_tag 'main'
= yield :map_headers
%body{ map_loader }
-
- #main_container
- #body
- #content
- = yield
-
+
+ = yield
\ No newline at end of file
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index 9198020..549a935 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,11 +1,85 @@
+a
+ :color #3366cc
+ :text-decoration none
+
+h2
+ :margin 0px 0px 5px 0px
+
+p
+ :margin 3px 3px 0px 3px
+
+// Block Elements
+#search_results
+ :width 710px
+ :font-family Arial, Helvetica, sans-serif
+ :font-size 14px
+ :color #000
+ :padding 10px 10px 0px 10px
+
+
+// Search box
+#search_box
+ :width 700px
+ :font-family Arial, Helvetica, sans-serif
+ :font-size 14px
+ :color #000
+ :background-color #e9f3f1
+ :padding 10px 10px 30px 10px
+
+ table
+ td
+ :padding-right 5px
+ :padding-top 10px
+ .first
+ td
+ :padding-top 0
+
+.platform_select
+ :width 170px
+ :float left
+ :margin-top 10px
+
+// Results Elements
.action
- :clear both
- :margin 5px
- :padding 5px
- :border-top 1px solid #ddd
- .name
- :float left
- :width 85%
- .links
- :float left
- :width 14%
+ :width 700px
+ :margin-bottom 30px
+
+.action-title
+ :margin-top 5px
+ :margin-bottom 5px
+ :font-size 160%
+ :display block
+
+.action-source
+ :width 320px
+ :float right
+ :margin-left 25px
+ :text-align right
+
+.action-goal
+
+.action-location
+
+.action-tags
+
+.action-url
+ :margin-top 10px
+ :display block
+ :color #ff6600
+
+.action-url a
+
+.action-url a:hover
+
+.action-byline
+
+.action-byline a
+ :font-weight bold
+
+.action-byline a:hover
+
+.action-created
+
+.action-type
+ :font-style italic
+
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
b8056712bb96970cd344ccd79c65d92a5ffce049
|
ignoring .DS_Store
|
diff --git a/.gitignore b/.gitignore
index f3a2cf2..d6545ac 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
log/*.log
+.DS_Store
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
74f706ab09496caafbba1d1a1428b289eeecd34a
|
Bringing in basic google mapping
|
diff --git a/app/controllers/map_controller.rb b/app/controllers/map_controller.rb
new file mode 100644
index 0000000..6a51ff1
--- /dev/null
+++ b/app/controllers/map_controller.rb
@@ -0,0 +1,65 @@
+class MapController < ApplicationController
+
+ before_filter :setup_map
+
+ include ActionView::Helpers::JavaScriptHelper
+
+ def index
+ actions = Action.find(:all, :origin => [current_latitude, current_longitude], :conditions => 'latitude IS NOT NULL and longitude IS NOT NULL')
+ actions.each do |action|
+ # now for the lat and lng of the marker we want to add.
+ marker_lat = action.latitude
+ marker_lng = action.longitude
+ @gmap.use_marker_code('createWithIconAndHtml', :with_args => [:point, :html, :icon_image])
+
+ incident_point = Mappa::GLatLng.new(:lat => marker_lat, :lng => marker_lng)
+
+ @gmap.add_marker(:point => incident_point, :create_with => 'createWithIconAndHtml', :html => "'#{escape_javascript(action.title)}'", :icon_image => "'/images/marker.png'")
+ end
+ # render :template => "map/index"
+
+
+ end
+
+protected
+ def setup_map
+ @gmap = Mappa::GMap.new()
+ @gmap.api_key = 'ABQIAAAAkGYfBpkZ5yYF_f9sthqC5BTJQa0g3IQ9GZqIMmInSLzwtGDKaBRu7u3V_uePSTUgmfHvnGnehFX3-A'
+
+ # set the longitude and latitiude of the centre point of our map
+ @gmap.lat, @gmap.lng = current_latitude, current_longitude
+
+ # set the zoom level of our map. This number is in the range of 1-18. 1 is lowest zoom and 18 is highest
+ # we've picked a nice middling 12.
+ @gmap.zoom = 4
+ @gmap.add_control(:control => 'small')
+ @gmap.add_control(:control => 'type')
+ @gmap.add_control(:control => 'overview')
+ end
+
+ def current_latitude
+ current_location.lat || 41.98
+ end
+
+ def current_longitude
+ current_location.lng || -87.90
+ end
+
+ def current_location
+ # debugger
+ @current_location ||= GeoKit::Geocoders::IpGeocoder.geocode(current_ip)
+ end
+
+ def current_ip
+ request.remote_ip == '127.0.0.1' ? '67.162.124.13' : request.remote_ip
+ end
+
+ # def get_current_location
+ # location = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)
+ # unless location.lat.nil? and location.lng.nil?
+ # return location.lat, location.lng
+ # else
+ # return 41.98, -87.90 # Chicago, an estimate
+ # end
+ # end
+end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 22a7940..f11852c 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,3 +1,10 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
+ def map_loader
+ if [email protected]? && @gmap.onload
+ {:onload => @gmap.onload_func_name + '()', :onunload => 'GUnload'}
+ else
+ {}
+ end
+ end
end
diff --git a/app/helpers/map_helper.rb b/app/helpers/map_helper.rb
new file mode 100644
index 0000000..65a9561
--- /dev/null
+++ b/app/helpers/map_helper.rb
@@ -0,0 +1,2 @@
+module MapHelper
+end
diff --git a/app/models/action.rb b/app/models/action.rb
index fdd0dce..0d2bd41 100644
--- a/app/models/action.rb
+++ b/app/models/action.rb
@@ -1,67 +1,67 @@
class Action < ActiveRecord::Base
include GeoKit::Geocoders
belongs_to :feed
delegate :site, :to => :feed
acts_as_taggable
- acts_as_mappable
+ acts_as_mappable :lat_column_name => :latitude, :lng_column_name => :longitude
before_save :look_for_tags, :look_for_location, :geocode_lookup
def update_from_feed_item(item)
puts " -- Action: #{item.title}"
self.title = item.title
self.url = item.link
self.description = item.description
self.created_at = item.pubDate if item.pubDate
figure_out_address_from(item)
end
def description=(new_description)
write_attribute(:description, fix_quoted_html(new_description))
end
protected
def fix_quoted_html(text)
text.gsub(/\</, '<').gsub(/\>/, '>')
end
def look_for_location
if feed.location_finder and self.description
match = self.description.match(feed.location_finder.to_s)
self.location = match[1] if match and match[1]
puts " Found Location: #{self.location}"
end
end
def look_for_tags
if feed.tag_finder and description
match = description.match(feed.tag_finder.to_s)
self.tag_list = match[1] if match and match[1]
puts " Found Tags: #{self.tag_list}"
end
end
def figure_out_address_from(item)
if item.geo_lat and item.geo_long
self.latitude = item.geo_lat
self.longitude = item.geo_long
end
end
def geocode_lookup
unless location.nil? or location.empty?
result = MultiGeocoder.geocode(location)
if result.success
self.latitude = result.lat
self.longitude = result.lng
- puts " Geocoding Successful"
+ puts " Geocoding Successful - #{result}"
end
end
end
end
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 8c65bf2..c910bb5 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,15 +1,15 @@
!!! 1.1
%html{"xmlns"=>"http://www.w3.org/1999/xhtml", "xml:lang"=>"en"}
%head
%meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}/
%title= 'Social Actions'
= stylesheet_link_tag 'main'
-
- %body
+ = yield :map_headers
+ %body{ map_loader }
+
#main_container
#body
-
#content
= yield
diff --git a/app/views/map/index.html.haml b/app/views/map/index.html.haml
new file mode 100644
index 0000000..5cd1b75
--- /dev/null
+++ b/app/views/map/index.html.haml
@@ -0,0 +1,5 @@
+- content_for :map_headers do
+ = map_header(@gmap)
+ = map_body(@gmap)
+
+#gmap{:style => "height:400px;width:400px"}
diff --git a/db/migrate/009_add_location_finder_to_feed.rb b/db/migrate/009_add_location_finder_to_feed.rb
new file mode 100644
index 0000000..d6825be
--- /dev/null
+++ b/db/migrate/009_add_location_finder_to_feed.rb
@@ -0,0 +1,9 @@
+class AddLocationFinderToFeed < ActiveRecord::Migration
+ def self.up
+ add_column :feeds, :location_finder, :string
+ end
+
+ def self.down
+ remove_column :feeds, :location_finder
+ end
+end
diff --git a/db/migrate/010_add_location_to_action.rb b/db/migrate/010_add_location_to_action.rb
new file mode 100644
index 0000000..69bfcd4
--- /dev/null
+++ b/db/migrate/010_add_location_to_action.rb
@@ -0,0 +1,9 @@
+class AddLocationToAction < ActiveRecord::Migration
+ def self.up
+ add_column :actions, :location, :string
+ end
+
+ def self.down
+ remove_column :actions, :location
+ end
+end
diff --git a/db/migrate/011_change_action_precision.rb b/db/migrate/011_change_action_precision.rb
new file mode 100644
index 0000000..9d83be0
--- /dev/null
+++ b/db/migrate/011_change_action_precision.rb
@@ -0,0 +1,9 @@
+class ChangeActionPrecision < ActiveRecord::Migration
+ def self.up
+ change_column :actions, :latitude, :decimal, :precision => 15, :scale => 10
+ change_column :actions, :longitude, :decimal, :precision => 15, :scale => 10
+ end
+
+ def self.down
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index ea74265..1428a33 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,58 +1,58 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of ActiveRecord to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 10) do
+ActiveRecord::Schema.define(:version => 11) do
create_table "actions", :force => true do |t|
t.text "description"
t.string "url"
t.text "title"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "feed_id"
- t.decimal "latitude", :precision => 11, :scale => 10
- t.decimal "longitude", :precision => 11, :scale => 10
+ t.decimal "latitude", :precision => 15, :scale => 10
+ t.decimal "longitude", :precision => 15, :scale => 10
t.string "location"
end
create_table "feeds", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "last_accessed"
t.datetime "created_at"
t.datetime "updated_at"
t.string "tag_finder"
t.integer "site_id"
t.string "location_finder"
end
create_table "sites", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type"], :name => "index_taggings_on_taggable_id_and_taggable_type"
create_table "tags", :force => true do |t|
t.string "name"
end
end
diff --git a/public/images/marker.png b/public/images/marker.png
new file mode 100644
index 0000000..1268364
Binary files /dev/null and b/public/images/marker.png differ
diff --git a/public/javascripts/map_js/_createWithIconAndHtml.mjs b/public/javascripts/map_js/_createWithIconAndHtml.mjs
new file mode 100644
index 0000000..ed050ff
--- /dev/null
+++ b/public/javascripts/map_js/_createWithIconAndHtml.mjs
@@ -0,0 +1,18 @@
+function createMarker(point,html,icon_image) {
+ var icon = new GIcon();
+
+ icon.image = icon_image ;
+
+ icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
+ icon.iconSize = new GSize(12, 20);
+ icon.shadowSize = new GSize(22, 20);
+ icon.iconAnchor = new GPoint(6, 20);
+ icon.infoWindowAnchor = new GPoint(5, 1);
+
+ var marker = new GMarker(point,icon);
+
+ GEvent.addListener(marker, "click", function() {
+ marker.openInfoWindowHtml(html);
+ });
+ return marker;
+ }
\ No newline at end of file
diff --git a/spec/controllers/map_controller_spec.rb b/spec/controllers/map_controller_spec.rb
new file mode 100644
index 0000000..455a68d
--- /dev/null
+++ b/spec/controllers/map_controller_spec.rb
@@ -0,0 +1,17 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe MapController do
+
+ #Delete these examples and add some real ones
+ it "should use MapController" do
+ controller.should be_an_instance_of(MapController)
+ end
+
+
+ describe "GET 'index'" do
+ it "should be successful" do
+ get 'index'
+ response.should be_success
+ end
+ end
+end
diff --git a/spec/helpers/map_helper_spec.rb b/spec/helpers/map_helper_spec.rb
new file mode 100644
index 0000000..e3e0a57
--- /dev/null
+++ b/spec/helpers/map_helper_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe MapHelper do
+
+ #Delete this example and add some real ones or delete this file
+ it "should include the MapHelper" do
+ included_modules = self.metaclass.send :included_modules
+ included_modules.should include(MapHelper)
+ end
+
+end
diff --git a/spec/views/map/index.html.erb_spec.rb b/spec/views/map/index.html.erb_spec.rb
new file mode 100644
index 0000000..9ef0cf4
--- /dev/null
+++ b/spec/views/map/index.html.erb_spec.rb
@@ -0,0 +1,12 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe "/map/index" do
+ before(:each) do
+ render 'map/index'
+ end
+
+ #Delete this example and add some real ones or delete this file
+ it "should tell you where to find the file" do
+ response.should have_tag('p', /Find me in app\/views\/map\/index/)
+ end
+end
diff --git a/test/functional/actions_controller_test.rb b/test/functional/actions_controller_test.rb
new file mode 100644
index 0000000..82b7e30
--- /dev/null
+++ b/test/functional/actions_controller_test.rb
@@ -0,0 +1,57 @@
+require File.dirname(__FILE__) + '/../test_helper'
+require 'actions_controller'
+
+# Re-raise errors caught by the controller.
+class ActionsController; def rescue_action(e) raise e end; end
+
+class ActionsControllerTest < Test::Unit::TestCase
+ fixtures :actions
+
+ def setup
+ @controller = ActionsController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ def test_should_get_index
+ get :index
+ assert_response :success
+ assert assigns(:actions)
+ end
+
+ def test_should_get_new
+ get :new
+ assert_response :success
+ end
+
+ def test_should_create_action
+ old_count = Action.count
+ post :create, :action => { }
+ assert_equal old_count + 1, Action.count
+
+ assert_redirected_to action_path(assigns(:action))
+ end
+
+ def test_should_show_action
+ get :show, :id => 1
+ assert_response :success
+ end
+
+ def test_should_get_edit
+ get :edit, :id => 1
+ assert_response :success
+ end
+
+ def test_should_update_action
+ put :update, :id => 1, :action => { }
+ assert_redirected_to action_path(assigns(:action))
+ end
+
+ def test_should_destroy_action
+ old_count = Action.count
+ delete :destroy, :id => 1
+ assert_equal old_count-1, Action.count
+
+ assert_redirected_to actions_path
+ end
+end
diff --git a/vendor/plugins/mappa/README b/vendor/plugins/mappa/README
new file mode 100644
index 0000000..268ab52
--- /dev/null
+++ b/vendor/plugins/mappa/README
@@ -0,0 +1,86 @@
+= Mappa
+
+== Overview
+
+Mappa is a Rails plug-in map-creation API for creating maps embedded in html web pages. Presently it only supports Google's Gmap2 API.
+It was written primarily because of the hacks required to make the Cartographer.rb rails plugin work with the new Gmap2 API.
+
+Following on from a basic implementation I got frustrated with the amount of javascript I was having to embed within my controller code, a necessity because of the dynamic nature of many of the maps (and map creation techniques) I was using. The result was the latest version of mappa which enables you to build your map javascript from external files.
+
+You need a google API key to use this plugin. This may be obtained by visiting http://www.google.com/apis/maps/signup.html. The API used in this example will suffice for testing as long as you are using the following testing url: http://localhost:3000
+
+This plugin is under constant development but is being used without any problems in production in spotcrime.net. Any amendments, suggestions, etc. are welcomed.
+Further examples of Mappa usage are available at the blog at http://neverintheoffice.net
+
+For more information, discussion, discourse, etc, just email me at [email protected]
+
+copyright Andy Mendelsohn.
+Andy Mendelsohn 2007
+
+== Usage
+Place the mappa folder into your vendor/plugins directory. There is no need to 'include Mappa' as it's included dynamically with the init.rb
+
+Examples:
+=== Basic
+
+The following quick example should produce a basic map.
+
+map_controller.rb :
+
+-------8<-------------------
+class MapController < ApplicationController
+
+ def index
+
+ @page_title = "Create new map"
+
+ @gmap = Mappa::GMap.new()
+ # the gmap api key for localhost:3000 - remember to change this!
+ @gmap.api_key = "ABQIAAAArjtwNyA-0TDmcb74hMzhHBTJQa0g3IQ9GZqIMmInSLzwtGDKaBRSDWK-cqMmi3YB5dD-8a6Kwe1Qmg"
+
+ @gmap.lat = 51.775362610
+ @gmap.lng = -0.00100011
+ @gmap.name = 'gmap'
+ @gmap.zoom = 12
+
+ end
+
+end
+-------8<-------------------
+
+The layout file: map.rhtml
+
+-------8<-------------------
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+ <head>
+ <title><%= @page_title || 'map' %></title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <%= yield :map_headers %>
+ </head>
+ <body onload="<%= @gmap.onload_func_name %>()" onunload="GUnload">
+ <%= yield %>
+ </body>
+</html>
+
+-------8<-------------------
+
+The view: index.rhtml
+
+-----8< -------------------
+
+<% content_for :map_headers do %>
+ <%= map_header(@gmap) %>
+ <%= map_body(@gmap) %>
+<% end %>
+
+<div style="height:700px;width:800px" id="gmap"></div>
+
+-----8<------------------
+
+
+
+
+
diff --git a/vendor/plugins/mappa/Rakefile b/vendor/plugins/mappa/Rakefile
new file mode 100644
index 0000000..2f7a44a
--- /dev/null
+++ b/vendor/plugins/mappa/Rakefile
@@ -0,0 +1,22 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the Mappa plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the Mappa plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'Mappa'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/vendor/plugins/mappa/init.rb b/vendor/plugins/mappa/init.rb
new file mode 100644
index 0000000..d0fa11b
--- /dev/null
+++ b/vendor/plugins/mappa/init.rb
@@ -0,0 +1,2 @@
+ActionView::Base.send :include, Mappa::MappaHelper
+ActionController::Base.send :include, Mappa
diff --git a/vendor/plugins/mappa/install.rb b/vendor/plugins/mappa/install.rb
new file mode 100644
index 0000000..f7732d3
--- /dev/null
+++ b/vendor/plugins/mappa/install.rb
@@ -0,0 +1 @@
+# Install hook code here
diff --git a/vendor/plugins/mappa/lib/mappa.rb b/vendor/plugins/mappa/lib/mappa.rb
new file mode 100644
index 0000000..08a234c
--- /dev/null
+++ b/vendor/plugins/mappa/lib/mappa.rb
@@ -0,0 +1,674 @@
+############################################################
+#
+# Mappa.rb
+#
+# (C) 2006-2007 Andy Mendelsohn
+#
+# Map making for Rails applications.
+# I'm guessing that it can be used outside of the Rails
+# framework, however it's been written -for- rails.
+# Presently the only class used for map making is
+# GMap which generates javascript for the Google GMap2 API code
+#
+############################################################
+
+module Mappa
+
+ #################################################################
+ #
+ # Mappa::GMap
+ # This Class implements the Google Maps GMap2 API
+ # Be aware that it requires an API key that's set at initialisation
+ # Testing is done locally with a key generated for localhost:3000
+ # the key is:
+ # "ABQIAAAArjtwNyA-0TDmcb74hMzhHBTJQa0g3IQ9GZqIMmInSLzwtGDKaBRSDWK-cqMmi3YB5dD-8a6Kwe1Qmg"
+ #
+ #################################################################
+
+ class NonExistantMJSError < StandardError
+
+ end
+
+ class GMap
+
+ attr_accessor :api_key, :include_funcs, :zoom, :lat, :lng, :js_funcs,
+ :js_code, :js_code_lookup, :mjs_path, :js_vars, :onload_func, :onload_func_name,
+ :marker_code, :marker_code_funcname_lookup, :marker_code_args,
+ :name, :width, :height, :draggable, :polylines, :event_listeners,
+ :type, :controls, :markers, :center, :zoom, :class, :icons, :debug, :onload,
+ :header_scripts, :center_on_bounds
+
+ def initialize(options = {})
+
+ @api_key = options[:api_key]
+ @name = options[:name] || 'gmap'
+ @zoom = options[:zoom]
+ @include_funcs = []
+ @type = nil
+ @onload_func_name = options[:onload_func_name] || 'init'
+ @onload_func = { :head => '', :tail => ''}
+ @js_code = {}
+ @js_vars = {}
+ @js_code_lookup = {}
+ @js_funcs = {}
+ @mjs_path = options[:mjs_path] || 'public/javascripts/map_js'
+ @marker_code = {}
+ @marker_code_funcname_lookup = {}
+ @marker_code_args = {}
+ @event_listeners = []
+ @markers = []
+ @controls = []
+ @polylines = []
+ @center_on_bounds = false
+ @onload = true
+ @header_scripts = []
+ read_js_funcs
+ end
+
+ # read_js_funcs reads javascript functions from another directory and reads them into
+ # the js_funcs hash. These functions can then be used and called without needing to include
+ # them in main controller code
+ def read_js_funcs
+ Dir["#{@mjs_path}/_*.mjs"].each do | file |
+ fname = File.basename(file).sub(/^_(\w+).mjs/, '\1')
+
+ open(file) do | f |
+ @js_funcs[fname] = f.readlines
+ end
+ end
+ end
+
+ def center_on_bounds?
+ @center_on_bounds
+ end
+
+ # builds the javascript functions for output to view
+ def build_js_funcs()
+
+ js_out = ""
+ @include_funcs.each do |fname|
+ js_out << "// #{fname}\n"
+ raise NonExistantMJSError, "_#{fname}.mjs does not exist in #{@mjs_path}." if @js_funcs[fname].nil?
+ js_out << @js_funcs[fname].join()
+ js_out << "//\n"
+
+ end
+ return js_out
+ end
+
+
+ # include_funcs is an array of functions to be read into the final javascript.
+ def include_funcs(*funcs)
+ @include_funcs = funcs
+ end
+
+ def header_scripts(*scriptnames)
+ @header_scripts = scriptnames
+ end
+
+ # Google map header required for all google maps.
+ def header()
+ if @api_key
+ "<script src=\"http://maps.google.com/maps?file=api&v=2&key=#{@api_key}\" type=\"text/javascript\"></script>"
+ else
+ "<!-- Google Map Header requires a valid api. Please add the api key to the relevant code calls. -->"
+ end
+ end
+
+ # map_javascript is the primary method for producing the javascript to be embedded within the view
+ def map_javascript(options = {})
+ if !map_center && !center_on_bounds?
+ "<!-- Google Map requires a lat long centering -->"
+ elsif !self.name
+ "<!-- Google map requires a name -->"
+ else
+ "<script type=\"text/javascript\">\n// <![CDATA[" << build_map << " //]]>\n</script>"
+ end
+ end
+
+ # The main map builder (Called from map_javascript)
+ # this will, in due time (i.e., when i need to use the facility!), add the ability to select
+ # js_vars by key (which is why we are using hashes for now.)
+ def build_map()
+
+ return_string = "\n"
+ # see if we have any javascript variables to set up
+
+ if @js_vars.length > 0
+ return_string << "// js_vars //\n"
+ return_string << @js_vars.values.to_s
+ end
+
+ # see if we have any functions to include
+
+ if @include_funcs.length > 0
+ return_string << build_js_funcs
+ end
+
+ # see if we have any createmarker code
+
+ if @marker_code.length > 0
+ return_string << @marker_code.values.to_s
+ end
+
+ # see if we have any embedded javascript code
+
+ if @js_code.length > 0
+ return_string << @js_code.values.to_s
+ end
+
+ if @onload == true
+
+ return_string << "
+
+ function #{onload_func_name}(){
+ if (GBrowserIsCompatible()) {" << build_load_func << "
+
+ }
+ // display a warning if the browser was not compatible
+ else {
+ alert(\"Sorry, the Google Maps API is not compatible with this browser\");
+ }
+ }
+ "
+ else
+ return_string << "
+ if (GBrowserIsCompatible()) {
+ function #{onload_func_name}(){
+ " << build_load_func << "
+ }
+ #{onload_func_name}();
+ }
+ // display a warning if the browser was not compatible
+ else {
+ alert(\"Sorry, the Google Maps API is not compatible with this browser\");
+ }
+ "
+ end
+ return return_string
+ end
+
+ # add arbitrary javascript code from within the body of the controller
+ # (as opposed to calling them in from external files via read_js_funcs)
+ def add_js(code_string, options = {})
+ @js_code[options[:as]] = code_string
+ end
+
+ # similiar to add_js but this is purely to define javascript variables at the top of the javascript
+ # script block for later use
+ def add_js_vars(code_string, options = {})
+ @js_vars[options[:as]] = code_string
+ end
+
+ # add_marker_code provides the ability to add javascript code that's to be called on creation of a marker
+ # this allows for different marker creation methods within one map.
+
+ def add_marker_code(code_string, options = {})
+ funcname = options[:as]
+ @marker_code[funcname] = code_string
+ @marker_code_funcname_lookup[funcname] = code_string.scan(/function\s+(\w+)\s*\(/)[0]
+ @marker_code_args[funcname] = options[:with_args]
+ end
+
+ # use_marker_code provides the ability to use javascript code that's to be called on creation of a marker
+ # this allows for different marker creation methods within one map.
+ # The difference between use_marker_code and add_marker_code is that use_marker_code reads code from an .mjs file
+ # which is stored in public/javascripts/map_js
+ # This avoids having to embed code within your controller
+
+ def use_marker_code(funcname, options = {})
+
+ code_string = @js_funcs[funcname].join()
+ @marker_code[funcname] = code_string
+ @marker_code_funcname_lookup[funcname] = code_string.scan(/function\s+(\w+)\s*\(/)[0]
+ @marker_code_args[funcname] = options[:with_args]
+
+ end
+
+ # similiar to add_js but this is purely to define javascript variables at the top of the javascript
+ # script block for later use. The difference between use_js_vars and add_js_vars is that use_js_vars can read the
+ # javascript code from an .mjs file that is stored by default in public/javascripts/map_js
+ def use_js_vars(varsname, options = {})
+ code_string = @js_funcs[varsname].join()
+ @js_vars[options[:as]] = code_string
+ end
+
+ # add an event_listener
+ def add_listener(options)
+ listener = Event_listener.new(options)
+ @event_listeners << listener
+ end
+
+ # add map controls
+ def add_control(options)
+ options[:map_name] = self.name
+ control = GControl.new(options)
+ @controls << control
+ end
+
+ # This method constructs and returns the function that's called by the body onload call
+ # it includes the ability to add js to the head and tail of the function (within the function body definition)
+ # as well.
+ def build_load_func
+ return_string = ""
+ return_string << @onload_func[:head]
+ return_string << to_javascript
+ return_string << map_onload_func_body
+ return_string << @onload_func[:tail]
+ end
+
+
+ # set the centerpoint of your map.
+ def set_center(lat,lng)
+ @center = GLatLng.new(:lat => lat, :lng => lng)
+ end
+
+ def map_center
+ if @center
+ @center.to_javascript
+ elsif @lat && @lng
+ set_center(@lat,@lng)
+ @center.to_javascript
+ else
+ false
+ end
+ end
+
+ # the size method will be deprecated as I feel that size of the map, which is a div style size, really should be external to the map code
+ def size(width, height)
+ self.width = width
+ self.height = height
+ end
+
+ # The core method for a map. Minimum requirements for a map are: div name, long & lat co-ords and a key
+ def to_javascript
+ return_string = "
+ #{self.name} = new GMap2(document.getElementById('#{self.name}'));
+ "
+ if !center_on_bounds?
+ return_string << " #{self.name}.setCenter(#{self.map_center()},#{self.zoom || 5}); "
+ end
+ return_string
+ end
+
+ # Add_marker allows the addition of a marker with or without a bespoke createmarker codeblock. See tests
+ # the markers are by calls to a create marker (or without), within the body of the init function
+ def add_marker(marker)
+
+ marker[:create_with] = 'default' if marker[:create_with].nil?
+
+ @markers << marker
+
+ end
+
+ # this method builds the body of the function, including controls and markers
+ def map_onload_func_body
+ return_string = ""
+ @controls.each do |control|
+ return_string << control.to_javascript
+ end
+
+ if [email protected]?
+ types = { 1 => 'G_SATELLITE_TYPE', 2 => 'G_MAP_TYPE', 3 => 'G_HYBRID_TYPE'}
+
+ return_string << "#{self.name}.setMapType(#{types[type]});"
+ end
+
+ @markers.each do | marker |
+ if marker[:create_with] == 'default'
+ return_string << GMarker.new(marker).to_javascript
+ else
+ function_key = marker[:create_with]
+ funcname = self.marker_code_funcname_lookup[function_key]
+
+ func_args = self.marker_code_args[function_key]
+ function_call_string = "var marker = #{funcname}("
+ func_args.each do | arg |
+ if marker[arg].class.name == 'Mappa::GLatLng'
+ function_call_string << marker[arg].to_javascript << ','
+ else
+ function_call_string << marker[arg].to_s << ','
+ end
+ end
+
+ function_call_string[-1] = ");\n"
+ return_string << function_call_string
+ end
+ return_string << "#{self.name}.addOverlay(marker);\n" if !return_string.nil?
+ return_string << "bounds.extend(marker);;\n" if center_on_bounds?
+ end
+
+ @event_listeners.each do | listener |
+ return_string << listener.to_javascript
+ end
+
+ if center_on_bounds?
+ return_string << " #{self.name}.centerAndZoomOnBounds(bounds); "
+ end
+
+ return return_string
+ end
+
+ def fetch_js_code(name)
+ self.js_code[name]
+ end
+
+ end
+
+
+ class GMarker
+ attr_accessor :point, :marker_options
+
+ def initialize(options ={})
+ @point = options[:point]
+ @marker_options = options[:marker_options]
+ end
+
+ def to_javascript
+ if !self.point
+ "<!-- marker requires a point -->"
+ else
+ substr = ""
+ if self.marker_options
+ substr = "," + self.marker_options.name
+ end
+ "var marker = new GMarker(#{self.point.to_javascript}#{substr});\n"
+ end
+ end
+
+ end
+
+ # GControl class gives us our standard map controls for google maps. self-explantatory code
+ class GControl
+
+ attr_accessor :control_anchor, :control_offset, :control, :map_name
+
+ @@controls = { :large => 'GLargeMapControl', :small => 'GSmallMapControl',
+ :zoom => 'GSmallZoomControl', :type => 'GMapTypeControl',
+ :scale => 'GScaleControl', :overview => 'GOverviewMapControl' }
+
+ @@anchors = { :top_right => 'G_ANCHOR_TOP_RIGHT',
+ :top_left => 'G_ANCHOR_TOP_LEFT',
+ :bottom_right => 'G_ANCHOR_BOTTOM_RIGHT',
+ :bottom_left => 'G_ANCHOR_BOTTOM_LEFT' }
+
+ def initialize(options ={})
+
+ anchor = options[:control_anchor]
+ @control_anchor = @@anchors[anchor.to_sym] || nil if !anchor.nil?
+ @control_offset = GSize.new(options[:control_offset]) if options[:control_offset]
+ control = options[:control]
+
+ @control = @@controls[control.to_sym]
+ @map_name = options[:map_name]
+
+ end
+
+ def to_javascript
+ return_string = ''
+ if !@control_anchor.nil?
+ if @control_offset
+ return_string << "var gpos = new GControlPosition(#{@control_anchor}, #{@control_offset});\n"
+ else
+ return_string << "var gpos = new GControlPosition(#{@control_anchor});\n"
+ end
+ return_string << "#{@map_name}.addControl(new #{@control}(),gpos);\n"
+ else
+ return_string << "#{@map_name}.addControl(new #{@control}());\n"
+ end
+ return return_string
+ end
+
+ end
+
+ class GSize
+
+ attr_accessor :height, :width
+
+ def initialize(options = {})
+ @height = options[:height]
+ @width = options[:width]
+ end
+
+ def to_javascript
+ return "new GSize(#{@height},#{@width})"
+ end
+
+ end
+
+ # GMarkerOptions are objects that provide options for markers (obvious eh? ;-) )
+ # given a gmakeroptions object of: 'gmarkeropts', you should be able to do the following:
+ # marker = new GMarker(latlng, gmarkeropts);
+ class GMarkerOptions
+
+ # we assume that if this is a prototype = true, then it's going to have a unique name,
+ # otherwise we generate it based upon the number of objects we've created
+ attr_accessor :name, :icon, :drag_cross_move, :title, :clickable, :draggable, :bouncy, :bounce_gravity, :prototype
+ @@count = 0
+
+
+ def initialize(options ={})
+
+ raise "name cannot end in an underscore followed by a number" if options[:prototype] && options[:name] =~ /_\d+/
+
+ @@count = @@count + 1
+
+ @name = options[:name]
+ @icon = options[:icon]
+ @drag_cross_move = options[:drag_cross_move]
+ @title = options[:title]
+ @clickable = options[:clickable]
+ @draggable = options[:draggable]
+ @bouncy = options[:bouncy]
+ @bounce_gravity = options[:bounce_gravity]
+ @prototype = options[:prototype]
+ if @prototype.nil?
+ @name = gen_name
+ end
+ end
+
+ def to_javascript
+ "var #{@name} = new GMarkerOptions\n#{@name}.setIcon = #{@icon}"
+ end
+
+ # Generate a unique name based on the number of new markeroptions objects we've created.
+ def gen_name
+
+ "markerOption_#{@@count}"
+ end
+ end
+
+ # the Point class is the class that is used to create points of the GLatLng class.
+ # this always outputs a javascript variable, which is where the primary difference is between point and GLatLng
+ # in fact, Some might say "that's the point of it!"
+ # There is no actual GMap2 class equivalent
+ # We generate a unique var name if the unique option is set to 1
+ #
+ class Point
+
+ attr_accessor :lat, :lng
+ @@count = 0
+
+ def initialize(options = {})
+ if options[:unique] == 1
+ @@count +=1
+ @unique_counter = @@count
+ else
+ @unique_counter = nil
+ end
+ @lat = options[:lat]
+ @lng = options[:lng]
+ end
+
+ def to_javascript
+ if !@unique_counter.nil?
+ "var point_#{@unique_counter} = " << Mappa::GLatLng.new(:lat => @lat, :lng => @lng).to_javascript << ";"
+ else
+ "var point = "<< Mappa::GLatLng.new(:lat => @lat, :lng => @lng).to_javascript << ";"
+ end
+ end
+
+ end
+
+ # Event_listener is used to give us our gmap event handlers, onclicks, etc.
+
+ class Event_listener
+ attr_accessor :action, :method, :element
+ # Creator and accessor for the GMap2 GLatLng equivalent.
+ #
+ def initialize(options = {:action => nil, :method => nil, :element => nil})
+ raise ArgumentError.new("events must have an action") if options[:action].nil?
+ raise ArgumentError.new("events must have a method") if options[:method].nil?
+ raise ArgumentError.new("events must have an elelemt") if options[:element].nil?
+
+
+ @action = options[:action]
+ @method = options[:method]
+ @element = options[:element]
+ end
+
+
+ def to_javascript
+ "
+ GEvent.addListener(#{@element}, '#{@action}', #{@method});"
+ end
+
+ end
+
+ # GLatLng method is merely responsible for sending back the javascript for a new GLatLng object that's then fed to any number of other
+ #objects. It's used to center maps as well as for providing the co-ords to a GMarker object
+
+ class GLatLng
+
+ attr_accessor :lat, :lng
+
+ def initialize(options = {})
+ @lat = options[:lat]
+ @lng = options[:lng]
+ end
+
+ def to_javascript
+ "new GLatLng(#{@lat},#{@lng})"
+ end
+
+ end
+
+ # GIcon creates all that's necessary for the production of unique icon code. the variable name is then used in conjunction with a gmarker to
+ # generate a new marker with a specific icon.
+
+ class GIcon
+
+ attr_accessor :name, :image, :from, :shadow, :icon_size, :shadow_size, :icon_anchor, :info_window_anchor, :info_shadow_anchor
+ @@count = 0
+ # todo: must test for must-have name and image
+
+ def initialize(options = {})
+ raise "name cannot end in an underscore followed by a number" if @prototype && @name =~ /_\d+/
+ @@count +=1
+ @name = options[:name]
+ @image = options[:image]
+ @from = options[:from] || ""
+ @shadow = options[:shadow] || "http://www.google.com/mapfiles/shadow50.png"
+ if options[:icon_size]
+ icon_size = options[:icon_size]
+ width = icon_size[:width]
+ height = icon_size[:height]
+ @icon_size = GSize.new(:height => height, :width => width)
+ else
+ @icon_size = GSize.new(:height => 20, :width => 34)
+ end
+ if options[:shadow_size]
+ shadow_size = options[:shadow_size]
+ width = shadow_size[:width]
+ height = shadow_size[:height]
+ @shadow_size = GSize.new(:height => height, :width => width)
+ else
+ @shadow_size = GSize.new(:height => 37, :width => 34)
+ end
+ if options[:icon_anchor]
+ icon_anchor = options[:icon_anchor]
+ @icon_ancher = GPoint.new(:x => icon_anchor[:x], :y => icon_anchor[:y])
+ else
+ @icon_anchor = GPoint.new(:x => 9, :y => 34)
+ end
+ if options[:info_window_anchor]
+ info_window_anchor = options[:info_window_anchor]
+ @info_window_ancher = GPoint.new(:x => info_window_anchor[:x], :y => info_window_anchor[:y])
+ else
+ @info_window_anchor = GPoint.new(:x => 9, :y => 2)
+ end
+ if options[:info_shadow_anchor]
+ info_shadow_anchor = options[:info_shadow_anchor]
+ @info_shadow_ancher = GPoint.new(:x => info_shadow_anchor[:x], :y => info_shadow_anchor[:y])
+ else
+ @info_shadow_anchor = GPoint.new(:x => 9, :y => 2)
+ end
+ if @name.nil?
+ @name = gen_name
+ end
+ end
+
+ def to_javascript
+ return_string = ""
+ if [email protected]?
+ return_string << "var #{gen_name()} = new GIcon(#{@from});\n"
+ else
+ return_string << "var #{gen_name()} = new GIcon();\n"
+ end
+ return_string << "#{@name}.image = '#{@image}';\n" if [email protected]?
+ return_string << "#{@name}.shadow = '#{@shadow}';\n" if [email protected]?
+ return_string << "#{@name}.iconSize = #{@icon_size.to_javascript};\n" if !@icon_size.nil?
+ return_string << "#{@name}.shadowSize = #{@shadow_size.to_javascript};\n" if !@shadow_size.nil?
+ return_string << "#{@name}.iconAnchor = #{@icon_anchor.to_javascript};\n" if !@icon_anchor.nil?
+ return_string << "#{@name}.infoWindowAnchor = #{@info_window_anchor.to_javascript};\n" if !@info_window_anchor.nil?
+ return_string << "#{@name}.infoShadowAnchor = #{@info_shadow_anchor.to_javascript};\n" if !@info_shadow_anchor.nil?
+ end
+ # Generate a unique name based on the number of icons we've set up
+ def gen_name
+ "gicon_#{@@count}"
+ end
+
+ def return_icon
+ @name
+ end
+ end
+
+# GPoints are used in lots of places. basically they are x/y co-ordinated points, as opposed to long and lat points.
+
+ class GPoint
+
+ def initialize(options = {})
+ @x = options[:x]
+ @y = options[:y]
+ end
+
+ def to_javascript
+ "new GPoint(#{@x},#{@y})"
+ end
+ end
+
+# TODO (soon!): polyines and polygons are pretty straightforward. Simple methods need to be fleshed out. At present they are easily created in
+# external javascript embedded within code read in (which is how i'm dealing with it right now). Using external, non-autogenerated code, is probably
+# the most flexible way of doing it right now.
+
+ class GPolyline
+
+ attr_accessor :points, :color, :weight, :opacity
+
+ def initialize(options = {})
+
+ end
+
+ end
+
+ class GPolygon
+
+ attr_accessor :points, :fill, :color, :opacity, :outline
+
+ def initialize(options = {})
+
+ end
+
+ end
+
+end
\ No newline at end of file
diff --git a/vendor/plugins/mappa/lib/mappa/mappa_helper.rb b/vendor/plugins/mappa/lib/mappa/mappa_helper.rb
new file mode 100644
index 0000000..56283f1
--- /dev/null
+++ b/vendor/plugins/mappa/lib/mappa/mappa_helper.rb
@@ -0,0 +1,13 @@
+module Mappa
+ module MappaHelper
+
+ def map_header(map)
+ map.header
+ end
+
+ def map_body(map)
+ map.map_javascript
+ end
+
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/mappa/lib/version.rb b/vendor/plugins/mappa/lib/version.rb
new file mode 100644
index 0000000..f33319a
--- /dev/null
+++ b/vendor/plugins/mappa/lib/version.rb
@@ -0,0 +1,3 @@
+module Mappa
+ Version = '0.1.1'
+end
\ No newline at end of file
diff --git a/vendor/plugins/mappa/tasks/mappa_tasks.rake b/vendor/plugins/mappa/tasks/mappa_tasks.rake
new file mode 100644
index 0000000..1c899e9
--- /dev/null
+++ b/vendor/plugins/mappa/tasks/mappa_tasks.rake
@@ -0,0 +1,4 @@
+# desc "Explaining what the task does"
+# task :Mappa do
+# # Task goes here
+# end
\ No newline at end of file
diff --git a/vendor/plugins/mappa/test/mappa_test.rb b/vendor/plugins/mappa/test/mappa_test.rb
new file mode 100644
index 0000000..e352c0d
--- /dev/null
+++ b/vendor/plugins/mappa/test/mappa_test.rb
@@ -0,0 +1,403 @@
+# require File.dirname(__FILE__) + '/test_helper'
+require 'test/unit'
+require File.dirname(__FILE__) + '/../lib/Mappa'
+
+class MappaTest < Test::Unit::TestCase
+
+ include Mappa
+
+ def setup
+ @map = Mappa::GMap.new()
+ @marker = Mappa::GMarker.new()
+ @map2 = Mappa::GMap.new()
+ @map2.lat = 43.907787
+ @map2.lng = -79.359741
+ @map2.name = "mymap"
+ @map3 = Mappa::GMap.new()
+ @map3.lat = 43.907787
+ @map3.lng = -79.359741
+ @map3.name = "mymap"
+ end
+
+ def test_should_read_javascript_from_path
+ @map.mjs_path = 'test/test_mappa'
+ @map.read_js_funcs()
+ assert_equal 3, @map.js_funcs.length()
+ end
+
+ def test_should_build_javascript_from_hash
+ @map.mjs_path = 'test/test_mappa'
+ @map.read_js_funcs()
+ @map.include_funcs( 'function1','function3','function2')
+ assert_equal "// function1
+function function1() {
+ return 1;
+}
+//
+// function3
+function function3() {
+ return 3;
+}
+//
+// function2
+function function2() {
+ return 2;
+}
+//
+", @map.build_js_funcs
+ end
+
+ def test_should_not_provide_header_without_api_key
+ assert_equal "<!-- Google Map Header requires a valid api. Please add the api key to the relevant code calls. -->", @map.header
+ end
+
+ def test_should_provide_header_with_api_key
+ # @map api_key for localhost 3000
+ @map.api_key = "ABQIAAAArjtwNyA-0TDmcb74hMzhHBTJQa0g3IQ9GZqIMmInSLzwtGDKaBRSDWK-cqMmi3YB5dD-8a6Kwe1Qmg"
+
+ assert_equal "<script src=\"http://maps.google.com/maps?file=api&v=2&key=ABQIAAAArjtwNyA-0TDmcb74hMzhHBTJQa0g3IQ9GZqIMmInSLzwtGDKaBRSDWK-cqMmi3YB5dD-8a6Kwe1Qmg\" type=\"text/javascript\"></script>", @map.header
+ end
+
+ def test_should_not_build_map_without_name
+ @map.lat = 43.907787
+ @map.lng = -79.359741
+ assert_equal "<!-- Google map requires a name -->", @map.map_javascript
+ end
+
+ def test_should_not_provide_map_without_latlong
+ assert_equal "<!-- Google Map requires a lat long centering -->", @map.map_javascript
+ end
+
+ def test_should_provide_map_with_latlong_and_name
+ assert_equal "<script type=\"text/javascript\">
+// <![CDATA[
+
+ function init(){
+ if (GBrowserIsCompatible()) {
+ mymap = new GMap2(document.getElementById('mymap'));
+ mymap.setCenter(new GLatLng(43.907787,-79.359741),5);
+
+ }
+ // display a warning if the browser was not compatible
+ else {
+ alert(\"Sorry, the Google Maps API is not compatible with this browser\");
+ }
+ }
+ //]]>
+</script>", @map2.map_javascript
+
+ end
+
+ def test_should_return_gmarker_error_without_point
+ @marker = Mappa::GMarker.new()
+
+ assert_equal "<!-- marker requires a point -->", @marker.to_javascript
+ end
+
+ def test_should_return_gmarker_with_point
+ @marker.point = Mappa::GLatLng.new(:lat => 43.907787, :lng => -79.359741)
+ assert_equal "new GMarker(new GLatLng(43.907787,-79.359741))", @marker.to_javascript
+ end
+
+ def test_should_return_icon_constructor
+ @marker_icon = Mappa::GIcon.new(:image => 'my.png')
+ assert_equal "var #{@marker_icon.gen_name} = new GIcon();
+#{@marker_icon.gen_name}.image = 'my.png';
+#{@marker_icon.gen_name}.shadow = 'http://www.google.com/mapfiles/shadow50.png';
+#{@marker_icon.gen_name}.iconSize = new GSize(20,34);
+#{@marker_icon.gen_name}.shadowSize = new GSize(37,34);
+#{@marker_icon.gen_name}.iconAnchor = new GPoint(9,34);
+#{@marker_icon.gen_name}.infoWindowAnchor = new GPoint(9,2);
+#{@marker_icon.gen_name}.infoShadowAnchor = new GPoint(9,2);
+", @marker_icon.to_javascript
+ end
+
+ def test_should_return_gmarker_with_point_and_icon
+
+ @marker_options1 = Mappa::GMarkerOptions.new(:icon => 'my.png')
+ @marker.marker_options = @marker_options1
+ @marker.point = Mappa::GLatLng.new(:lat => 43.907787, :lng => -79.359741)
+
+ assert_equal "var #{@marker_options1.name} = new GMarkerOptions\n#{@marker_options1.name}.setIcon = #{@marker_options1.icon}", @marker_options1.to_javascript
+ assert_equal "new GMarker(new GLatLng(43.907787,-79.359741),#{@marker_options1.name})", @marker.to_javascript
+
+ end
+
+ def test_should_return_point_with_latlng
+
+ @point = Mappa::Point.new(:lat => 43.907787, :lng => -79.359741)
+ assert_equal "var point = new GLatLng(43.907787,-79.359741);", @point.to_javascript
+
+ end
+
+ def test_should_return_incremented_unique_point_with_latlng
+
+ @point = Mappa::Point.new(:unique => 1, :lat => 43.907787, :lng => -79.359741)
+ assert_equal "var point_1 = new GLatLng(43.907787,-79.359741);", @point.to_javascript
+
+ @point2 = Mappa::Point.new(:unique => 1, :lat => 43.907787, :lng => -79.359741)
+ assert_equal "var point_2 = new GLatLng(43.907787,-79.359741);", @point2.to_javascript
+
+ @point = Mappa::Point.new(:unique => 1, :lat => 43.907787, :lng => -79.359741)
+ assert_equal "var point_3 = new GLatLng(43.907787,-79.359741);", @point.to_javascript
+
+ end
+
+ def test_should_increment_gmarkeroption_generated_name
+ @marker_options2 = Mappa::GMarkerOptions.new(:icon => 'your.png')
+ assert_equal "markerOption_1", @marker_options2.name
+ @marker_options3 = Mappa::GMarkerOptions.new(:icon => 'whose.png')
+ assert_equal "markerOption_1", @marker_options2.name
+ assert_equal "markerOption_2", @marker_options3.name
+ end
+
+ def test_marker_options_should_throw_an_exception_if_underscore_followed_by_number_for_proto_names
+ begin
+ @marker_options2 = Mappa::GMarkerOptions.new(:icon => 'worst.png', :prototype => true, :name =>'worst_1')
+ rescue Exception => e
+ error_message = e.message
+ end
+ assert_equal "name cannot end in an underscore followed by a number", error_message
+ assert_raise(RuntimeError) { @marker_options2 = Mappa::GMarkerOptions.new(:icon => 'worst.png', :prototype => true, :name =>'worst_1') }
+ end
+
+ def test_should_return_correct_js_string_from_GLatLang
+ @latlang = Mappa::GLatLng.new(:lat => 43.907787, :lng => -79.359741)
+ assert "new GLatLang(43.907787,-79.359741)", @latlang.to_s
+ end
+
+ def test_should_allow_adding_javascript_vars
+ jstring_head = "
+ var gmap = null;
+ var keycount = 0;
+ var pointArray = {};
+ var pointlist = [];
+ var markers = {};
+ var latlngs = {};
+ var points = [];
+ var editable = true;
+ var oldpolyline = null;
+ var lastPosition = 0;
+ "
+
+ @map3.add_js_vars(jstring_head, :as => 'header_vars')
+ assert @map3.js_vars.to_s, "
+ var gmap = null;
+ var keycount = 0;
+ var pointArray = {};
+ var pointlist = [];
+ var markers = {};
+ var latlngs = {};
+ var points = [];
+ var editable = true;
+ var oldpolyline = null;
+ var lastPosition = 0;
+ "
+
+ end
+
+ def test_should_allow_adding_jscript
+ jstring = "
+ function createMarker(point,name,html) {
+ var marker = new GMarker(point);
+ GEvent.addListener(marker, \"click\", function() {
+ marker.openInfoWindowHtml(html);
+ });
+ // save the info we need to use later for the sidebar
+ gmarkers[i] = marker;
+ htmls[i] = html;
+ i++;
+ return marker;
+ }
+
+ "
+
+ @map.add_js(jstring, :as => 'create_with_html')
+ assert_equal jstring, @map.fetch_js_code('create_with_html')
+ end
+
+ def test_should_include_extra_js_with_output
+
+ jstring = "
+ function createMarker(point,name,html) {
+ var marker = new GMarker(point);
+ GEvent.addListener(marker, \"click\", function() {
+ marker.openInfoWindowHtml(html);
+ });
+ }
+
+ "
+
+ @map2.add_js(jstring, :as => 'create_with_html')
+
+ assert_equal "<script type=\"text/javascript\">
+// <![CDATA[
+ function createMarker(point,name,html) {
+ var marker = new GMarker(point);
+ GEvent.addListener(marker, \"click\", function() {
+ marker.openInfoWindowHtml(html);
+ });
+ }
+
+
+
+ function init(){
+ if (GBrowserIsCompatible()) {
+ mymap = new GMap2(document.getElementById('mymap'));
+ mymap.setCenter(new GLatLng(43.907787,-79.359741),5);
+
+ }
+ // display a warning if the browser was not compatible
+ else {
+ alert(\"Sorry, the Google Maps API is not compatible with this browser\");
+ }
+ }
+ //]]>
+</script>", @map2.map_javascript
+ # </script>", @map2.map_onload_javascript
+ end
+
+ def test_that_marker_is_added_with_correct_js_code
+
+ jstring = "
+ function createMarker(point,html) {
+ var marker = new GMarker(point);
+ GEvent.addListener(marker, \"click\", function() {
+ marker.openInfoWindowHtml(html);
+ });
+ }
+
+ "
+ @map2.add_marker_code(jstring, :as => 'create_with_html', :with_args => [:point, :html])
+
+ @point = Mappa::GLatLng.new(:lat => 10.907787, :lng => 40.359741)
+
+ @map2.add_marker(:point => @point, :create_with => 'create_with_html', :html => "'<b>This is some html!</b>'")
+
+ assert_equal "<script type=\"text/javascript\">
+// <![CDATA[
+ function createMarker(point,html) {
+ var marker = new GMarker(point);
+ GEvent.addListener(marker, \"click\", function() {
+ marker.openInfoWindowHtml(html);
+ });
+ }
+
+
+
+ function init(){
+ if (GBrowserIsCompatible()) {
+ mymap = new GMap2(document.getElementById('mymap'));
+ mymap.setCenter(new GLatLng(43.907787,-79.359741),5);
+var marker = createMarker(new GLatLng(10.907787,40.359741),'<b>This is some html!</b>')
+mymap.addOverlay(marker)
+
+ }
+ // display a warning if the browser was not compatible
+ else {
+ alert(\"Sorry, the Google Maps API is not compatible with this browser\");
+ }
+ }
+ //]]>
+</script>", @map2.map_javascript
+
+ end
+
+ def test_load_function_can_have_head
+
+ jstring = "
+ function createpoly(pointlist) {
+ // create poly code goes here
+ }
+
+ "
+
+ @map2.add_js(jstring, :as => 'create_poly')
+
+ @point = Mappa::GLatLng.new(:lat => 10.907787, :lng => 40.359741)
+
+ @map2.onload_func[:head] = "
+ createPoly();
+ "
+
+
+
+ assert_equal "<script type=\"text/javascript\">
+// <![CDATA[
+ function createpoly(pointlist) {
+ // create poly code goes here
+ }
+
+
+
+ function init(){
+ if (GBrowserIsCompatible()) {
+ createPoly();
+
+ mymap = new GMap2(document.getElementById('mymap'));
+ mymap.setCenter(new GLatLng(43.907787,-79.359741),5);
+
+ }
+ // display a warning if the browser was not compatible
+ else {
+ alert(\"Sorry, the Google Maps API is not compatible with this browser\");
+ }
+ }
+ //]]>
+</script>", @map2.map_javascript
+
+ end
+ def test_load_function_can_have_tail
+
+ jstring = "
+ function createpoly(pointlist) {
+ // create poly code goes here
+ }
+
+ "
+
+ @map2.add_js(jstring, :as => 'create_poly')
+
+ @point = Mappa::GLatLng.new(:lat => 10.907787, :lng => 40.359741)
+
+ @map2.onload_func[:tail] = "
+ createPoly();
+ "
+
+
+
+ assert_equal "<script type=\"text/javascript\">
+// <![CDATA[
+ function createpoly(pointlist) {
+ // create poly code goes here
+ }
+
+
+
+ function init(){
+ if (GBrowserIsCompatible()) {
+ mymap = new GMap2(document.getElementById('mymap'));
+ mymap.setCenter(new GLatLng(43.907787,-79.359741),5);
+
+ createPoly();
+
+ }
+ // display a warning if the browser was not compatible
+ else {
+ alert(\"Sorry, the Google Maps API is not compatible with this browser\");
+ }
+ }
+ //]]>
+</script>", @map2.map_javascript
+
+ end
+
+ # should make this one redundant really. We don't want size set from the Mappa module and i don't think it's useful at the moment.
+ def test_should_allow_setting_dimensions_by_size_function()
+ # @map = GMap.new()
+ @map.size(800,500)
+ assert_equal 500, @map.height
+ assert_equal 800, @map.width
+ end
+
+end
diff --git a/vendor/plugins/mappa/test/test_mappa/_function1.mjs b/vendor/plugins/mappa/test/test_mappa/_function1.mjs
new file mode 100644
index 0000000..3d0da26
--- /dev/null
+++ b/vendor/plugins/mappa/test/test_mappa/_function1.mjs
@@ -0,0 +1,3 @@
+function function1() {
+ return 1;
+}
diff --git a/vendor/plugins/mappa/test/test_mappa/_function2.mjs b/vendor/plugins/mappa/test/test_mappa/_function2.mjs
new file mode 100644
index 0000000..9c3c0df
--- /dev/null
+++ b/vendor/plugins/mappa/test/test_mappa/_function2.mjs
@@ -0,0 +1,3 @@
+function function2() {
+ return 2;
+}
diff --git a/vendor/plugins/mappa/test/test_mappa/_function3.mjs b/vendor/plugins/mappa/test/test_mappa/_function3.mjs
new file mode 100644
index 0000000..198ab32
--- /dev/null
+++ b/vendor/plugins/mappa/test/test_mappa/_function3.mjs
@@ -0,0 +1,3 @@
+function function3() {
+ return 3;
+}
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
f0448d61326c28e7b6fd796ac8f924fe32e992dd
|
Adding in some location finding, and geocoding
|
diff --git a/app/models/action.rb b/app/models/action.rb
index 8d05115..fdd0dce 100644
--- a/app/models/action.rb
+++ b/app/models/action.rb
@@ -1,41 +1,67 @@
class Action < ActiveRecord::Base
+
+ include GeoKit::Geocoders
+
+
belongs_to :feed
delegate :site, :to => :feed
acts_as_taggable
acts_as_mappable
+ before_save :look_for_tags, :look_for_location, :geocode_lookup
+
def update_from_feed_item(item)
+ puts " -- Action: #{item.title}"
self.title = item.title
self.url = item.link
self.description = item.description
self.created_at = item.pubDate if item.pubDate
- puts "pubDate is #{item.pubDate} created_at is #{self.created_at}"
figure_out_address_from(item)
end
def description=(new_description)
write_attribute(:description, fix_quoted_html(new_description))
- look_for_tags
end
protected
def fix_quoted_html(text)
text.gsub(/\</, '<').gsub(/\>/, '>')
end
+ def look_for_location
+ if feed.location_finder and self.description
+ match = self.description.match(feed.location_finder.to_s)
+ self.location = match[1] if match and match[1]
+ puts " Found Location: #{self.location}"
+ end
+ end
+
def look_for_tags
- if feed.tag_finder
+ if feed.tag_finder and description
match = description.match(feed.tag_finder.to_s)
self.tag_list = match[1] if match and match[1]
- puts "Found Tags: #{self.tag_list}"
+ puts " Found Tags: #{self.tag_list}"
end
end
def figure_out_address_from(item)
if item.geo_lat and item.geo_long
self.latitude = item.geo_lat
self.longitude = item.geo_long
end
end
+
+ def geocode_lookup
+ unless location.nil? or location.empty?
+ result = MultiGeocoder.geocode(location)
+ if result.success
+ self.latitude = result.lat
+ self.longitude = result.lng
+ puts " Geocoding Successful"
+ end
+ end
+ end
+
+
end
diff --git a/db/schema.rb b/db/schema.rb
index 723346b..ea74265 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,56 +1,58 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of ActiveRecord to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 8) do
+ActiveRecord::Schema.define(:version => 10) do
create_table "actions", :force => true do |t|
t.text "description"
t.string "url"
t.text "title"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "feed_id"
t.decimal "latitude", :precision => 11, :scale => 10
t.decimal "longitude", :precision => 11, :scale => 10
+ t.string "location"
end
create_table "feeds", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "last_accessed"
t.datetime "created_at"
t.datetime "updated_at"
t.string "tag_finder"
t.integer "site_id"
+ t.string "location_finder"
end
create_table "sites", :force => true do |t|
t.string "name"
t.string "url"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type"], :name => "index_taggings_on_taggable_id_and_taggable_type"
create_table "tags", :force => true do |t|
t.string "name"
end
end
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index c737ff2..6755899 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,126 +1,144 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: change_org
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
+ location_finder:
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
# tag_finder:
+# location_finder:
# last_accessed: <%= 1.day.ago %>
# site: the_point
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: give_meaning
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/pca/badgefeed.aspx
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
+ location_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
zazengo:
name: Latest Zazengo Projects
url: http://www.zazengo.com/projects.rss
- tag_finder: "<div>Topics: <span class=\"issues\">([\w\s,]+)</span></div>"
+ tag_finder: "<span class=\"issues\">([\w\s,]+)</span>"
+ location_finder: "<span class=\"street-address\">([\w\s,]+)</span>"
last_accessed: <%= 1.day.ago %>
site: zazengo
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
1f6f3653721dcc07d9f6f9bee58d92c46704e8b6
|
Adding zazengo feeds, and also some look and feel small changes
|
diff --git a/app/views/actions/index.html.haml b/app/views/actions/index.html.haml
index bb68c76..3aefa70 100644
--- a/app/views/actions/index.html.haml
+++ b/app/views/actions/index.html.haml
@@ -1,5 +1,4 @@
%h1 Listing actions
= render :partial => 'action', :collection => current_objects
-= link_to 'New action', new_object_path
diff --git a/app/views/actions/show.html.haml b/app/views/actions/show.html.haml
index b2088cc..9194a75 100644
--- a/app/views/actions/show.html.haml
+++ b/app/views/actions/show.html.haml
@@ -1,22 +1,22 @@
%h1 Viewing action
%div[current_object]
%h2= current_object.title
.description
= current_object.description
%p
Link:
- = link_to current_object.url
+ = link_to current_object.url, current_object.url, :popup => true
.dates
Created:
= current_object.created_at
.platform
Source:
= link_to current_object.site.name, current_object.site.url, :popup => true
%p= link_to 'Back', objects_path
diff --git a/config/routes.rb b/config/routes.rb
index d94afa1..48d3f1b 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,35 +1,37 @@
ActionController::Routing::Routes.draw do |map|
+ map.resources :actions
+
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
index e534bfd..9198020 100644
--- a/public/stylesheets/sass/main.sass
+++ b/public/stylesheets/sass/main.sass
@@ -1,11 +1,11 @@
.action
:clear both
:margin 5px
:padding 5px
:border-top 1px solid #ddd
.name
:float left
- :width 75%
+ :width 85%
.links
:float left
- :width 24%
+ :width 14%
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index 23184e4..c737ff2 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,119 +1,126 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
tag_finder:
last_accessed: <%= 1.day.ago %>
site: global_giving
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
tag_finder:
last_accessed: <%= 1.day.ago %>
site: pledge_bank
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
last_accessed: <%= 1.day.ago %>
site: change_org
change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
tag_finder: "<br />Tags: ([\w\s,]+)<br />"
last_accessed: <%= 1.day.ago %>
site: change_org
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
tag_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
tag_finder:
last_accessed: <%= 1.day.ago %>
site: razoo
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
tag_finder:
last_accessed: <%= 1.day.ago %>
site: democracy_in_action
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
tag_finder:
last_accessed: <%= 1.day.ago %>
site: care_2_petitions
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
# tag_finder:
# last_accessed: <%= 1.day.ago %>
# site: the_point
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
last_accessed: <%= 1.day.ago %>
site: give_meaning
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
tag_finder: "\n\n Tags: ([\w\s,]+)"
last_accessed: <%= 1.day.ago %>
site: give_meaning
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
tag_finder:
last_accessed: <%= 1.day.ago %>
site: changing_the_present
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
tag_finder:
last_accessed: <%= 1.day.ago %>
site: fundable
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
tag_finder:
last_accessed: <%= 1.day.ago %>
site: bring_light
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
tag_finder:
last_accessed: <%= 1.day.ago %>
site: kiva
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/pca/badgefeed.aspx
tag_finder:
last_accessed: <%= 1.day.ago %>
site: six_degrees
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
tag_finder:
last_accessed: <%= 1.day.ago %>
site: first_giving
+
+zazengo:
+ name: Latest Zazengo Projects
+ url: http://www.zazengo.com/projects.rss
+ tag_finder: "<div>Topics: <span class=\"issues\">([\w\s,]+)</span></div>"
+ last_accessed: <%= 1.day.ago %>
+ site: zazengo
\ No newline at end of file
diff --git a/spec/fixtures/sites.yml b/spec/fixtures/sites.yml
index 1049ac2..1cc510c 100644
--- a/spec/fixtures/sites.yml
+++ b/spec/fixtures/sites.yml
@@ -1,59 +1,62 @@
global_giving:
name: GlobalGiving
url: http://www.globalgiving.com
pledge_bank:
name: PledgeBank
url: http://www.pledgebank.com
change_org:
name: Change.org Giving Networks
url: http://www.change.org
razoo:
name: Razoo Acts
url: http://beta.razoo.com
democracy_in_action:
name: DemocracyinAction
url: http://www.democracyinaction.org
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com
# https is causing failing right now
# the_point:
# name: ThePoint
# url: http://www.thepoint.com/rss
#
# last_accessed: <%= 1.day.ago %>
give_meaning:
name: GiveMeaning
url: http://www.givemeaning.com
changing_the_present:
name: ChangingthePresent
url: http://www.changingthepresent.com
fundable:
name: Fundable
url: http://www.fundable.org
bring_light:
name: BringLight
url: http://www.bringlight.com
kiva:
name: Kiva
url: http://www.kiva.org
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org
first_giving:
name: Firstgiving
url: http://www.firstgiving.com
+zazengo:
+ name: Zazengo
+ url: http://www.zazengo.com
\ No newline at end of file
diff --git a/vendor/plugins/haml/init.rb b/vendor/plugins/haml/init.rb
index 378b795..142726c 100644
--- a/vendor/plugins/haml/init.rb
+++ b/vendor/plugins/haml/init.rb
@@ -1,3 +1,2 @@
-require 'rubygems'
require 'haml'
Haml.init_rails(binding)
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
e84d60f129f951a224e685490f47f38d0bb0752f
|
Put up a very rough interface to the actions using make_resourceful
|
diff --git a/app/controllers/actions_controller.rb b/app/controllers/actions_controller.rb
new file mode 100644
index 0000000..0da610e
--- /dev/null
+++ b/app/controllers/actions_controller.rb
@@ -0,0 +1,16 @@
+class ActionsController < ApplicationController
+ make_resourceful do
+ actions :index, :show
+ response_for :index do |format|
+ format.html
+ format.xml
+ end
+ response_for :show do |format|
+ format.html
+ format.xml
+ end
+ end
+
+
+
+end
diff --git a/app/helpers/actions_helper.rb b/app/helpers/actions_helper.rb
new file mode 100644
index 0000000..9611c69
--- /dev/null
+++ b/app/helpers/actions_helper.rb
@@ -0,0 +1,2 @@
+module ActionsHelper
+end
diff --git a/app/views/actions/_action.html.haml b/app/views/actions/_action.html.haml
new file mode 100644
index 0000000..92e0587
--- /dev/null
+++ b/app/views/actions/_action.html.haml
@@ -0,0 +1,7 @@
+%div[action]
+
+ .name
+ = action.title
+
+ .links
+ = link_to 'Show', object_path(action)
diff --git a/app/views/actions/_form.html.haml b/app/views/actions/_form.html.haml
new file mode 100644
index 0000000..e69de29
diff --git a/app/views/actions/edit.html.haml b/app/views/actions/edit.html.haml
new file mode 100644
index 0000000..84af5b7
--- /dev/null
+++ b/app/views/actions/edit.html.haml
@@ -0,0 +1,11 @@
+%h1 Editing action
+
+= error_messages_for :action
+
+- form_for(:action, :url => object_url, :html => { :method => :put }) do |f|
+ = render :partial => "form", :locals => {:f => f}
+ %p= submit_tag "Update"
+
+= link_to 'Show', object_path
+|
+= link_to 'Back', objects_path
diff --git a/app/views/actions/index.html.haml b/app/views/actions/index.html.haml
new file mode 100644
index 0000000..bb68c76
--- /dev/null
+++ b/app/views/actions/index.html.haml
@@ -0,0 +1,5 @@
+%h1 Listing actions
+
+= render :partial => 'action', :collection => current_objects
+
+= link_to 'New action', new_object_path
diff --git a/app/views/actions/index.xml.haml b/app/views/actions/index.xml.haml
new file mode 100644
index 0000000..c5994ac
--- /dev/null
+++ b/app/views/actions/index.xml.haml
@@ -0,0 +1 @@
+= current_objects.to_xml
\ No newline at end of file
diff --git a/app/views/actions/new.html.haml b/app/views/actions/new.html.haml
new file mode 100644
index 0000000..72ebe56
--- /dev/null
+++ b/app/views/actions/new.html.haml
@@ -0,0 +1,9 @@
+%h1 Creating action
+
+= error_messages_for :action
+
+- form_for(:action, :url => objects_url) do |f|
+ = render :partial => "form", :locals => {:f => f}
+ %p= submit_tag "Create"
+
+= link_to 'Back', objects_path
diff --git a/app/views/actions/show.html.haml b/app/views/actions/show.html.haml
new file mode 100644
index 0000000..b2088cc
--- /dev/null
+++ b/app/views/actions/show.html.haml
@@ -0,0 +1,22 @@
+%h1 Viewing action
+
+%div[current_object]
+ %h2= current_object.title
+
+ .description
+ = current_object.description
+
+ %p
+ Link:
+ = link_to current_object.url
+
+ .dates
+ Created:
+ = current_object.created_at
+
+ .platform
+ Source:
+ = link_to current_object.site.name, current_object.site.url, :popup => true
+
+
+ %p= link_to 'Back', objects_path
diff --git a/app/views/actions/show.xml.haml b/app/views/actions/show.xml.haml
new file mode 100644
index 0000000..281c019
--- /dev/null
+++ b/app/views/actions/show.xml.haml
@@ -0,0 +1 @@
+= current_object.to_xml
\ No newline at end of file
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
new file mode 100644
index 0000000..8c65bf2
--- /dev/null
+++ b/app/views/layouts/application.html.haml
@@ -0,0 +1,15 @@
+!!! 1.1
+
+%html{"xmlns"=>"http://www.w3.org/1999/xhtml", "xml:lang"=>"en"}
+ %head
+ %meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}/
+ %title= 'Social Actions'
+ = stylesheet_link_tag 'main'
+
+ %body
+ #main_container
+ #body
+
+ #content
+ = yield
+
diff --git a/public/stylesheets/.gitignore b/public/stylesheets/.gitignore
new file mode 100644
index 0000000..5f93228
--- /dev/null
+++ b/public/stylesheets/.gitignore
@@ -0,0 +1 @@
+main.css
\ No newline at end of file
diff --git a/public/stylesheets/sass/main.sass b/public/stylesheets/sass/main.sass
new file mode 100644
index 0000000..e534bfd
--- /dev/null
+++ b/public/stylesheets/sass/main.sass
@@ -0,0 +1,11 @@
+.action
+ :clear both
+ :margin 5px
+ :padding 5px
+ :border-top 1px solid #ddd
+ .name
+ :float left
+ :width 75%
+ .links
+ :float left
+ :width 24%
diff --git a/spec/controllers/actions_controller_spec.rb b/spec/controllers/actions_controller_spec.rb
new file mode 100644
index 0000000..a852e63
--- /dev/null
+++ b/spec/controllers/actions_controller_spec.rb
@@ -0,0 +1,10 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe ActionsController do
+
+ #Delete this example and add some real ones
+ it "should use ActionsController" do
+ controller.should be_an_instance_of(ActionsController)
+ end
+
+end
diff --git a/spec/helpers/actions_helper_spec.rb b/spec/helpers/actions_helper_spec.rb
new file mode 100644
index 0000000..c64e2e3
--- /dev/null
+++ b/spec/helpers/actions_helper_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe ActionsHelper do
+
+ #Delete this example and add some real ones or delete this file
+ it "should include the ActionsHelper" do
+ included_modules = self.metaclass.send :included_modules
+ included_modules.should include(ActionsHelper)
+ end
+
+end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
145e7b89574398327e4b43485df9935ec160953d
|
Adding HAML
|
diff --git a/vendor/plugins/haml/init.rb b/vendor/plugins/haml/init.rb
new file mode 100644
index 0000000..378b795
--- /dev/null
+++ b/vendor/plugins/haml/init.rb
@@ -0,0 +1,3 @@
+require 'rubygems'
+require 'haml'
+Haml.init_rails(binding)
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
bae83f525b17bff891a4f82b8d40d3db7ec20427
|
Adding make_resourceful
|
diff --git a/vendor/plugins/make_resourceful/DEFAULTS b/vendor/plugins/make_resourceful/DEFAULTS
new file mode 100644
index 0000000..b77b38f
--- /dev/null
+++ b/vendor/plugins/make_resourceful/DEFAULTS
@@ -0,0 +1,148 @@
+There's a rough equivalence between a basic @make_resourceful@ call
+and a hand-made controller.
+This:
+
+ class PostsController < ApplicationController
+ make_resourceful { actions :all }
+ end
+
+Creates a controller that works more or less like the one that follows.
+Note that the real code generated by make_resourceful
+is more extensible in various ways.
+Thus whenever possible, there are comments in the following controller
+indicating how to customize various bits of the controller.
+
+ class PostsController < ApplicationController
+ def index
+ # Override #current_objects to change this
+ @posts = Post.find(:all)
+
+ # Use before :index to add something here
+
+ # Use response_for :index to change this
+ respond_to { |f| f.html; f.js }
+ end
+
+ def show
+ # Override #current_object to change this
+ @post = Post.find(params[:id])
+
+ # Use before :show to add something here
+
+ # Use response_for :show to change this
+ respond_to { |f| f.html; f.js }
+ end
+
+ def create
+ # Override #build_object to change this
+ @post = Post.new(params[:post])
+
+ # Use before :create to add something here
+
+ if @post.save
+ # Use after :create to add something here
+
+ # Use response_for :create to change this
+ respond_to do |f|
+ f.html do
+ flash[:notice] = "Create successful!"
+ redirect_to post_path(@post)
+ end
+ f.js
+ end
+ else
+ # Use after :create_fails to add something here
+
+ # Use response_for :create_fails to change this
+ respond_to do |f|
+ format.html
+ flash[:error] = "There was a problem!"
+ render :action => :new, :status => 422
+ end
+ format.js
+ end
+ end
+ end
+
+ def update
+ # Override #current_object to change this
+ @post = Post.find(params[:id])
+
+ # Use before :update to do something here
+
+ if @post.update_attributes params[:post]
+ # Use after :update to add something here
+
+ # Use response_for :update to change this
+ respond_to do |f|
+ f.html do
+ flash[:notice] = "Save successful!"
+ redirect_to post_path(@post)
+ end
+ f.js
+ end
+ else
+ # Use after :update_fails to add something here
+
+ # Use response_for :update_fails to change this
+ respond_to do |f|
+ format.html
+ flash[:error] = "There was a problem saving!"
+ render :action => :edit, :status => 422
+ end
+ format.js
+ end
+ end
+ end
+
+ def new
+ # Override #build_object to change this
+ @post = Post.new(params[:post])
+
+ # Use before :new to add something here
+
+ # Use response_for :new to change this
+ respond_to { |f| f.html; f.js }
+ end
+
+ def edit
+ # Override #current_object to change this
+ @post = Post.find(params[:id])
+
+ # Use before :edit to add something here
+
+ # Use response_for :edit to change this
+ respond_to { |f| f.html; f.js }
+ end
+
+ def destroy
+ # Override #current_object to change this
+ @post = Post.find(params[:id])
+
+ # Use before :destroy to do something here
+
+ if @post.destroy
+ # Use after :destroy to add something here
+
+ # Use response_for :destroy to change this
+ respond_to do |f|
+ f.html do
+ flash[:notice] = "Record deleted!"
+ redirect_to posts_path(@post)
+ end
+ f.js
+ end
+ else
+ # Use after :destroy_fails to add something here
+
+ # Use response_for :destroy_fails to change this
+ respond_to do |f|
+ format.html
+ flash[:error] = "There was a problem deleting!"
+ render :back
+ end
+ format.js
+ end
+ end
+ end
+ end
diff --git a/vendor/plugins/make_resourceful/LICENSE b/vendor/plugins/make_resourceful/LICENSE
new file mode 100644
index 0000000..92a93ae
--- /dev/null
+++ b/vendor/plugins/make_resourceful/LICENSE
@@ -0,0 +1,7 @@
+Copyright (c) 2007 Hampton Catlin
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/plugins/make_resourceful/README b/vendor/plugins/make_resourceful/README
new file mode 100644
index 0000000..793a859
--- /dev/null
+++ b/vendor/plugins/make_resourceful/README
@@ -0,0 +1,239 @@
+= make_resourceful
+===== Take back control of your Controllers. Make them awesome. Make them sleek. Make them resourceful.
+
+REST is a fine pattern for designing controllers,
+but it can be pretty repetitive.
+Who wants to write out the same actions and copy the same model lookup logic
+all over their application?
+
+make_resourceful handles all that for you.
+It sets up all your RESTful actions and responses with next to no code.
+Everything has full, sensible default functionality.
+
+Of course, no controller _only_ uses the defaults.
+So make_resourceful can be massively customized,
+while still keeping your controllers trim and readable.
+
+== Get it!
+
+Rails
+
+ $ ruby script/plugin install http://svn.hamptoncatlin.com/make_resourceful/trunk
+ $ mv vendor/plugins/trunk vendor/plugins/make_resourceful
+
+Subversion
+
+ $ svn co http://svn.hamptoncatlin.com/make_resourceful/trunk make_resourceful
+
+== Use it!
+
+The easiest way to start with make_resourceful
+is to run the resource_scaffold generator.
+It uses the same syntax as the Rails scaffold_resource generator:
+
+ $ script/generate resource_scaffold post title:string body:text
+
+It does, however, require Haml[http://haml.hamptoncatlin.com].
+You _are_ using Haml, right? No?
+I'll wait here while you go fall in love with it.
+
+If you want to try make_resourceful on one of your current controllers,
+just replace the mess of repetition with this:
+
+ class FooController < ApplicationController
+ make_resourceful do
+ actions :all
+ end
+ end
+
+Those three lines will replace the entire default controller
+that comes out of the scaffold_resource generator.
+
+=== Really?
+
+Yes.
+
+=== Can I do nested resources?
+
+ make_resourceful do
+ actions :all
+ belongs_to :post
+ end
+
+=== What if I want to use fancy permalinks?
+
+ def current_object
+ @current_object ||= current_model.find_by_permalink(params[:id])
+ end
+
+=== What about paging?
+
+ def current_objects
+ @current_object ||= current_model.find(:all,
+ :order => "created_at DESC", :page => {:current => params[:page], :size => 10 } )
+ end
+
+=== What if I want to do something in the middle of an action?
+
+ before :show, :index do
+ @page_title = "Awesome!"
+ end
+
+ after :create_fails do
+ @page_title = "Not So Awesome!"
+ end
+
+=== What about all of my awesome respond_to blocks for my XML APIs and RJS responses?
+
+ response_for :show do |format|
+ format.html
+ format.js
+ format.xml
+ end
+
+ response_for :update_fails do |format|
+ format.html { render :action => 'edit' }
+ format.json { render :json => false.to_json, :status => 422 }
+ end
+
+=== So I guess I have to write responses for all my actions?
+
+Nope! make_resourceful makes them do the right thing by default.
+You only need to customize them if you want to do something special.
+
+=== Seriously?!
+
+Yes!
+
+== Grok it!
+
+=== +make_resourceful+ the Method
+
+The +make_resourceful+ block is where most of the action happens.
+Here you specify which actions you want to auto-generate,
+what code you want to run for given callbacks,
+and so forth.
+
+You also use the block to declare various bits of information about your controller.
+For instance, if the controller is nested, you'd call +belongs_to+.
+If you wanted to expose your models as some sort of text format,
+you'd call +publish+.
+
+Check out the documentation of Resourceful::Builder
+for more information on the methods you can call here.
+
+=== Helper Methods
+
+make_resourceful provides lots of useful methods
+that can be used in your callbacks and in your views.
+They range from accessing the records you're looking up
+to easily generating URLs for a record
+to getting information about the action itself.
+
+Two of the most useful methods are +current_object+ and +current_objects+
+(note the subtle plurality difference).
++current_objects+ only works for +index+,
+and returns all the records in the current model.
++current_object+ works for all actions other than +index+,
+and returns the record that's currently being dealt with.
+
+The full documentation of the helper methods
+is in Resourceful::Default::Accessors and Resourceful::Default::URLs.
+
+=== Nested Resources
+
+make_resourceful supports easy management of nested resources.
+This is set up with the Resourceful::Builder#belongs_to declaration.
+Pass in the name of the parent model,
+
+ belongs_to :user
+
+and everything will be taken care of.
+When +index+ is run for GET /users/12/albums,
+parent_object[link:classes/Resourceful/Accessors.html#M000024]
+will get <tt>User.find(params[:user_id])</tt>,
+and current_objects[link:classes/Resourceful/Default/Accessors.html#M000010]
+will get <tt>parent_object.albums</tt>.
+When +create+ is run for POST /users/12/albums,
+the newly created Album will automatically belong to the user
+with id 12.
+
+The normal non-scoped actions still work, too.
+GET /albums/15 runs just fine.
+make_resourceful knows that since there's no <tt>params[:user_id]</tt>,
+you just want to deal with the album.
+
+You can even have a single resource nested under several different resources.
+Just pass multiple parent names to the Resourceful::Builder#belongs_to, like
+
+ belongs_to :user, :artist
+
+Then /users/15/albums and /artists/7/albums will both work.
+
+This does, however, mean that make_resourceful only supports one level of nesting.
+There's no automatic handling of /users/15/collections/437/albums.
+However, this is really the best way to organize most resources anyway;
+see this article[http://weblog.jamisbuck.org/2007/2/5/nesting-resources].
+
+If you really need a deeply nested controller,
+it should be easy enough to set up on your own.
+Just override current_model[link:classes/Resourceful/Default/Accessors.html#M000018].
+See the next section for more details.
+
+=== Overriding Methods
+
+Not only are helper methods useful to the developer to use,
+they're used internally by the actions created by make_resourceful.
+Thus one of the main ways make_resourceful can be customized
+is by overriding accessors.
+
+For instance, if you want to only look up the 10 most recent records for +index+,
+you're override +current_objects+.
+If you wanted to use a different model than that suggested by the name of the controller,
+you'd override +current_model+.
+
+When you're overriding methods that do SQL lookups, though, be a little cautious.
+By default, these methods cache their values in instance variables
+so that multiple SQL queries aren't run on multiple calls.
+When overriding them, it's wise for you to do the same.
+For instance,
+
+ def current_object
+ @current_object ||= current_model.find_by_name(params[:name])
+ end
+
+=== For More Information...
+
+Haven't found all the information you need in the RDoc?
+Still a little confused about something?
+Don't despair, there are still more resources available!
+
+* Nathan Weizenbaum periodically makes blog posts about new features and versions of make_resourceful.
+ They may be a little outdated, but they should still be useful and explanatory.
+ * On nesting and associations: here[http://nex-3.com/posts/55-nesting-and-make_resourceful].
+ * An overview of make_resourceful 0.2.0 and 0.2.2: here[http://localhost:3000/posts/54-make_resourceful-0-2-0].
+ * On Resourceful::Builder#publish[link:classes/Resourceful/Builder.html#M000061]
+ and Resourceful::Serialize:
+ here[http://nex-3.com/posts/35-make_resourceful-the-basics-of-publish] and
+ here[http://nex-3.com/posts/36-make_resourceful-publish-extras].
+* There's an excellent, active Google Group (link[http://groups.google.com/group/make_resourceful])
+ where people will be happy to answer your questions.
+* Read the source code!
+ It's very straightforward,
+ and make_resourceful is built to encourage overriding methods
+ and hacking the source.
+
+---
+
+Copyright 2007 Hampton Catlin, Nathan Weizenbaum, and Jeff Hardy.
+
+Contributions by:
+
+* Russell Norris
+* Jonathan Linowes
+* Cristi Balan
+* Mike Ferrier
+* James Golick
+* Don Petersen
+* Alex Ross
+* Tom Stuart
diff --git a/vendor/plugins/make_resourceful/Rakefile b/vendor/plugins/make_resourceful/Rakefile
new file mode 100644
index 0000000..a5c2490
--- /dev/null
+++ b/vendor/plugins/make_resourceful/Rakefile
@@ -0,0 +1,42 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+require 'spec/rake/spectask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+spec_files = Rake::FileList["spec/**/*_spec.rb"]
+
+desc "Run specs"
+Spec::Rake::SpecTask.new do |t|
+ t.spec_files = spec_files
+ t.spec_opts = ["-c"]
+end
+
+desc "Generate code coverage"
+Spec::Rake::SpecTask.new(:coverage) do |t|
+ t.spec_files = spec_files
+ t.rcov = true
+ t.rcov_opts = ['--exclude', 'spec,/var/lib/gems']
+end
+
+desc 'Test the make_resourceful plugin.'
+task :test do
+ Dir.chdir(File.dirname(__FILE__) + '/test')
+ tests = IO.popen('rake test')
+
+ while byte = tests.read(1)
+ print byte
+ end
+end
+
+desc 'Generate documentation for the make_resourceful plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'make_resourceful'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.main = 'README'
+ rdoc.rdoc_files.include(FileList.new('*').exclude(/[^A-Z0-9]/))
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/vendor/plugins/make_resourceful/VERSION b/vendor/plugins/make_resourceful/VERSION
new file mode 100644
index 0000000..74ccf98
--- /dev/null
+++ b/vendor/plugins/make_resourceful/VERSION
@@ -0,0 +1 @@
+0.2.3.0
\ No newline at end of file
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/resourceful_scaffold_generator.rb b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/resourceful_scaffold_generator.rb
new file mode 100644
index 0000000..bb9f9e0
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/resourceful_scaffold_generator.rb
@@ -0,0 +1,87 @@
+class ResourcefulScaffoldGenerator < Rails::Generator::NamedBase
+ attr_reader :controller_class_path,
+ :controller_file_path,
+ :controller_class_nesting,
+ :controller_class_nesting_depth,
+ :controller_class_name,
+ :controller_underscore_name,
+ :controller_plural_name
+ alias_method :controller_file_name, :controller_underscore_name
+ alias_method :controller_table_name, :controller_plural_name
+
+ def initialize(runtime_args, runtime_options = {})
+ super
+
+ base_name, @controller_class_path, @controller_file_path, @controller_class_nesting, @controller_class_nesting_depth = extract_modules(@name.pluralize)
+ @controller_class_name_without_nesting, @controller_underscore_name, @controller_plural_name = inflect_names(base_name)
+
+ if @controller_class_nesting.empty?
+ @controller_class_name = @controller_class_name_without_nesting
+ else
+ @controller_class_name = "#{@controller_class_nesting}::#{@controller_class_name_without_nesting}"
+ end
+ end
+
+ def manifest
+ record do |m|
+ # Check for class naming collisions.
+ m.class_collisions(controller_class_path, "#{controller_class_name}Controller", "#{controller_class_name}Helper")
+ m.class_collisions(class_path, "#{class_name}")
+
+ # Controller, helper, views, and test directories.
+ m.directory(File.join('app/models', class_path))
+ m.directory(File.join('app/controllers', controller_class_path))
+ m.directory(File.join('app/helpers', controller_class_path))
+ m.directory(File.join('app/views', controller_class_path, controller_file_name))
+ m.directory(File.join('test/functional', controller_class_path))
+ m.directory(File.join('test/unit', class_path))
+ m.directory(File.join('test/fixtures', class_path))
+
+ # Views
+ for action in scaffold_views
+ m.template("view_#{action}.haml", File.join('app/views', controller_class_path, controller_file_name, "#{action}.html.haml"))
+ end
+ m.template('view_partial.haml', File.join('app/views', controller_class_path, controller_file_name, "_#{singular_name}.html.haml"))
+
+ # Helper
+ m.template('helper.rb', File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb"))
+
+ # Model
+ m.template('model.rb', File.join('app/models', class_path, "#{file_name}.rb"))
+
+ unless options[:skip_migration]
+ m.migration_template('migration.rb', 'db/migrate',
+ :assigns => {
+ :migration_name => "Create#{class_name.pluralize.gsub(/::/, '')}",
+ :attributes => attributes
+ },
+ :migration_file_name => "create_#{file_path.gsub(/\//, '_').pluralize}")
+ end
+
+ # Controller
+ m.template('controller.rb', File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb"))
+
+ # Tests
+ m.template('functional_test.rb', File.join('test/functional', controller_class_path, "#{controller_file_name}_controller_test.rb"))
+ m.template('unit_test.rb', File.join('test/unit', class_path, "#{file_name}_test.rb"))
+ m.template('fixtures.yml', File.join('test/fixtures', "#{table_name}.yml"))
+
+ # Route
+ m.route_resources controller_file_name
+ end
+ end
+
+ protected
+
+ def banner
+ "Usage: #{$0} resourcefulscaffold ModelName [field:type, field:type]"
+ end
+
+ def scaffold_views
+ %w[ index show new edit _form ]
+ end
+
+ def model_name
+ class_name.demodulize
+ end
+end
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/controller.rb b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/controller.rb
new file mode 100644
index 0000000..61cd04c
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/controller.rb
@@ -0,0 +1,5 @@
+class <%= controller_class_name %>Controller < ApplicationController
+ make_resourceful do
+ actions :all
+ end
+end
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/fixtures.yml b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/fixtures.yml
new file mode 100644
index 0000000..ff55a6e
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/fixtures.yml
@@ -0,0 +1,10 @@
+one:
+ id: 1
+<% for attribute in attributes -%>
+ <%= attribute.name %>: <%= attribute.default %>
+<% end -%>
+two:
+ id: 2
+<% for attribute in attributes -%>
+ <%= attribute.name %>: <%= attribute.default %>
+<% end -%>
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/functional_test.rb b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/functional_test.rb
new file mode 100644
index 0000000..3e404a0
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/functional_test.rb
@@ -0,0 +1,57 @@
+require File.dirname(__FILE__) + '<%= '/..' * controller_class_nesting_depth %>/../test_helper'
+require '<%= controller_file_path %>_controller'
+
+# Re-raise errors caught by the controller.
+class <%= controller_class_name %>Controller; def rescue_action(e) raise e end; end
+
+class <%= controller_class_name %>ControllerTest < Test::Unit::TestCase
+ fixtures :<%= table_name %>
+
+ def setup
+ @controller = <%= controller_class_name %>Controller.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ def test_should_get_index
+ get :index
+ assert_response :success
+ assert assigns(:<%= table_name %>)
+ end
+
+ def test_should_get_new
+ get :new
+ assert_response :success
+ end
+
+ def test_should_create_<%= file_name %>
+ old_count = <%= class_name %>.count
+ post :create, :<%= file_name %> => { }
+ assert_equal old_count + 1, <%= class_name %>.count
+
+ assert_redirected_to <%= file_name %>_path(assigns(:<%= file_name %>))
+ end
+
+ def test_should_show_<%= file_name %>
+ get :show, :id => 1
+ assert_response :success
+ end
+
+ def test_should_get_edit
+ get :edit, :id => 1
+ assert_response :success
+ end
+
+ def test_should_update_<%= file_name %>
+ put :update, :id => 1, :<%= file_name %> => { }
+ assert_redirected_to <%= file_name %>_path(assigns(:<%= file_name %>))
+ end
+
+ def test_should_destroy_<%= file_name %>
+ old_count = <%= class_name %>.count
+ delete :destroy, :id => 1
+ assert_equal old_count-1, <%= class_name %>.count
+
+ assert_redirected_to <%= table_name %>_path
+ end
+end
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/helper.rb b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/helper.rb
new file mode 100644
index 0000000..9bd821b
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/helper.rb
@@ -0,0 +1,2 @@
+module <%= controller_class_name %>Helper
+end
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/migration.rb b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/migration.rb
new file mode 100644
index 0000000..5711faa
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/migration.rb
@@ -0,0 +1,13 @@
+class <%= migration_name %> < ActiveRecord::Migration
+ def self.up
+ create_table :<%= table_name %>, :force => true do |t|
+<% for attribute in attributes -%>
+ t.column :<%= attribute.name %>, :<%= attribute.type %>
+<% end -%>
+ end
+ end
+
+ def self.down
+ drop_table :<%= table_name %>
+ end
+end
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/model.rb b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/model.rb
new file mode 100644
index 0000000..8d4c89e
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/model.rb
@@ -0,0 +1,2 @@
+class <%= class_name %> < ActiveRecord::Base
+end
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/unit_test.rb b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/unit_test.rb
new file mode 100644
index 0000000..49ec7ca
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/unit_test.rb
@@ -0,0 +1,7 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../test_helper'
+
+class <%= class_name %>Test < Test::Unit::TestCase
+ def test_truth
+ assert true
+ end
+end
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view__form.haml b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view__form.haml
new file mode 100644
index 0000000..3c354e8
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view__form.haml
@@ -0,0 +1,5 @@
+<%- for attribute in attributes -%>
+%p
+ %label{:for => "<%= singular_name %>_<%= attribute.name %>"} <%= attribute.column.human_name %>:
+ = f.<%= attribute.field_type %> :<%= attribute.name %>
+<% end -%>
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_edit.haml b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_edit.haml
new file mode 100644
index 0000000..c54add0
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_edit.haml
@@ -0,0 +1,11 @@
+%h1 Editing <%= singular_name %>
+
+= error_messages_for :<%= singular_name %>
+
+- form_for(:<%= singular_name %>, :url => object_url, :html => { :method => :put }) do |f|
+ = render :partial => "form", :locals => {:f => f}
+ %p= submit_tag "Update"
+
+= link_to 'Show', object_path
+|
+= link_to 'Back', objects_path
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_index.haml b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_index.haml
new file mode 100644
index 0000000..ab46c62
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_index.haml
@@ -0,0 +1,5 @@
+%h1 Listing <%= plural_name %>
+
+= render :partial => '<%= singular_name %>', :collection => current_objects
+
+= link_to 'New <%= singular_name %>', new_object_path
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_new.haml b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_new.haml
new file mode 100644
index 0000000..ee16c90
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_new.haml
@@ -0,0 +1,9 @@
+%h1 Creating <%= singular_name %>
+
+= error_messages_for :<%= singular_name %>
+
+- form_for(:<%= singular_name %>, :url => objects_url) do |f|
+ = render :partial => "form", :locals => {:f => f}
+ %p= submit_tag "Create"
+
+= link_to 'Back', objects_path
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_partial.haml b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_partial.haml
new file mode 100644
index 0000000..5a61b4d
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_partial.haml
@@ -0,0 +1,12 @@
+%div[<%= singular_name %>]
+<% for attribute in attributes -%>
+ %p.<%= attribute.name %>
+ %strong <%= attribute.column.human_name %>
+ = h <%= singular_name %>.<%= attribute.name %>
+<% end -%>
+
+ = link_to 'Show', object_path(<%= singular_name %>)
+ |
+ = link_to 'Edit', edit_object_path(<%= singular_name %>)
+ |
+ = link_to 'Destroy', object_path(<%= singular_name %>), :confirm => 'Really destroy <%= singular_name %>?', :method => :delete
diff --git a/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_show.haml b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_show.haml
new file mode 100644
index 0000000..1fe80e0
--- /dev/null
+++ b/vendor/plugins/make_resourceful/generators/resourceful_scaffold/templates/view_show.haml
@@ -0,0 +1,14 @@
+%h1 Viewing <%= singular_name %>
+
+%div[current_object]
+<% for attribute in attributes -%>
+ %p.<%= attribute.name %>
+ %strong <%= attribute.column.human_name %>
+ = h current_object.<%= attribute.name %>
+<% end -%>
+
+= link_to 'Edit', edit_object_path
+|
+= link_to 'Destroy', object_path, :confirm => 'Really destroy <%= singular_name %>?', :method => :delete
+|
+= link_to 'Back', objects_path
diff --git a/vendor/plugins/make_resourceful/init.rb b/vendor/plugins/make_resourceful/init.rb
new file mode 100644
index 0000000..773c09a
--- /dev/null
+++ b/vendor/plugins/make_resourceful/init.rb
@@ -0,0 +1,3 @@
+require 'resourceful/maker'
+
+ActionController::Base.extend Resourceful::Maker
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/base.rb b/vendor/plugins/make_resourceful/lib/resourceful/base.rb
new file mode 100644
index 0000000..412e5ad
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/base.rb
@@ -0,0 +1,52 @@
+# The module containing all the code for make_resourceful.
+#
+# For methods available in the +make_resourceful+ block,
+# see Resourceful::Builder.
+#
+# For helper methods and methods you can override
+# to customize the behavior of your actions,
+# see Resourceful::Default::Accessors
+# and Resourceful::Default::URLs.
+module Resourceful
+ # We want to define some stuff before we load other modules
+
+ # The default actions generated by make_resourceful.
+ ACTIONS = [:index, :show, :edit, :update, :create, :new, :destroy]
+
+ # The actions that modify the database.
+ MODIFYING_ACTIONS = [:update, :create, :destroy]
+
+ # The actions that act on multiple records.
+ PLURAL_ACTIONS = [:index]
+
+ # The actions that act on just one record.
+ SINGULAR_ACTIONS = ACTIONS - PLURAL_ACTIONS
+end
+
+require 'resourceful/default/accessors'
+require 'resourceful/default/responses'
+require 'resourceful/default/callbacks'
+require 'resourceful/default/urls'
+
+# All modules included by this module
+# are made available to the controller as accessors.
+module Resourceful::Base
+ @@made_resourceful_callbacks = []
+
+ # This method is meant to be called by included classes.
+ # It takes a block of the same form as that given to Maker#make_resourceful.
+ # The Maker will then run that block
+ # along with the blocks given by the individual controllers.
+ def self.made_resourceful(&block)
+ if block
+ @@made_resourceful_callbacks << block
+ else
+ @@made_resourceful_callbacks
+ end
+ end
+
+ include Resourceful::Default::Accessors
+ include Resourceful::Default::Responses
+ include Resourceful::Default::Callbacks
+ include Resourceful::Default::URLs
+end
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/builder.rb b/vendor/plugins/make_resourceful/lib/resourceful/builder.rb
new file mode 100644
index 0000000..adf2663
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/builder.rb
@@ -0,0 +1,335 @@
+require 'resourceful/response'
+require 'resourceful/serialize'
+require 'resourceful/default/actions'
+
+module Resourceful
+ # The Maker#make_resourceful block is evaluated in the context
+ # of an instance of this class.
+ # It provides various methods for customizing the behavior of the actions
+ # built by make_resourceful.
+ #
+ # All instance methods of this class are available in the +make_resourceful+ block.
+ class Builder
+ # The klass of the controller on which the builder is working.
+ attr :controller, true
+
+ # The constructor is only meant to be called internally.
+ #
+ # This takes the klass (class object) of a controller
+ # and constructs a Builder ready to apply the make_resourceful
+ # additions to the controller.
+ def initialize(kontroller)
+ @controller = kontroller
+ @inherited = !kontroller.read_inheritable_attribute(:resourceful_responses).blank?
+ @action_module = Resourceful::Default::Actions.dup
+ @ok_actions = []
+ @callbacks = {:before => {}, :after => {}}
+ @responses = {}
+ @publish = {}
+ @parents = []
+ end
+
+ # This method is only meant to be called internally.
+ #
+ # Applies all the changes that have been declared
+ # via the instance methods of this Builder
+ # to the kontroller passed in to the constructor.
+ def apply
+ apply_publish
+
+ kontroller = @controller
+ Resourceful::ACTIONS.each do |action_named|
+ # See if this is a method listed by #actions
+ unless @ok_actions.include? action_named
+ # If its not listed, then remove the method
+ # No one can hit it... if its DEAD!
+ @action_module.send :remove_method, action_named
+ end
+ end
+
+ kontroller.hidden_actions.reject! &@ok_actions.method(:include?)
+ kontroller.send :include, @action_module
+
+ kontroller.read_inheritable_attribute(:resourceful_callbacks).merge! @callbacks
+ kontroller.read_inheritable_attribute(:resourceful_responses).merge! @responses
+ kontroller.write_inheritable_attribute(:made_resourceful, true)
+
+ kontroller.write_inheritable_attribute(:parents, @parents)
+ kontroller.before_filter :load_parent_object, :only => @ok_actions
+ end
+
+ # :call-seq:
+ # actions(*available_actions)
+ # actions :all
+ #
+ # Adds the default RESTful actions to the controller.
+ #
+ # If the only argument is <tt>:all</tt>,
+ # adds all the actions listed in Resourceful::ACTIONS[link:classes/Resourceful.html]
+ # (or Resourceful::SINGULAR_ACTIONS[link:classes/Resourceful.html]
+ # for a singular controller).
+ #
+ # Otherwise, this adds all actions
+ # whose names were passed as arguments.
+ #
+ # For example:
+ #
+ # actions :show, :new, :create
+ #
+ # This adds the +show+, +new+, and +create+ actions
+ # to the controller.
+ #
+ # The available actions are defined in Default::Actions.
+ def actions(*available_actions)
+ if available_actions.first == :all
+ available_actions = controller.new.plural? ? ACTIONS : SINGULAR_ACTIONS
+ end
+
+ available_actions.each { |action| @ok_actions << action.to_sym }
+ end
+ alias build actions
+
+ # :call-seq:
+ # before(*events) { ... }
+ #
+ # Sets up a block of code to run before one or more events.
+ #
+ # All the default actions can be used as +before+ events:
+ # <tt>:index</tt>, <tt>:show</tt>, <tt>:create</tt>, <tt>:update</tt>, <tt>:new</tt>, <tt>:edit</tt>, and <tt>:destroy</tt>.
+ #
+ # +before+ events are run after any objects are loaded[link:classes/Resourceful/Default/Accessors.html#M000015],
+ # but before any database operations or responses.
+ #
+ # For example:
+ #
+ # before :show, :edit do
+ # @page_title = current_object.title
+ # end
+ #
+ # This will set the <tt>@page_title</tt> variable
+ # to the current object's title
+ # for the show and edit actions.
+ def before(*events, &block)
+ events.each do |event|
+ @callbacks[:before][event.to_sym] = block
+ end
+ end
+
+ # :call-seq:
+ # after(*events) { ... }
+ #
+ # Sets up a block of code to run after one or more events.
+ #
+ # There are two sorts of +after+ events.
+ # <tt>:create</tt>, <tt>:update</tt>, and <tt>:destroy</tt>
+ # are run after their respective database operations
+ # have been completed successfully.
+ # <tt>:create_fails</tt>, <tt>:update_fails</tt>, and <tt>:destroy_fails</tt>,
+ # on the other hand,
+ # are run after the database operations fail.
+ #
+ # +after+ events are run after the database operations
+ # but before any responses.
+ #
+ # For example:
+ #
+ # after :create_fails, :update_fails do
+ # current_object.password = nil
+ # end
+ #
+ # This will nillify the password of the current object
+ # if the object creation/modification failed.
+ def after(*events, &block)
+ events.each do |event|
+ @callbacks[:after][event.to_sym] = block
+ end
+ end
+
+ # :call-seq:
+ # response_for(*actions) { ... }
+ # response_for(*actions) { |format| ... }
+ #
+ # Sets up a block of code to run
+ # instead of the default responses for one or more events.
+ #
+ # If the block takes a format parameter,
+ # it has the same semantics as Rails' +respond_to+ method.
+ # Various format methods are called on the format object
+ # with blocks that say what to do for each format.
+ # For example:
+ #
+ # response_for :index do |format|
+ # format.html
+ # format.atom do
+ # headers['Content-Type'] = 'application/atom+xml; charset=utf-8'
+ # render :action => 'atom', :layout => false
+ # end
+ # end
+ #
+ # This doesn't do anything special for the HTML
+ # other than ensure that the proper view will be rendered,
+ # but for ATOM it sets the proper content type
+ # and renders the atom template.
+ #
+ # If you only need to set the HTML response,
+ # you can omit the format parameter.
+ # For example:
+ #
+ # response_for :new do
+ # render :action => 'edit'
+ # end
+ #
+ # This is the same as
+ #
+ # response_for :new do |format|
+ # format.html { render :action => 'edit' }
+ # end
+ #
+ # The default responses are defined by
+ # Default::Responses.included[link:classes/Resourceful/Default/Responses.html#M000011].
+ def response_for(*actions, &block)
+ raise "Must specify one or more actions for response_for." if actions.empty?
+
+ if block.arity < 1
+ response_for(*actions) do |format|
+ format.html(&block)
+ end
+ else
+ response = Response.new
+ block.call response
+
+ actions.each do |action|
+ @responses[action.to_sym] = response.formats
+ end
+ end
+ end
+
+ # :call-seq:
+ # publish *formats, options = {}, :attributes => [ ... ]
+ #
+ # publish allows you to easily expose information about resourcess in a variety of formats.
+ # The +formats+ parameter is a list of formats
+ # in which to publish the resources.
+ # The formats supported by default are +xml+, +yaml+, and +json+,
+ # but other formats may be added by defining +to_format+ methods
+ # for the Array and Hash classes
+ # and registering the mime type with Rails' Mime::Type.register[http://api.rubyonrails.org/classes/Mime/Type.html#M001115].
+ # See Resourceful::Serialize for more details..
+ #
+ # The <tt>:attributes</tt> option is mandatory.
+ # It takes an array of attributes (as symbols) to make public.
+ # These attributes can refer to any method on current_object;
+ # they aren't limited to database fields.
+ # For example:
+ #
+ # # posts_controller.rb
+ # publish :yaml, :attributes => [:title, :created_at, :rendered_content]
+ #
+ # Then GET /posts/12.yaml would render
+ #
+ # ---
+ # post:
+ # title: Cool Stuff
+ # rendered_content: |-
+ # <p>This is a post.</p>
+ # <p>It's about <strong>really</strong> cool stuff.</p>
+ # created_at: 2007-04-28 04:32:08 -07:00
+ #
+ # The <tt>:attributes</tt> array can even contain attributes
+ # that are themselves models.
+ # In this case, you must use a hash to specify their attributes as well.
+ # For example:
+ #
+ # # person_controller.rb
+ # publish :xml, :json, :attributes => [
+ # :name, :favorite_color, {
+ # :pet_cat => [:name, :breed],
+ # :hat => [:type]
+ # }]
+ #
+ # Then GET /people/18.xml would render
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <person>
+ # <name>Nathan</name>
+ # <favorite-color>blue</favorite_color>
+ # <pet-cat>
+ # <name>Jasmine</name>
+ # <breed>panther</breed>
+ # </pet-cat>
+ # <hat>
+ # <type>top</type>
+ # </hat>
+ # </person>
+ #
+ # publish will also allow the +index+ action
+ # to render lists of objects.
+ # An example would be too big,
+ # but play with it a little on your own to see.
+ #
+ # publish takes only one optional option: <tt>only</tt>.
+ # This specifies which action to publish the resources for.
+ # By default, they're published for both +show+ and +index+.
+ # For example:
+ #
+ # # cats_controller.rb
+ # publish :json, :only => :index, :attributes => [:name, :breed]
+ #
+ # Then GET /cats.json would work, but GET /cats/294.json would fail.
+ def publish(*formats)
+ options = {
+ :only => [:show, :index]
+ }.merge(Hash === formats.last ? formats.pop : {})
+ raise "Must specify :attributes option" unless options[:attributes]
+
+ Array(options.delete(:only)).each do |action|
+ @publish[action] ||= []
+ formats.each do |format|
+ format = format.to_sym
+ @publish[action] << [format, proc do
+ render_action = [:json, :xml].include?(format) ? format : :text
+ render render_action => (plural_action? ? current_objects : current_object).serialize(format, options)
+ end]
+ end
+ end
+ end
+
+ # Specifies parent resources for the current resource.
+ # Each of these parents will be loaded automatically
+ # if the proper id parameter is given.
+ # For example,
+ #
+ # # cake_controller.rb
+ # belongs_to :baker, :customer
+ #
+ # Then on GET /bakers/12/cakes,
+ #
+ # params[:baker_id] #=> 12
+ # parent? #=> true
+ # parent_name #=> "baker"
+ # parent_model #=> Baker
+ # parent_object #=> Baker.find(12)
+ # current_objects #=> Baker.find(12).cakes
+ #
+ def belongs_to(*parents)
+ @parents = parents.map(&:to_s)
+ end
+
+ # This method is only meant to be called internally.
+ #
+ # Returns whether or not the Builder's controller
+ # inherits make_resourceful settings from a parent controller.
+ def inherited?
+ @inherited
+ end
+
+ private
+
+ def apply_publish
+ @publish.each do |action, types|
+ @responses[action.to_sym] ||= []
+ @responses[action.to_sym] += types
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/default/accessors.rb b/vendor/plugins/make_resourceful/lib/resourceful/default/accessors.rb
new file mode 100644
index 0000000..d98386d
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/default/accessors.rb
@@ -0,0 +1,346 @@
+module Resourceful
+ # This module contains various methods
+ # that are available from actions and callbacks.
+ # Default::Accessors and Default::URLs are the most useful to users;
+ # the rest are mostly used internally.
+ #
+ # However, if you want to poke around the internals a little,
+ # check out Default::Actions, which has the default Action definitions,
+ # and Default::Responses.included, which defines the default response_for[link:classes/Resourceful/Builder.html#M000061] blocks.
+ module Default
+ # This module contains all sorts of useful methods
+ # that allow access to the resources being worked with,
+ # metadata about the controller and action,
+ # and so forth.
+ #
+ # Many of these accessors call other accessors
+ # and are called by the default make_resourceful actions[link:classes/Resourceful/Default/Actions.html].
+ # This means that overriding one method
+ # can affect everything else.
+ #
+ # This can be dangerous, but it can also be very powerful.
+ # make_resourceful is designed to take advantage of overriding,
+ # so as long as the new methods accomplish the same purpose as the old ones,
+ # everything will just work.
+ # Even if you make a small mistake,
+ # it's hard to break the controller in any unexpected ways.
+ #
+ # For example, suppose your controller is called TagsController,
+ # but your model is called PhotoTag.
+ # All you have to do is override current_model_name:
+ #
+ # def current_model_name
+ # "PhotoTag"
+ # end
+ #
+ # Then current_model will return the PhotoTag model,
+ # current_object will call <tt>PhotoTag.find</tt>,
+ # and so forth.
+ #
+ # Overriding current_objects and current_object is particularly useful
+ # for providing customized model lookup logic.
+ module Accessors
+ # Returns an array of all the objects of the model corresponding to the controller.
+ # For UsersController, it essentially runs <tt>User.find(:all)</tt>.
+ #
+ # However, there are a few important differences.
+ # First, this method caches is results in the <tt>@current_objects</tt> instance variable.
+ # That way, multiple calls won't run multiple queries.
+ #
+ # Second, this method uses the current_model accessor,
+ # which provides a lot of flexibility
+ # (see the documentation for current_model for details).
+ def current_objects
+ @current_objects ||= current_model.find(:all)
+ end
+
+ # Calls current_objects and stores
+ # the result in an instance variable
+ # named after the controller.
+ #
+ # This is called automatically by the default make_resourceful actions.
+ # You shouldn't need to use it directly unless you're creating a new action.
+ #
+ # For example, in UsersController,
+ # calling +load_objects+ sets <tt>@users = current_objects</tt>.
+ def load_objects
+ instance_variable_set("@#{instance_variable_name}", current_objects)
+ end
+
+ # Returns the object referenced by the id parameter
+ # (or the newly-created object for the +new+ and +create+ actions).
+ # For UsersController, it essentially runs <tt>User.find(params[:id])</tt>.
+ #
+ # However, there are a few important differences.
+ # First, this method caches is results in the <tt>@current_objects</tt> instance variable.
+ # That way, multiple calls won't run multiple queries.
+ #
+ # Second, this method uses the current_model accessor,
+ # which provides a lot of flexibility
+ # (see the documentation for current_model for details).
+ #
+ # Note that this is different for a singleton controller,
+ # where there's only one resource per parent resource.
+ # Then this just returns that resource.
+ # For example, if Person has_one Hat,
+ # then in HatsController current_object essentially runs <tt>Person.find(params[:person_id]).hat</tt>.
+ def current_object
+ @current_object ||= if plural?
+ current_model.find(params[:id])
+ else
+ parent_object.send(instance_variable_name)
+ end
+ end
+
+
+ # Calls current_object and stores
+ # the result in an instance variable
+ # named after the controller.
+ #
+ # This is called automatically by the default make_resourceful actions.
+ # You shouldn't need to use it directly unless you're creating a new action.
+ #
+ # For example, in UsersController,
+ # calling +load_object+ sets <tt>@user = current_object</tt>.
+ def load_object
+ instance_variable_set("@#{instance_variable_name.singularize}", current_object)
+ end
+
+ # Creates a new object of the type of the current model
+ # with the current object's parameters.
+ # +current_object+ then returns this object for this action
+ # instead of looking up a new object.
+ #
+ # This is called automatically by the default make_resourceful actions.
+ # You shouldn't need to use it directly unless you're creating a new action.
+ #
+ # Note that if a parent object exists,
+ # the newly created object will automatically be a child of the parent object.
+ # For example, on POST /people/4/things,
+ #
+ # build_object
+ # current_object.person.id #=> 4
+ #
+ def build_object
+ @current_object = if current_model.respond_to? :build
+ current_model.build(object_parameters)
+ else
+ returning(current_model.new(object_parameters)) do |obj|
+ obj.send("#{parent_name}_id=", parent_object.id) if singular? && parent?
+ end
+ end
+ end
+
+ # The string name of the current model.
+ # By default, this is derived from the name of the controller.
+ def current_model_name
+ controller_name.singularize.camelize
+ end
+
+ # An array of namespaces under which the current controller is.
+ # For example, in Admin::Content::PagesController:
+ #
+ # namespaces #=> [:admin, :content]
+ #
+ def namespaces
+ @namespaces ||= self.class.name.split('::').slice(0...-1).map(&:underscore).map(&:to_sym)
+ end
+
+ # The name of the instance variable that load_object and load_objects should assign to.
+ def instance_variable_name
+ controller_name
+ end
+
+ # The class of the current model.
+ # Note that if a parent object exists,
+ # this instead returns the association object.
+ # For example, in HatsController where Person has_many :hats,
+ #
+ # current_model #=> Person.find(params[:person_id]).hats
+ #
+ # This is useful because the association object uses duck typing
+ # to act like a model class.
+ # It supplies a find method that's automatically scoped
+ # to ensure that the object returned is actually a child of the parent,
+ # and so forth.
+ def current_model
+ if !parent? || singular?
+ current_model_name.constantize
+ else
+ parent_object.send(instance_variable_name)
+ end
+ end
+
+ # Returns the hash passed as HTTP parameters
+ # that defines the new (or updated) attributes
+ # of the current object.
+ # This is only meaningful for +create+ or +update+.
+ def object_parameters
+ params[current_model_name.underscore]
+ end
+
+ # Returns a list of the names of all the potential parents of the current model.
+ # For a non-nested controller, this is <tt>[]</tt>.
+ # For example, in HatsController where Rack has_many :hats and Person has_many :hats,
+ #
+ # parents #=> ["rack", "person"]
+ #
+ # Note that the parents must be declared via Builder#belongs_to.
+ def parent_names
+ self.class.read_inheritable_attribute :parents
+ end
+
+ # Returns true if an appropriate parent id parameter has been supplied.
+ # For example, in HatsController where Rack has_many :hats and Person has_many :hats,
+ # if <tt>params[:rack_id]</tt> or <tt>params[:person_id]</tt> is given,
+ #
+ # parent? #=> true
+ #
+ # Otherwise, if both <tt>params[:rack_id]</tt> and <tt>params[:rack_id]</tt> are nil,
+ #
+ # parent? #=> false
+ #
+ # Note that parents must be declared via Builder#belongs_to.
+ def parent?
+ !!parent_name
+ end
+
+ # Returns the name of the current parent object if a parent id is given, or nil otherwise.
+ # For example, in HatsController where Rack has_many :hats and Person has_many :hats,
+ # if <tt>params[:rack_id]</tt> is given,
+ #
+ # parent_name #=> "rack"
+ #
+ # If <tt>params[:person_id]</tt> is given,
+ #
+ # parent_name #=> "person"
+ #
+ # If both <tt>params[:rack_id]</tt> and <tt>params[:rack_id]</tt> are nil,
+ #
+ # parent_name #=> nil
+ #
+ # There are several things to note about this method.
+ # First, make_resourceful only supports single-level model nesting.
+ # Thus, if neither <tt>params[:rack_id]</tt> nor <tt>params[:rack_id]</tt> are nil,
+ # the return value of +parent_name+ is undefined.
+ #
+ # Second, don't use parent_name to check whether a parent id is given.
+ # It's better to use the more semantic parent? method.
+ #
+ # Third, parent_name caches its return value in the <tt>@parent_name</tt> variable,
+ # which you should keep in mind if you're overriding it.
+ # However, because <tt>@parent_name == nil</tt> could mean that there is no parent
+ # _or_ that the method hasn't been run yet,
+ # it uses <tt>defined?(@parent_name)</tt> to do the caching
+ # rather than <tt>@parent_name ||=</tt>. See the source code.
+ #
+ # Finally, note that parents must be declared via Builder#belongs_to.
+ def parent_name
+ return @parent_name if defined?(@parent_name)
+ @parent_name = parent_names.find { |name| params["#{name}_id"] }
+ end
+
+ # Returns the model class of the current parent.
+ # For example, in HatsController where Person has_many :hats,
+ # if <tt>params[:person_id]</tt> is given,
+ #
+ # parent_models #=> Rack
+ #
+ # Note that parents must be declared via Builder#belongs_to.
+ def parent_model
+ parent_name.camelize.constantize
+ end
+
+ # Returns the current parent object for the current object.
+ # For example, in HatsController where Person has_many :hats,
+ # if <tt>params[:person_id]</tt> is given,
+ #
+ # parent_object #=> Person.find(params[:person_id])
+ #
+ # Note that parents must be declared via Builder#belongs_to.
+ #
+ # Note also that the results of this method are cached
+ # so that multiple calls don't result in multiple SQL queries.
+ def parent_object
+ @parent_object ||= parent_model.find(params["#{parent_name}_id"])
+ end
+
+ # Assigns the current parent object, as given by parent_objects,
+ # to its proper instance variable, as given by parent_name.
+ #
+ # This is automatically added as a before_filter.
+ # You shouldn't need to use it directly unless you're creating a new action.
+ def load_parent_object
+ instance_variable_set("@#{parent_name}", parent_object) if parent?
+ end
+
+ # Renders a 422 error if no parent id is given.
+ # This is meant to be used with before_filter
+ # to ensure that some actions are only called with a parent id.
+ # For example:
+ #
+ # before_filter :ensure_parent_exists, :only => [:create, :update]
+ #
+ def ensure_parent_exists
+ return true if parent?
+ render :text => 'No parent id given', :status => 422
+ return false
+ end
+
+ # Returns whether or not the database update in the +create+, +update+, and +destroy+
+ # was completed successfully.
+ def save_succeeded?
+ @save_succeeded
+ end
+
+ # Declares that the current databse update was completed successfully.
+ # Causes subsequent calls to <tt>save_succeeded?</tt> to return +true+.
+ #
+ # This is mostly meant to be used by the default actions,
+ # but it can be used by user-defined actions as well.
+ def save_succeeded!
+ @save_succeeded = true
+ end
+
+ # Declares that the current databse update was not completed successfully.
+ # Causes subsequent calls to <tt>save_succeeded?</tt> to return +false+.
+ #
+ # This is mostly meant to be used by the default actions,
+ # but it can be used by user-defined actions as well.
+ def save_failed!
+ @save_succeeded = false
+ end
+
+ # Returns whether or not the current action acts upon multiple objects.
+ # By default, the only such action is +index+.
+ def plural_action?
+ PLURAL_ACTIONS.include?(params[:action].to_sym)
+ end
+
+ # Returns whether or not the current action acts upon a single object.
+ # By default, this is the case for all actions but +index+.
+ def singular_action?
+ !plural_action?
+ end
+
+ # Returns whether the controller is a singleton,
+ # implying that there is only one such resource for each parent resource.
+ #
+ # Note that the way this is determined is based on the singularity of the controller name,
+ # so it may yield false positives for oddly-named controllers and need to be overridden.
+ def singular?
+ instance_variable_name.singularize == instance_variable_name
+ end
+
+ # Returns whether the controller is a normal plural controller,
+ # implying that there are multiple resources for each parent resource.
+ #
+ # Note that the way this is determined is based on the singularity of the controller name,
+ # so it may yield false negatives for oddly-named controllers.
+ # If this is the case, the singular? method should be overridden.
+ def plural?
+ !singular?
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/default/actions.rb b/vendor/plugins/make_resourceful/lib/resourceful/default/actions.rb
new file mode 100644
index 0000000..61e8088
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/default/actions.rb
@@ -0,0 +1,92 @@
+module Resourceful
+ module Default
+ # Contains the definitions of the default resourceful actions.
+ # These are made available with the Builder#actions method.
+ #
+ # These methods are very compact,
+ # so the best way to understand them is just to look at their source.
+ # Check out Resourceful::Accessors and Resourceful::Callbacks
+ # for the documentation of the methods called within the actions.
+ #
+ # Along with each action is listed the RESTful method
+ # which corresponds to the action.
+ # The controller in the examples is FoosController,
+ # and the id for single-object actions is 12.
+ module Actions
+ # GET /foos
+ def index
+ load_objects
+ before :index
+ response_for :index
+ end
+
+ # GET /foos/12
+ def show
+ load_object
+ before :show
+ response_for :show
+ rescue
+ response_for :show_fails
+ end
+
+ # POST /foos
+ def create
+ build_object
+ load_object
+ before :create
+ if current_object.save
+ save_succeeded!
+ after :create
+ response_for :create
+ else
+ save_failed!
+ after :create_fails
+ response_for :create_fails
+ end
+ end
+
+ # PUT /foos/12
+ def update
+ load_object
+ before :update
+ if current_object.update_attributes object_parameters
+ save_succeeded!
+ after :update
+ response_for :update
+ else
+ save_failed!
+ after :update_fails
+ response_for :update_fails
+ end
+ end
+
+ # GET /foos/new
+ def new
+ build_object
+ load_object
+ before :new
+ response_for :new
+ end
+
+ # GET /foos/12/edit
+ def edit
+ load_object
+ before :edit
+ response_for :edit
+ end
+
+ # DELETE /foos/12
+ def destroy
+ load_object
+ before :destroy
+ if current_object.destroy
+ after :destroy
+ response_for :destroy
+ else
+ after :destroy_fails
+ response_for :destroy_fails
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/default/callbacks.rb b/vendor/plugins/make_resourceful/lib/resourceful/default/callbacks.rb
new file mode 100644
index 0000000..6738a49
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/default/callbacks.rb
@@ -0,0 +1,50 @@
+require 'resourceful/builder'
+
+module Resourceful
+ module Default
+ # This module is mostly meant to be used by the make_resourceful default actions.
+ # It provides various methods that declare where callbacks set in the +make_resourceful+ block,
+ # like Builder#before and Builder#response_for,
+ # should be called.
+ module Callbacks
+ # Calls any +before+ callbacks set in the +make_resourceful+ block for the given event.
+ def before(event)
+ resourceful_fire(:before, event.to_sym)
+ end
+
+ # Calls any +after+ callbacks set in the +make_resourceful+ block for the given event.
+ def after(event)
+ resourceful_fire(:after, event.to_sym)
+ end
+
+ # Calls any +response_for+ callbacks set in the +make_resourceful+ block for the given event.
+ # Note that these aren't called directly,
+ # but instead passed along to Rails' respond_to method.
+ def response_for(event)
+ if responses = self.class.read_inheritable_attribute(:resourceful_responses)[event.to_sym]
+ respond_to do |format|
+ responses.each do |key, value|
+ format.send(key, &scope(value))
+ end
+ end
+ end
+ end
+
+ # Returns a block identical to the given block,
+ # but in the context of the current controller.
+ # The returned block accepts no arguments,
+ # even if the given block accepted them.
+ def scope(block)
+ lambda do
+ instance_eval(&(block || lambda {}))
+ end
+ end
+
+ private
+
+ def resourceful_fire(type, name)
+ scope(self.class.read_inheritable_attribute(:resourceful_callbacks)[type][name]).call
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/default/responses.rb b/vendor/plugins/make_resourceful/lib/resourceful/default/responses.rb
new file mode 100644
index 0000000..67cd5e6
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/default/responses.rb
@@ -0,0 +1,118 @@
+module Resourceful
+ module Default
+ module Responses
+ # Sets the default flash message.
+ # This message can be overridden by passing in
+ # an HTTP parameter of the form "_flash[type]" via POST or GET.
+ #
+ # You can use this to easily have multiple forms
+ # post to the same create/edit/destroy actions
+ # but display different flash notices -
+ # without modifying the controller code at all.
+ #
+ # By default, the flash types are +notice+ when the database operation completes successfully
+ # and +error+ when it fails.
+ #
+ #--
+ # TODO: Move this out of here
+ #++
+ def set_default_flash(type, message)
+ flash[type] ||= (params[:_flash] && params[:_flash][type]) || message
+ end
+
+ # Sets the default redirect
+ # (the argument passed to +redirect_to+).
+ # This message can be overridden by passing in
+ # an HTTP parameter of the form "_redirect_on[status]" via POST or GET.
+ #
+ # You can use this to easily have multiple forms
+ # post to the same create/edit/destroy actions
+ # but redirect to different URLs -
+ # without modifying the controller code at all.
+ #
+ # By default, the redirect statuses are +success+ when the database operation completes successfully
+ # and +failure+ when it fails.
+ # Use the <tt>:status</tt> option to specify which status to run the redirect for.
+ # For example:
+ #
+ # set_default_redirect "/posts", :status => :failure
+ #
+ # This will run <tt>redirect_to params[:_redirect_on][:failure]</tt> if the parameter exists,
+ # or <tt>redirect_to "/posts"</tt> otherwise.
+ #
+ #--
+ # TODO: Move this out of here
+ #++
+ def set_default_redirect(to, options = {})
+ status = options[:status] || :success
+ redirect_to (params[:_redirect_on] && params[:_redirect_on][status]) || to
+ end
+
+ # This method is automatically run when this module is included in Resourceful::Base.
+ # It sets up the default responses for the default actions.
+ def self.included(base)
+ base.made_resourceful do
+ response_for(:show, :index, :edit, :new) do |format|
+ format.html
+ format.js
+ end
+
+ response_for(:show_fails) do |format|
+ not_found = Proc.new { render :text => "No item found", :status => 404 }
+ format.html ¬_found
+ format.js ¬_found
+ format.xml ¬_found
+ end
+
+ response_for(:create) do |format|
+ format.html do
+ set_default_flash(:notice, "Create successful!")
+ set_default_redirect object_path
+ end
+ format.js
+ end
+
+ response_for(:create_fails) do |format|
+ format.html do
+ set_default_flash :error, "There was a problem!"
+ render :action => :new, :status => 422
+ end
+ format.js
+ end
+
+ response_for(:update) do |format|
+ format.html do
+ set_default_flash :notice, "Save successful!"
+ set_default_redirect object_path
+ end
+ format.js
+ end
+
+ response_for(:update_fails) do |format|
+ format.html do
+ set_default_flash :error, "There was a problem saving!"
+ render :action => :edit, :status => 422
+ end
+ format.js
+ end
+
+ response_for(:destroy) do |format|
+ format.html do
+ set_default_flash :notice, "Record deleted!"
+ set_default_redirect objects_path
+ end
+ format.js
+ end
+
+ response_for(:destroy_fails) do |format|
+ format.html do
+ set_default_flash :error, "There was a problem deleting!"
+ set_default_redirect :back, :status => :failure
+ end
+ format.js
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/default/urls.rb b/vendor/plugins/make_resourceful/lib/resourceful/default/urls.rb
new file mode 100644
index 0000000..589ef09
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/default/urls.rb
@@ -0,0 +1,137 @@
+module Resourceful
+ module Default
+ # This file contains various methods to make URL helpers less painful.
+ # They provide methods analogous to the standard foo_url and foo_path helpers.
+ # However, they use make_resourceful's knowledge of the structure of the controller
+ # to allow you to avoid figuring out which method to call and which parent objects it should be passed.
+ module URLs
+ # This returns the path for the given object,
+ # by default current_object[link:classes/Resourceful/Default/Accessors.html#M000012].
+ # For example, in HatsController the following are equivalent:
+ #
+ # object_path #=> "/hats/12"
+ # hat_path(@hat) #=> "/hats/12"
+ #
+ def object_path(object = current_object); object_route(object, 'path'); end
+ # Same as object_path, but with the protocol and hostname.
+ def object_url (object = current_object); object_route(object, 'url'); end
+
+ # This is the same as object_path,
+ # unless a parent exists.
+ # Then it returns the nested path for the object.
+ # For example, in HatsController where Person has_many :hats and <tt>params[:person_id] == 42</tt>,
+ # the following are equivalent:
+ #
+ # nested_object_path #=> "/person/42/hats/12"
+ # person_hat_path(@person, @hat) #=> "/person/42/hats/12"
+ #
+ def nested_object_path(object = current_object); nested_object_route(object, 'path'); end
+ # Same as nested_object_path, but with the protocol and hostname.
+ def nested_object_url (object = current_object); nested_object_route(object, 'url'); end
+
+ # This returns the path for the edit action for the given object,
+ # by default current_object[link:classes/Resourceful/Default/Accessors.html#M000012].
+ # For example, in HatsController the following are equivalent:
+ #
+ # edit_object_path #=> "/hats/12/edit"
+ # edit_person_hat_path(@person, @hat) #=> "/hats/12/edit"
+ #
+ def edit_object_path(object = current_object); edit_object_route(object, 'path'); end
+ # Same as edit_object_path, but with the protocol and hostname.
+ def edit_object_url (object = current_object); edit_object_route(object, 'url'); end
+
+ # This returns the path for the collection of the current controller.
+ # For example, in HatsController where Person has_many :hats and <tt>params[:person_id] == 42</tt>,
+ # the following are equivalent:
+ #
+ # objects_path #=> "/people/42/hats"
+ # person_hats_path(@person) #=> "/people/42/hats"
+ #
+ def objects_path; objects_route('path'); end
+ # Same as objects_path, but with the protocol and hostname.
+ def objects_url ; objects_route('url'); end
+
+ # This returns the path for the new action for the current controller.
+ # For example, in HatsController where Person has_many :hats and <tt>params[:person_id] == 42</tt>,
+ # the following are equivalent:
+ #
+ # new_object_path #=> "/people/42/hats/new"
+ # new_person_hat_path(@person) #=> "/people/42/hats/new"
+ #
+ def new_object_path; new_object_route('path'); end
+ # Same as new_object_path, but with the protocol and hostname.
+ def new_object_url ; new_object_route('url'); end
+
+ # This returns the path for the parent object.
+ #
+ def parent_path(object = parent_object)
+ instance_route(parent_name, object, 'path')
+ end
+ # Same as parent_path, but with the protocol and hostname.
+ def parent_url(object = parent_object)
+ instance_route(parent_name, object, 'url')
+ end
+
+ # This prefix is added to the Rails URL helper names
+ # before they're called.
+ # By default, it's the underscored list of namespaces of the current controller,
+ # or nil if there are no namespaces defined.
+ # However, it can be overridden if another prefix is needed.
+ # Note that if this is overridden,
+ # the new method should return a string ending in an underscore.
+ #
+ # For example, in Admin::Content::PagesController:
+ #
+ # url_helper_prefix #=> "admin_content_"
+ #
+ # Then object_path is the same as <tt>admin_content_page_path(current_object)</tt>.
+ def url_helper_prefix
+ namespaces.empty? ? nil : "#{namespaces.join('_')}_"
+ end
+
+ # This prefix is added to the Rails URL helper names
+ # for the make_resourceful collection URL helpers,
+ # objects_path and new_object_path.
+ # It's only added if url_helper_prefix returns nil.
+ # By default, it's the parent name followed by an underscore if a parent is given,
+ # and the empty string otherwise.
+ #
+ # See also url_helper_prefix.
+ def collection_url_prefix
+ parent? ? "#{parent_name}_" : ''
+ end
+
+ private
+
+ def object_route(object, type)
+ instance_route(current_model_name.underscore, object, type)
+ end
+
+ def nested_object_route(object, type)
+ return object_route(object, type) unless parent?
+ send("#{url_helper_prefix}#{parent_name}_#{current_model_name.underscore}_#{type}", parent_object, object)
+ end
+
+ def edit_object_route(object, type)
+ instance_route(current_model_name.underscore, object, type, "edit")
+ end
+
+ def objects_route(type)
+ collection_route(current_model_name.pluralize.underscore, type)
+ end
+
+ def new_object_route(type)
+ collection_route(current_model_name.underscore, type, "new")
+ end
+
+ def instance_route(name, object, type, action = nil)
+ send("#{action ? action + '_' : ''}#{url_helper_prefix}#{name}_#{type}", object)
+ end
+
+ def collection_route(name, type, action = nil)
+ send("#{action ? action + '_' : ''}#{url_helper_prefix || collection_url_prefix}#{name}_#{type}",
+ *(parent? ? [parent_object] : []))
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/maker.rb b/vendor/plugins/make_resourceful/lib/resourceful/maker.rb
new file mode 100644
index 0000000..adfd8e3
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/maker.rb
@@ -0,0 +1,83 @@
+require 'resourceful/builder'
+require 'resourceful/base'
+
+module Resourceful
+ # This module is extended by the ActionController::Base class object.
+ # It provides the actual +make_resourceful+ method
+ # and sets up the controller so that everything will work.
+ module Maker
+ # Called automatically on ActionController::Base.
+ # Initializes various inheritable attributes.
+ def self.extended(base)
+ base.write_inheritable_attribute :resourceful_callbacks, {}
+ base.write_inheritable_attribute :resourceful_responses, {}
+ base.write_inheritable_attribute :parents, []
+ base.write_inheritable_attribute :made_resourceful, false
+ end
+
+ # :call-seq:
+ # make_resourceful(options = {}) { ... }
+ #
+ # This is the central method, and namesake, of make_resourceful.
+ # It takes a block and evaluates it in the context of a Builder,
+ # allowing the controller to be customized extensively.
+ #
+ # See Resourceful::Builder for documentation on the methods available
+ # in the context of the block.
+ #
+ # The only option currently available is <tt>:include</tt>.
+ # It takes an object that responds to to_proc
+ # (or an array of such objects)
+ # and evaluates that proc in the same context as the block.
+ # For example:
+ #
+ # make_resourceful :include => proc { actions :all } do
+ # before :show do
+ # current_object.current_user = current_user
+ # end
+ # end
+ #
+ # This is the same as:
+ #
+ # make_resourceful do
+ # actions :all
+ # before :show do
+ # current_object.current_user = current_user
+ # end
+ # end
+ #
+ def make_resourceful(options = {}, &block)
+ # :stopdoc:
+ include Resourceful::Base
+ # :startdoc:
+
+ builder = Resourceful::Builder.new(self)
+ unless builder.inherited?
+ Resourceful::Base.made_resourceful.each { |proc| builder.instance_eval(&proc) }
+ end
+ Array(options[:include]).each { |proc| builder.instance_eval(&proc) }
+ builder.instance_eval(&block)
+
+ builder.apply
+
+ add_helpers
+ end
+
+ # Returns whether or not make_resourceful has been called
+ # on this controller or any controllers it inherits from.
+ def made_resourceful?
+ read_inheritable_attribute(:made_resourceful)
+ end
+
+ private
+
+ def add_helpers
+ helper_method(:object_path, :objects_path, :new_object_path, :edit_object_path,
+ :object_url, :objects_url, :new_object_url, :edit_object_url,
+ :parent_path, :parent_url,
+ :current_objects, :current_object, :current_model, :current_model_name,
+ :namespaces, :instance_variable_name, :parent_names, :parent_name,
+ :parent?, :parent_model, :parent_object, :save_succeeded?)
+ end
+ end
+end
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/response.rb b/vendor/plugins/make_resourceful/lib/resourceful/response.rb
new file mode 100644
index 0000000..f5f0b5c
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/response.rb
@@ -0,0 +1,33 @@
+module Resourceful
+ # This is the class of the object passed to the Builder#response_for method.
+ # It shouldn't be used by users.
+ #
+ # The Response collects format procs
+ # and returns them with the format method,
+ # in the order they were given.
+ # For example:
+ #
+ # response.html { redirect_to '/' }
+ # response.xml { render :xml => current_object.to_xml }
+ # response.js
+ # response.formats #=> [[:html, #<Proc>], [:xml, #<Proc>], [:js, #<Proc>]]
+ #
+ # Note that the <tt>:js</tt> response is the empty proc -
+ # the same as <tt>proc {}</tt>.
+ class Response # :nodoc:
+ # Returns a list of pairs of formats and procs
+ # representing the formats passed to the response object.
+ # See class description.
+ attr :formats
+
+ # Returns a new Response with no format data.
+ def initialize
+ @formats = []
+ end
+
+ # Used to dispatch the individual format methods.
+ def method_missing(name, &block)
+ @formats.push([name, block || proc {}]) unless @formats.any? {|n,b| n == name}
+ end
+ end
+end
diff --git a/vendor/plugins/make_resourceful/lib/resourceful/serialize.rb b/vendor/plugins/make_resourceful/lib/resourceful/serialize.rb
new file mode 100644
index 0000000..08b0893
--- /dev/null
+++ b/vendor/plugins/make_resourceful/lib/resourceful/serialize.rb
@@ -0,0 +1,181 @@
+require 'resourceful/builder'
+
+module Resourceful
+ # This module contains mixin modules
+ # used to implement the object serialization
+ # used for the Builder#publish method.
+ # They can also be used to get serialized representations of objects
+ # in other contexts.
+ #
+ # Serialization makes use of duck typing.
+ # Each class that can be serialized
+ # (just Array and ActiveRecord::Base by default)
+ # implements the +serialize+ and +to_serializable+ methods.
+ # These methods are implemented differently by the different classes,
+ # but the semantics of the implementations are consistent,
+ # so they can be used consistently.
+ #
+ # +to_serializable+ returns an object that can be directly serialized
+ # with a call to +to_xml+, +to_yaml+, or +to_json+.
+ # This object is either a hash or an array,
+ # and all the elements are either values, like strings and integers,
+ # or other serializable objects.
+ # This is useful for getting a model into a simple data structure format.
+ # The +attributes+ argument uses the same semantics
+ # as the <tt>:attributes</tt> option for Builder#publish.
+ # For example:
+ #
+ # c = Cake.new(:flavor => 'chocolate', :text => 'Happy birthday, Chris!')
+ # c.recipient = User.new(:name => 'Chris', :password => 'not very secure')
+ # c.to_serializable [
+ # :flavor, :text,
+ # :recipient => :name
+ # ]
+ #
+ # This would return the Ruby hash
+ #
+ # { :flavor => 'chocolate', :text => 'Happy birthday, Chris!',
+ # :user => {:name => 'Chris'} }
+ #
+ # +serialize+ takes a format (<tt>:xml</tt>, <tt>:yaml</tt>, or <tt>:json</tt> - see New Formats below)
+ # and a hash of options.
+ # The only option currently recognized is <tt>:attributes</tt>,
+ # which has the same semantics
+ # as the <tt>:attributes</tt> option for Builder#publish.
+ # +serialize+ returns a string containing the target
+ # serialized in the given format.
+ # For example:
+ #
+ # c = CandyBag.new(:title => 'jellybag')
+ # c.candies << Candy.new(:type => 'jellybean', :flavor => 'root beer')
+ # c.candies << Candy.new(:type => 'jellybean', :flavor => 'pear')
+ # c.candies << Candy.new(:type => 'licorice', :flavor => 'anisey')
+ # c.serialize :xml, :attributes => [:title, {:candies => [:type, :flavor]}]
+ #
+ # This would return a Ruby string containing
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <candy-bag>
+ # <title>jellybag</title>
+ # <candies>
+ # <candy>
+ # <type>jellybean</type>
+ # <flavor>root beer</flavor>
+ # </candy>
+ # <candy>
+ # <type>jellybean</type>
+ # <flavor>pear</flavor>
+ # </candy>
+ # <candy>
+ # <type>licorice</type>
+ # <flavor>anisey</flavor>
+ # </candy>
+ # </candies>
+ # </candy-bag>
+ #
+ module Serialize
+
+ # Takes an attributes option in the form passed to Builder#publish
+ # and returns a hash (or nil, if attributes is nil)
+ # containing the same data,
+ # but in a more consistent format.
+ # All keys are converted to symbols,
+ # and all lists are converted to hashes.
+ # For example:
+ #
+ # Resourceful::Serialize.normalize_attributes([:foo, :bar, {"baz" => ["boom"]}])
+ # #=> {"baz"=>["boom"], :foo=>nil, :bar=>nil}
+ #
+ def self.normalize_attributes(attributes) # :nodoc:
+ return nil if attributes.nil?
+ return {attributes.to_sym => nil} if String === attributes
+ return {attributes => nil} if !attributes.respond_to?(:inject)
+
+ attributes.inject({}) do |hash, attr|
+ if Array === attr
+ hash[attr[0]] = attr[1]
+ hash
+ else
+ hash.merge normalize_attributes(attr)
+ end
+ end
+ end
+
+ # This module contains the definitions of +serialize+ and +to_serializable+
+ # that are included in ActiveRecord::Base.
+ module Model
+ # :call-seq:
+ # serialize format, options = {}, :attributes => [ ... ]
+ #
+ # See the module documentation for Serialize for details.
+ def serialize(format, options)
+ raise "Must specify :attributes option" unless options[:attributes]
+ hash = self.to_serializable(options[:attributes])
+ root = self.class.to_s.underscore
+ if format == :xml
+ hash.send("to_#{format}", :root => root)
+ else
+ {root => hash}.send("to_#{format}")
+ end
+ end
+
+ # See the module documentation for Serialize for details.
+ def to_serializable(attributes)
+ raise "Must specify attributes for #{self.inspect}.to_serializable" if attributes.nil?
+
+ Serialize.normalize_attributes(attributes).inject({}) do |hash, (key, value)|
+ hash[key.to_s] = attr_hash_value(self.send(key), value)
+ hash
+ end
+ end
+
+ private
+
+ # Given an attribute value
+ # and a normalized (see above) attribute hash,
+ # returns the serializable form of that attribute.
+ def attr_hash_value(attr, sub_attributes)
+ if attr.respond_to?(:to_serializable)
+ attr.to_serializable(sub_attributes)
+ else
+ attr
+ end
+ end
+ end
+
+ # This module contains the definitions of +serialize+ and +to_serializable+
+ # that are included in ActiveRecord::Base.
+ module Array
+ # :call-seq:
+ # serialize format, options = {}, :attributes => [ ... ]
+ #
+ # See the module documentation for Serialize for details.
+ def serialize(format, options)
+ raise "Not all elements respond to to_serializable" unless all? { |e| e.respond_to? :to_serializable }
+ raise "Must specify :attributes option" unless options[:attributes]
+
+ serialized = map { |e| e.to_serializable(options[:attributes]) }
+ root = first.class.to_s.pluralize.underscore
+
+ if format == :xml
+ serialized.send("to_#{format}", :root => root)
+ else
+ {root => serialized}.send("to_#{format}")
+ end
+ end
+
+ # See the module documentation for Serialize for details.
+ def to_serializable(attributes)
+ if first.respond_to?(:to_serializable)
+ attributes = Serialize.normalize_attributes(attributes)
+ map { |e| e.to_serializable(attributes) }
+ else
+ self
+ end
+ end
+ end
+ end
+end
+
+class ActiveRecord::Base; include Resourceful::Serialize::Model; end
+class Array; include Resourceful::Serialize::Array; end
diff --git a/vendor/plugins/make_resourceful/spec/accessors_spec.rb b/vendor/plugins/make_resourceful/spec/accessors_spec.rb
new file mode 100644
index 0000000..aa0f192
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/accessors_spec.rb
@@ -0,0 +1,473 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe Resourceful::Default::Accessors, "#current_objects" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @objects = stub_list 5, 'object'
+ @model = stub
+ @controller.stubs(:current_model).returns(@model)
+ end
+
+ it "should look up all objects in the current model" do
+ @model.expects(:find).with(:all).returns(@objects)
+ @controller.current_objects.should == @objects
+ end
+
+ it "should cache the result, so subsequent calls won't run multiple queries" do
+ @model.expects(:find).once.returns(@objects)
+ @controller.current_objects
+ @controller.current_objects
+ end
+
+ it "shouldn't run a query if @current_objects is set" do
+ @controller.instance_variable_set('@current_objects', @objects)
+ @model.expects(:find).never
+ @controller.current_objects.should == @objects
+ end
+end
+
+describe Resourceful::Default::Accessors, "#load_objects" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @objects = stub_list 5, 'object'
+ @controller.stubs(:current_objects).returns(@objects)
+ @controller.stubs(:instance_variable_name).returns("posts")
+ end
+
+ it "should set the current instance variable to the object collection" do
+ @controller.load_objects
+ @controller.instance_variable_get('@posts').should == @objects
+ end
+end
+
+describe Resourceful::Default::Accessors, "#current_object on a plural controller" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:plural?).returns(true)
+ @controller.stubs(:params).returns(:id => "12")
+
+ @object = stub
+ @model = stub
+ @controller.stubs(:current_model).returns(@model)
+ end
+
+ it "should look up the object specified by the :id parameter in the current model" do
+ @model.expects(:find).with('12').returns(@object)
+ @controller.current_object.should == @object
+ end
+
+ it "should cache the result, so subsequent calls won't run multiple queries" do
+ @model.expects(:find).once.returns(@object)
+ @controller.current_object
+ @controller.current_object
+ end
+
+ it "shouldn't run a query if @current_object is set" do
+ @controller.instance_variable_set('@current_object', @object)
+ @model.expects(:find).never
+ @controller.current_object.should == @object
+ end
+end
+
+describe Resourceful::Default::Accessors, "#current_object on a singular controller" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:plural?).returns(false)
+ @controller.stubs(:instance_variable_name).returns("post")
+
+ @parent = stub('parent')
+ @controller.stubs(:parent_object).returns(@parent)
+ @controller.stubs(:parent?).returns(true)
+
+ @object = stub
+ end
+
+ it "should look up the instance object of the parent object" do
+ @parent.expects(:post).returns(@object)
+ @controller.current_object.should == @object
+ end
+end
+
+describe Resourceful::Default::Accessors, "#load_object" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @object = stub
+ @controller.stubs(:current_object).returns(@object)
+ @controller.stubs(:instance_variable_name).returns("posts")
+ end
+
+ it "should set the current singular instance variable to the current object" do
+ @controller.load_object
+ @controller.instance_variable_get('@post').should == @object
+ end
+end
+
+describe Resourceful::Default::Accessors, "#build_object with a #build-able model" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @params = {:name => "Bob", :password => "hideously insecure"}
+ @controller.stubs(:object_parameters).returns(@params)
+
+ @object = stub
+ @model = stub
+ @controller.stubs(:current_model).returns(@model)
+
+ @model.stubs(:build).returns(@object)
+ end
+
+ it "should return a new object built with current_model from the object parameters" do
+ @model.expects(:build).with(@params).returns(@object)
+ @controller.build_object.should == @object
+ end
+
+ it "should make current_object return the newly built object" do
+ @controller.build_object
+ @controller.current_object.should == @object
+ end
+end
+
+describe Resourceful::Default::Accessors, "#build_object with a non-#build-able model" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @params = {:name => "Bob", :password => "hideously insecure"}
+ @controller.stubs(:object_parameters).returns(@params)
+
+ @controller.stubs(:singular?).returns(false)
+ @controller.stubs(:parent?).returns(false)
+
+ @object = stub
+ @model = stub
+ @controller.stubs(:current_model).returns(@model)
+
+ @model.stubs(:new).returns(@object)
+ end
+
+ it "should return a new instance of the current_model built with the object parameters" do
+ @model.expects(:new).with(@params).returns(@object)
+ @controller.build_object.should == @object
+ end
+end
+
+describe Resourceful::Default::Accessors, "#current_model_name" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:controller_name).returns("funky_posts")
+ end
+
+ it "should return the controller's name, singularized and camel-cased" do
+ @controller.current_model_name.should == "FunkyPost"
+ end
+end
+
+describe Resourceful::Default::Accessors, "#namespaces" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @kontroller.stubs(:name).returns("FunkyStuff::Admin::Posts")
+ end
+
+ it "should return an array of underscored symbols representing the namespaces of the controller class" do
+ @controller.namespaces.should == [:funky_stuff, :admin]
+ end
+
+ it "should cache the result, so subsequent calls won't run multiple computations" do
+ @kontroller.expects(:name).once.returns("Posts")
+ @controller.namespaces
+ @controller.namespaces
+ end
+end
+
+describe Resourceful::Default::Accessors, "#instance_variable_name" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:controller_name).returns("posts")
+ end
+
+ it "should return controller_name" do
+ @controller.instance_variable_name == "posts"
+ end
+end
+
+describe Resourceful::Default::Accessors, "#current_model for a singular controller" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ stub_const :Post
+ @controller.stubs(:singular?).returns(true)
+ @controller.stubs(:current_model_name).returns("Post")
+
+ @parent = stub('parent')
+ @controller.stubs(:parent_object).returns(@parent)
+ @controller.stubs(:parent?).returns(true)
+ end
+
+ it "should return the constant named by current_model_name" do
+ @controller.current_model.should == Post
+ end
+end
+
+describe Resourceful::Default::Accessors, "#current_model for a plural controller with no parent" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ stub_const :Post
+ @controller.stubs(:singular?).returns(false)
+ @controller.stubs(:current_model_name).returns("Post")
+ @controller.stubs(:parent?).returns(false)
+ end
+
+ it "should return the constant named by current_model_name" do
+ @controller.current_model.should == Post
+ end
+end
+
+describe Resourceful::Default::Accessors, "#object_parameters" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @params = {"crazy_user" => {:name => "Hampton", :location => "Canada"}}
+ @controller.stubs(:params).returns(@params)
+ @controller.stubs(:current_model_name).returns("CrazyUser")
+ end
+
+ it "should return the element of the params hash with the name of the model" do
+ @controller.object_parameters.should == @params["crazy_user"]
+ end
+end
+
+describe Resourceful::Default::Accessors, " with two parent classes set on the controller class and one parent parameter supplied" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @parents = %w{post comment}
+ @models = @parents.map(&:camelize).map(&method(:stub_const))
+ @kontroller.write_inheritable_attribute(:parents, @parents)
+ @controller.stubs(:singular?).returns(false)
+ @controller.stubs(:instance_variable_name).returns('lines')
+
+ @params = HashWithIndifferentAccess.new :post_id => 12
+ @controller.stubs(:params).returns(@params)
+
+ @post = stub('Post')
+ Post.stubs(:find).returns(@post)
+
+ @model = stub
+ end
+
+ it "should return true for #parent?" do
+ @controller.parent?.should be_true
+ end
+
+ it "should return the string names of all the parents for #parent_names" do
+ @controller.parent_names.should == @parents
+ end
+
+ it "should return the string name of the current parent for #parent_name" do
+ @controller.parent_name.should == 'post'
+ end
+
+ it "should return the model class for #parent_model" do
+ @controller.parent_model.should == Post
+ end
+
+ it "should return the parent object for #parent_object" do
+ Post.expects(:find).with(12).returns(@post)
+ @controller.parent_object.should == @post
+ end
+
+ it "should cache the value of #parent_object so multiple calls won't cause multiple queries" do
+ Post.expects(:find).returns(@post).once
+ @controller.parent_object
+ @controller.parent_object
+ end
+
+ it "should bind the parent object its proper instance variable" do
+ @controller.load_parent_object
+ @controller.instance_variable_get('@post').should == @post
+ end
+
+ it "should return the parent-scoped model for #current_model" do
+ @post.stubs(:lines).returns(@model)
+ @controller.current_model.should == @model
+ end
+
+ it "should return true for #ensure_parent_exists" do
+ @controller.expects(:render).never
+ @controller.ensure_parent_exists.should be_true
+ end
+end
+
+describe Resourceful::Default::Accessors, " with two parent classes set on the controller class but no parent parameter supplied" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @parents = %w{post comment}
+ @models = @parents.map(&:camelize).map(&method(:stub_const))
+ @kontroller.write_inheritable_attribute(:parents, @parents)
+ @controller.stubs(:params).returns({})
+ @controller.stubs(:controller_name).returns('line')
+ stub_const('Line')
+ end
+
+ it "should return false for #parent?" do
+ @controller.parent?.should be_false
+ end
+
+ it "should return nil for #parent_name" do
+ @controller.parent_name.should be_nil
+ end
+
+ it "should return the unscoped model for #current_model" do
+ @controller.current_model.should == Line
+ end
+
+ it "should return false and render a 422 error for #ensure_parent_exists" do
+ @controller.expects(:render).with(has_entry(:status, 422))
+ @controller.ensure_parent_exists.should be_false
+ end
+end
+
+describe Resourceful::Default::Accessors, " with no parents" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:parents).returns([])
+ @controller.stubs(:current_model_name).returns('Line')
+ stub_const 'Line'
+ end
+
+ it "should return false for #parent?" do
+ @controller.parent?.should be_false
+ end
+
+ it "should return nil for #parent_name" do
+ @controller.parent_name.should be_nil
+ end
+
+ it "should return the unscoped model for #current_model" do
+ @controller.current_model.should == Line
+ end
+end
+
+describe Resourceful::Default::Accessors, " for a singular controller with a parent" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:singular?).returns(true)
+
+ @model = stub_model('Thing')
+ @model.send(:attr_accessor, :person_id)
+ @controller.stubs(:current_model).returns(@model)
+
+ @person = stub_model('Person')
+ @person.stubs(:id).returns 42
+ @controller.stubs(:parent_object).returns(@person)
+ @controller.stubs(:parent_name).returns('person')
+ @controller.stubs(:parent?).returns(true)
+
+ @controller.stubs(:object_parameters).returns :thinginess => 12, :bacon => true
+ end
+
+ it "should set assign the parent's id to a newly built object" do
+ thing = @controller.build_object
+ thing.thinginess.should == 12
+ thing.person_id.should == @person.id
+ end
+end
+
+describe Resourceful::Default::Accessors, "#save_succeeded!" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.save_succeeded!
+ end
+
+ it "should make #save_succeeded? return true" do
+ @controller.save_succeeded?.should be_true
+ end
+end
+
+describe Resourceful::Default::Accessors, "#save_failed!" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.save_failed!
+ end
+
+ it "should make #save_succeeded? return false" do
+ @controller.save_succeeded?.should be_false
+ end
+end
+
+describe Resourceful::Default::Accessors, " for a plural action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:params).returns :action => "index"
+ end
+
+ it "should know it's a plural action" do
+ @controller.should be_a_plural_action
+ end
+
+ it "should know it's not a singular action" do
+ @controller.should_not be_a_singular_action
+ end
+end
+
+describe Resourceful::Default::Accessors, " for a singular action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:params).returns :action => "show"
+ end
+
+ it "should know it's not a plural action" do
+ @controller.should_not be_a_plural_action
+ end
+
+ it "should know it's a singular action" do
+ @controller.should be_a_singular_action
+ end
+end
+
+describe Resourceful::Default::Accessors, " for a singular controller" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:instance_variable_name).returns "post"
+ end
+
+ it "should know it's not plural" do
+ @controller.should_not be_plural
+ end
+
+ it "should know it's singular" do
+ @controller.should be_singular
+ end
+end
+
+describe Resourceful::Default::Accessors, " for a plural controller" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Accessors
+ @controller.stubs(:instance_variable_name).returns "posts"
+ end
+
+ it "should know it's plural" do
+ @controller.should be_plural
+ end
+
+ it "should know it's not singular" do
+ @controller.should_not be_singular
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/actions_spec.rb b/vendor/plugins/make_resourceful/spec/actions_spec.rb
new file mode 100644
index 0000000..f0bcf15
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/actions_spec.rb
@@ -0,0 +1,283 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe Resourceful::Default::Actions, " index action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:load_objects, :before, :response_for].each(&@controller.method(:stubs))
+ end
+
+ after(:each) { @controller.index }
+
+ it "should load the object collection" do
+ @controller.expects(:load_objects)
+ end
+
+ it "should call the before :index callback" do
+ @controller.expects(:before).with(:index)
+ end
+
+ it "should run the response for index" do
+ @controller.expects(:response_for).with(:index)
+ end
+end
+
+describe Resourceful::Default::Actions, " show action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:load_object, :before, :response_for].each(&@controller.method(:stubs))
+ end
+
+ after(:each) { @controller.show }
+
+ it "should load the instance object" do
+ @controller.expects(:load_object)
+ end
+
+ it "should call the before :show callback" do
+ @controller.expects(:before).with(:show)
+ end
+
+ it "should run the response for show" do
+ @controller.expects(:response_for).with(:show)
+ end
+
+ it "should run the response for show failing if an exception is raised" do
+ @controller.stubs(:load_object).raises("Oh no!")
+ @controller.expects(:response_for).with(:show_fails)
+ end
+end
+
+describe Resourceful::Default::Actions, " successful create action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:build_object, :load_object, :before, :after,
+ :save_succeeded!, :response_for].each(&@controller.method(:stubs))
+ @object = stub :save => true
+ @controller.stubs(:current_object).returns(@object)
+ end
+
+ after(:each) { @controller.create }
+
+ it "should build the object from the POSTed parameters" do
+ @controller.expects(:build_object)
+ end
+
+ it "should load the instance object" do
+ @controller.expects(:load_object)
+ end
+
+ it "should call the before :create callback" do
+ @controller.expects(:before).with(:create)
+ end
+
+ it "should try to save the object" do
+ @object.expects(:save).returns(true)
+ end
+
+ it "should record the successful save" do
+ @controller.expects(:save_succeeded!)
+ end
+
+ it "should call the after :create callback" do
+ @controller.expects(:after).with(:create)
+ end
+
+ it "should run the response for create" do
+ @controller.expects(:response_for).with(:create)
+ end
+end
+
+describe Resourceful::Default::Actions, " unsuccessful create action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:build_object, :load_object, :before, :after,
+ :save_failed!, :response_for].each(&@controller.method(:stubs))
+ @object = stub :save => false
+ @controller.stubs(:current_object).returns(@object)
+ end
+
+ after(:each) { @controller.create }
+
+ it "should record the unsuccessful save" do
+ @controller.expects(:save_failed!)
+ end
+
+ it "should call the after :create_fails callback" do
+ @controller.expects(:after).with(:create_fails)
+ end
+
+ it "should run the response for create failing" do
+ @controller.expects(:response_for).with(:create_fails)
+ end
+end
+
+describe Resourceful::Default::Actions, " successful update action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:load_object, :before, :after, :object_parameters,
+ :save_succeeded!, :response_for].each(&@controller.method(:stubs))
+ @object = stub :update_attributes => true
+ @controller.stubs(:current_object).returns(@object)
+ end
+
+ after(:each) { @controller.update }
+
+ it "should load the instance object" do
+ @controller.expects(:load_object)
+ end
+
+ it "should call the before :update callback" do
+ @controller.expects(:before).with(:update)
+ end
+
+ it "should try to update the object with the POSTed attributes" do
+ @controller.expects(:object_parameters).returns(:params => "stuff")
+ @object.expects(:update_attributes).with(:params => "stuff").returns(true)
+ end
+
+ it "should record the successful save" do
+ @controller.expects(:save_succeeded!)
+ end
+
+ it "should call the after :update callback" do
+ @controller.expects(:after).with(:update)
+ end
+
+ it "should run the response for update" do
+ @controller.expects(:response_for).with(:update)
+ end
+end
+
+describe Resourceful::Default::Actions, " unsuccessful update action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:load_object, :before, :after, :object_parameters,
+ :save_failed!, :response_for].each(&@controller.method(:stubs))
+ @object = stub :update_attributes => false
+ @controller.stubs(:current_object).returns(@object)
+ end
+
+ after(:each) { @controller.update }
+
+ it "should record the unsuccessful save" do
+ @controller.expects(:save_failed!)
+ end
+
+ it "should call the after :update_fails callback" do
+ @controller.expects(:after).with(:update_fails)
+ end
+
+ it "should run the response for update failing" do
+ @controller.expects(:response_for).with(:update_fails)
+ end
+end
+
+describe Resourceful::Default::Actions, " new action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:build_object, :load_object,
+ :before, :response_for].each(&@controller.method(:stubs))
+ end
+
+ after(:each) { @controller.new }
+
+ it "should build the object from the POSTed parameters" do
+ @controller.expects(:build_object)
+ end
+
+ it "should load the instance object" do
+ @controller.expects(:load_object)
+ end
+
+ it "should call the before :new callback" do
+ @controller.expects(:before).with(:new)
+ end
+
+ it "should run the response for new" do
+ @controller.expects(:response_for).with(:new)
+ end
+end
+
+describe Resourceful::Default::Actions, " edit action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:load_object, :before, :response_for].each(&@controller.method(:stubs))
+ end
+
+ after(:each) { @controller.edit }
+
+ it "should load the instance object" do
+ @controller.expects(:load_object)
+ end
+
+ it "should call the before :edit callback" do
+ @controller.expects(:before).with(:edit)
+ end
+
+ it "should run the response for edit" do
+ @controller.expects(:response_for).with(:edit)
+ end
+end
+
+describe Resourceful::Default::Actions, " successful destroy action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:load_object, :before,
+ :after, :response_for].each(&@controller.method(:stubs))
+ @object = stub :destroy => true
+ @controller.stubs(:current_object).returns(@object)
+ end
+
+ after(:each) { @controller.destroy }
+
+ it "should load the instance object" do
+ @controller.expects(:load_object)
+ end
+
+ it "should call the before :destroy callback" do
+ @controller.expects(:before).with(:destroy)
+ end
+
+ it "should try to destroy the object" do
+ @object.expects(:destroy).returns(true)
+ end
+
+ it "should call the after :destroy callback" do
+ @controller.expects(:after).with(:destroy)
+ end
+
+ it "should run the response for destroy" do
+ @controller.expects(:response_for).with(:destroy)
+ end
+end
+
+describe Resourceful::Default::Actions, " unsuccessful destroy action" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Actions
+ [:load_object, :before,
+ :after, :response_for].each(&@controller.method(:stubs))
+ @object = stub :destroy => false
+ @controller.stubs(:current_object).returns(@object)
+ end
+
+ after(:each) { @controller.destroy }
+
+ it "should call the after :destroy_fails callback" do
+ @controller.expects(:after).with(:destroy_fails)
+ end
+
+ it "should run the response for destroy failing" do
+ @controller.expects(:response_for).with(:destroy_fails)
+ end
+end
+
diff --git a/vendor/plugins/make_resourceful/spec/base_spec.rb b/vendor/plugins/make_resourceful/spec/base_spec.rb
new file mode 100644
index 0000000..f0675db
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/base_spec.rb
@@ -0,0 +1,12 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe Resourceful::Base, ".made_resourceful" do
+ before(:all) { @original_blocks = Resourceful::Base.made_resourceful.dup }
+ before(:each) { Resourceful::Base.made_resourceful.replace [] }
+ after(:all) { Resourceful::Base.made_resourceful.replace @original_blocks }
+
+ it "should store blocks when called with blocks and return them when called without a block" do
+ 5.times { Resourceful::Base.made_resourceful(&should_be_called) }
+ Resourceful::Base.made_resourceful.each(&:call)
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/builder_spec.rb b/vendor/plugins/make_resourceful/spec/builder_spec.rb
new file mode 100644
index 0000000..439dd5d
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/builder_spec.rb
@@ -0,0 +1,309 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe Resourceful::Builder, " applied without any modification" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ end
+
+ it "should remove all resourceful actions" do
+ @kontroller.expects(:send).with do |name, action_module|
+ name == :include && (action_module.instance_methods & Resourceful::ACTIONS.map(&:to_s)).empty?
+ end
+ @builder.apply
+ end
+
+ it "shouldn't un-hide any actions" do
+ @builder.apply
+ @kontroller.hidden_actions.should == Resourceful::ACTIONS
+ end
+
+ it "shouldn't set any callbacks" do
+ @builder.apply
+ callbacks.should == {:before => {}, :after => {}}
+ end
+
+ it "shouldn't set any responses" do
+ @builder.apply
+ responses.should be_empty
+ end
+
+ it "shouldn't set any parents" do
+ @builder.apply
+ parents.should be_empty
+ end
+
+ it "should set the controller as made_resourceful" do
+ @builder.apply
+ @kontroller.read_inheritable_attribute(:made_resourceful).should be_true
+ end
+
+ it "should set load_parent_object as a before_filter for no actions" do
+ @kontroller.expects(:before_filter).with(:load_parent_object, :only => [])
+ @builder.apply
+ end
+end
+
+describe Resourceful::Builder, " with some actions set" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ @actions = [:show, :index, :new, :create]
+ @builder.actions *@actions
+ end
+
+ it "should include the given actions" do
+ @kontroller.expects(:send).with do |name, action_module|
+ name == :include && (action_module.instance_methods & Resourceful::ACTIONS.map(&:to_s)).sort ==
+ @actions.map(&:to_s).sort
+ end
+ @builder.apply
+ end
+
+ it "should un-hide the given actions" do
+ @builder.apply
+ (@kontroller.hidden_actions & @actions).should be_empty
+ end
+
+ it "should set load_parent_object as a before_filter for the given actions" do
+ @kontroller.expects(:before_filter).with(:load_parent_object, :only => [:show, :index, :new, :create])
+ @builder.apply
+ end
+end
+
+describe Resourceful::Builder, " with all actions set for a plural controller" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ @kontroller.class_eval { def plural?; true; end }
+ create_builder
+ @builder.actions :all
+ end
+
+ it "should include all actions" do
+ @kontroller.expects(:send).with do |name, action_module|
+ name == :include && (action_module.instance_methods & Resourceful::ACTIONS.map(&:to_s)).sort ==
+ Resourceful::ACTIONS.map(&:to_s).sort
+ end
+ @builder.apply
+ end
+end
+
+describe Resourceful::Builder, " with all actions set for a singular controller" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ @kontroller.class_eval { def plural?; false; end }
+ create_builder
+ @builder.actions :all
+ end
+
+ it "should include all singular actions" do
+ @kontroller.expects(:send).with do |name, action_module|
+ name == :include && (action_module.instance_methods & Resourceful::ACTIONS.map(&:to_s)).sort ==
+ Resourceful::SINGULAR_ACTIONS.map(&:to_s).sort
+ end
+ @builder.apply
+ end
+end
+
+describe Resourceful::Builder, " with several before and after callbacks set" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ @builder.before(:create, :update, 'destroy', &(should_be_called { times(3) }))
+ @builder.after('index', &should_be_called)
+ @builder.after(:update, &should_be_called)
+ @builder.apply
+ end
+
+ it "should save the callbacks as the :resourceful_callbacks inheritable_attribute" do
+ callbacks[:before][:create].call
+ callbacks[:before][:update].call
+ callbacks[:before][:destroy].call
+ callbacks[:after][:index].call
+ callbacks[:after][:update].call
+ end
+end
+
+describe Resourceful::Builder, " with responses set for several formats" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ @builder.response_for('create') do |f|
+ f.html(&should_be_called)
+ f.js(&should_be_called)
+ f.yaml(&should_be_called)
+ f.xml(&should_be_called)
+ f.txt(&should_be_called)
+ end
+ @builder.response_for(:remove_failed, 'update') do |f|
+ f.yaml(&(should_be_called { times(2) }))
+ f.png(&(should_be_called { times(2) }))
+ end
+ @builder.apply
+ end
+
+ it "should save the responses as the :resourceful_responses inheritable_attribute" do
+ responses[:create].map(&:first).should == [:html, :js, :yaml, :xml, :txt]
+ responses[:create].map(&:last).each(&:call)
+
+ responses[:remove_failed].map(&:first).should == [:yaml, :png]
+ responses[:remove_failed].map(&:last).each(&:call)
+
+ responses[:update].map(&:first).should == [:yaml, :png]
+ responses[:update].map(&:last).each(&:call)
+ end
+end
+
+describe Resourceful::Builder, " with a response set for the default format" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ @builder.response_for('index', &should_be_called)
+ @builder.apply
+ end
+
+ it "should save the response as a response for HTML in the :resourceful_responses inheritable_attribute" do
+ responses[:index].map(&:first).should == [:html]
+ responses[:index].map(&:last).each(&:call)
+ end
+end
+
+describe Resourceful::Builder, " with a response set for no actions" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ end
+
+ it "should raise an error" do
+ lambda { @builder.response_for {} }.should raise_error("Must specify one or more actions for response_for.")
+ end
+end
+
+describe Resourceful::Builder, " publishing without an attributes hash" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ end
+
+ it "should raise an error" do
+ proc { @builder.publish :xml, :yaml }.should raise_error("Must specify :attributes option")
+ end
+end
+
+describe Resourceful::Builder, " publishing several formats" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+
+ @model = stub_model("Thing")
+ @kontroller.stubs(:current_object).returns(@model)
+
+ @models = (1..5).map { stub_model("Thing") }
+ @kontroller.stubs(:current_objects).returns(@models)
+
+ @builder.publish :yaml, :json, 'xml', :additional => 'option', :attributes => [:name, :stuff]
+ @builder.apply
+ end
+
+ it "should add a list of types as responses for index and show" do
+ responses[:index].map(&:first).should == [:yaml, :json, :xml]
+ responses[:show].map(&:first).should == [:yaml, :json, :xml]
+ end
+
+ it "should respond by rendering the serialized model with the proper type, passing along un-recognized options" do
+ @model.expects(:serialize).with(:yaml, :additional => 'option', :attributes => [:name, :stuff]).returns('serialized')
+ @kontroller.expects(:render).with(:text => 'serialized')
+ @kontroller.instance_eval(&responses[:index].find { |type, _| type == :yaml }[1])
+ end
+
+ it "should respond render XML and JSON with the proper action" do
+ @model.expects(:serialize).with(:xml, :additional => 'option', :attributes => [:name, :stuff]).returns('XML serialized')
+ @model.expects(:serialize).with(:json, :additional => 'option', :attributes => [:name, :stuff]).returns('JSON serialized')
+ @kontroller.expects(:render).with(:xml => 'XML serialized')
+ @kontroller.expects(:render).with(:json => 'JSON serialized')
+
+ @kontroller.instance_eval(&responses[:index].find { |type, _| type == :xml }[1])
+ @kontroller.instance_eval(&responses[:index].find { |type, _| type == :json }[1])
+ end
+
+ it "should render current_objects if the action is plural" do
+ @kontroller.stubs(:plural_action?).returns(true)
+ @models.expects(:serialize).with(:yaml, :additional => 'option', :attributes => [:name, :stuff]).returns('serialized')
+ @kontroller.expects(:render).with(:text => 'serialized')
+ @kontroller.instance_eval(&responses[:index].find { |type, _| type == :yaml }[1])
+ end
+end
+
+describe Resourceful::Builder, " publishing only to #show" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+
+ @model = stub_model("Thing")
+ @kontroller.stubs(:current_object).returns(@model)
+
+ @builder.publish :json, :yaml, :only => :show, :attributes => [:name, :stuff]
+ @builder.apply
+ end
+
+ it "should add responses for show" do
+ responses[:show].map(&:first).should == [:json, :yaml]
+ end
+
+ it "shouldn't add responses for index" do
+ responses[:index].should be_nil
+ end
+
+ it "shouldn't pass the :only option to the serialize call" do
+ @model.expects(:serialize).with(:yaml, :attributes => [:name, :stuff])
+ @kontroller.stubs(:render)
+ @kontroller.instance_eval(&responses[:show].find { |type, _| type == :yaml }[1])
+ end
+end
+
+describe Resourceful::Builder, " publishing in addition to other responses" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+
+ @builder.response_for(:index) {}
+ @builder.publish :json, :yaml, :attributes => [:name, :stuff]
+ @builder.response_for :show do |f|
+ f.html {}
+ f.js {}
+ end
+ @builder.apply
+ end
+
+ it "should add published responses in addition to pre-existing ones" do
+ responses[:show].map(&:first).should == [:html, :js, :json, :yaml]
+ responses[:index].map(&:first).should == [:html, :json, :yaml]
+ end
+end
+
+describe Resourceful::Builder, " belonging to several parents" do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+
+ @builder.belongs_to :post, :blat, :stang
+ @builder.apply
+ end
+
+ it "should save the parents as the :parents inheritable_attribute" do
+ parents.should == ['post', 'blat', 'stang']
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/callbacks_spec.rb b/vendor/plugins/make_resourceful/spec/callbacks_spec.rb
new file mode 100644
index 0000000..8ee6f88
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/callbacks_spec.rb
@@ -0,0 +1,72 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe Resourceful::Default::Callbacks, " with a few callbacks" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Callbacks
+ callbacks[:before] = {:create => proc { "awesome!" }}
+ callbacks[:after] = {:index => proc { @var }}
+ @controller.instance_variable_set('@var', 'value')
+ end
+
+ it "should fire the :before callback with the given name when #before is called" do
+ @controller.before(:create).should == "awesome!"
+ end
+
+ it "should fire the :after callback with the given name when #before is called" do
+ @controller.after("index").should == "value"
+ end
+end
+
+describe Resourceful::Default::Callbacks, " with a few responses" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Callbacks
+ responses[:create_failed] = [[:html, nil], [:js, nil]]
+ responses[:create] = [[:html, proc { "create html" }], [:xml, proc { @xml }]]
+ @controller.instance_variable_set('@xml', 'create XML')
+ @response = Resourceful::Response.new
+ end
+
+ it "should respond to each format with a call to the given block when #response_for is called" do
+ @controller.expects(:respond_to).yields(@response)
+ @controller.response_for(:create_failed)
+ @response.formats[0][0].should == :html
+ @response.formats[0][1].call.should be_nil
+
+ @response.formats[1][0].should == :js
+ @response.formats[1][1].call.should be_nil
+ end
+
+ it "should properly scope blocks when #response_for is called" do
+ @controller.expects(:respond_to).yields(@response)
+ @controller.response_for(:create)
+ @response.formats[0][0].should == :html
+ @response.formats[0][1].call.should == "create html"
+
+ @response.formats[1][0].should == :xml
+
+ # This value comes from the instance variable in @controller.
+ # Having it be "create XML" ensures that the block was properly scoped.
+ @response.formats[1][1].call.should == "create XML"
+ end
+end
+
+describe Resourceful::Default::Callbacks, "#scope" do
+ include ControllerMocks
+ before(:each) { mock_controller Resourceful::Default::Callbacks }
+
+ it "should re-bind the block to the controller's context" do
+ block = proc { @var }
+ @controller.instance_variable_set('@var', 'value')
+
+ block.call.should == nil
+ @controller.scope(block).call.should == 'value'
+ end
+
+ it "should make the block empty if it's passed in as nil" do
+ @controller.scope(nil).call.should == nil
+ end
+end
+
+
diff --git a/vendor/plugins/make_resourceful/spec/integration_spec.rb b/vendor/plugins/make_resourceful/spec/integration_spec.rb
new file mode 100644
index 0000000..4ab4c36
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/integration_spec.rb
@@ -0,0 +1,396 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe "ThingsController", "with all the resourceful actions", :type => :integration do
+ include RailsMocks
+ #inherit Test::Unit::TestCase
+ before :each do
+ mock_resourceful do
+ actions :all
+ end
+ @objects = stub_list(5, 'Thing') do |t|
+ [:destroy, :save, :update_attributes].each { |m| t.stubs(m).returns(true) }
+ t.stubs(:to_param).returns('12')
+ end
+ @object = @objects.first
+ Thing.stubs(:find).returns(@object)
+ Thing.stubs(:new).returns(@object)
+ end
+
+ ## Default responses
+
+ (Resourceful::ACTIONS - Resourceful::MODIFYING_ACTIONS).each(&method(:should_render_html))
+ Resourceful::ACTIONS.each(&method(:should_render_js))
+ Resourceful::ACTIONS.each(&method(:shouldnt_render_xml))
+
+ ## Specs for #index
+
+ it "should find all records on GET /things" do
+ Thing.expects(:find).with(:all).returns(@objects)
+ get :index
+ end
+
+ it "should return a list of objects for #current_objects after GET /things" do
+ Thing.stubs(:find).returns(@objects)
+ get :index
+ controller.current_objects.should == @objects
+ end
+
+ it "should assign @things to a list of objects for GET /things" do
+ Thing.stubs(:find).returns(@objects)
+ get :index
+ assigns(:things).should == @objects
+ end
+
+ ## Specs for #show
+
+ it "should find the record with id 12 on GET /things/12" do
+ Thing.expects(:find).with('12').returns(@object)
+ get :show, :id => 12
+ end
+
+ it "should return an object for #current_object after GET /things/12" do
+ Thing.stubs(:find).returns(@object)
+ get :show, :id => 12
+ controller.current_object.should == @object
+ end
+
+ it "should assign @thing to an object for GET /things/12" do
+ Thing.stubs(:find).returns(@object)
+ get :show, :id => 12
+ assigns(:thing).should == @object
+ end
+
+ ## Specs for #edit
+
+ it "should find the record with id 12 on GET /things/12/edit" do
+ Thing.expects(:find).with('12').returns(@object)
+ get :edit, :id => 12
+ end
+
+ it "should return an object for #current_object after GET /things/12/edit" do
+ Thing.stubs(:find).returns(@object)
+ get :edit, :id => 12
+ controller.current_object.should == @object
+ end
+
+ it "should assign @thing to an object for GET /things/12/edit" do
+ Thing.stubs(:find).returns(@object)
+ get :edit, :id => 12
+ assigns(:thing).should == @object
+ end
+
+ ## Specs for #new
+
+ it "should create a new object from params[:thing] for GET /things/new" do
+ Thing.expects(:new).with('name' => "Herbert the thing").returns(@object)
+ get :new, :thing => {:name => "Herbert the thing"}
+ end
+
+ it "should create a new object even if there aren't any params for GET /things/new" do
+ Thing.expects(:new).with(nil).returns(@object)
+ get :new
+ end
+
+ it "should return the new object for #current_object after GET /things/new" do
+ Thing.stubs(:new).returns(@object)
+ get :new
+ controller.current_object.should == @object
+ end
+
+ it "should assign @thing to the new object for GET /things/new" do
+ Thing.stubs(:new).returns(@object)
+ get :new
+ assigns(:thing).should == @object
+ end
+
+ ## Specs for #create
+
+ it "should create a new object from params[:thing] for POST /things" do
+ Thing.expects(:new).with('name' => "Herbert the thing").returns(@object)
+ post :create, :thing => {:name => "Herbert the thing"}
+ end
+
+ it "should create a new object even if there aren't any params for POST /things" do
+ Thing.expects(:new).with(nil).returns(@object)
+ post :create
+ end
+
+ it "should return the new object for #current_object after POST /things" do
+ Thing.stubs(:new).returns(@object)
+ post :create
+ controller.current_object.should == @object
+ end
+
+ it "should assign @thing to the new object for POST /things" do
+ Thing.stubs(:new).returns(@object)
+ post :create
+ assigns(:thing).should == @object
+ end
+
+ it "should save the new object for POST /things" do
+ Thing.stubs(:new).returns(@object)
+ @object.expects(:save)
+ post :create
+ end
+
+ it "should set an appropriate flash notice for a successful POST /things" do
+ Thing.stubs(:new).returns(@object)
+ post :create
+ flash[:notice].should == "Create successful!"
+ end
+
+ it "should redirect to the new object for a successful POST /things" do
+ Thing.stubs(:new).returns(@object)
+ post :create
+ response.should redirect_to('/things/12')
+ end
+
+ it "should set an appropriate flash error for an unsuccessful POST /things" do
+ Thing.stubs(:new).returns(@object)
+ @object.stubs(:save).returns(false)
+ post :create
+ flash[:error].should == "There was a problem!"
+ end
+
+ it "should give a failing response for an unsuccessful POST /things" do
+ Thing.stubs(:new).returns(@object)
+ @object.stubs(:save).returns(false)
+ post :create
+ response.should_not be_success
+ response.code.should == '422'
+ end
+
+ it "should render the #new template for an unsuccessful POST /things" do
+ Thing.stubs(:new).returns(@object)
+ @object.stubs(:save).returns(false)
+ post :create
+ response.should render_template('new')
+ end
+
+ ## Specs for #update
+
+ it "should find the record with id 12 on PUT /things/12" do
+ Thing.expects(:find).with('12').returns(@object)
+ put :update, :id => 12
+ end
+
+ it "should return an object for #current_object after PUT /things/12" do
+ Thing.stubs(:find).returns(@object)
+ put :update, :id => 12
+ controller.current_object.should == @object
+ end
+
+ it "should assign @thing to an object for PUT /things/12" do
+ Thing.stubs(:find).returns(@object)
+ put :update, :id => 12
+ assigns(:thing).should == @object
+ end
+
+ it "should update the new object for PUT /things/12" do
+ Thing.stubs(:find).returns(@object)
+ @object.expects(:update_attributes).with('name' => "Jorje")
+ put :update, :id => 12, :thing => {:name => "Jorje"}
+ end
+
+ it "should set an appropriate flash notice for a successful PUT /things/12" do
+ Thing.stubs(:find).returns(@object)
+ put :update, :id => 12
+ flash[:notice].should == "Save successful!"
+ end
+
+ it "should redirect to the updated object for a successful PUT /things/12" do
+ Thing.stubs(:find).returns(@object)
+ put :update, :id => 12
+ response.should redirect_to('/things/12')
+ end
+
+ it "should set an appropriate flash error for an unsuccessful PUT /things/12" do
+ Thing.stubs(:find).returns(@object)
+ @object.stubs(:update_attributes).returns(false)
+ put :update, :id => 12
+ flash[:error].should == "There was a problem saving!"
+ end
+
+ it "should give a failing response for an unsuccessful PUT /things/12" do
+ Thing.stubs(:find).returns(@object)
+ @object.stubs(:update_attributes).returns(false)
+ put :update, :id => 12
+ response.should_not be_success
+ response.code.should == '422'
+ end
+
+ it "should render the #edit template for an unsuccessful PUT /things/12" do
+ Thing.stubs(:find).returns(@object)
+ @object.stubs(:update_attributes).returns(false)
+ put :update, :id => 12
+ response.should render_template('edit')
+ end
+
+ ## Specs for #destroy
+
+ it "should find the record with id 12 on DELETE /things/12" do
+ Thing.expects(:find).with('12').returns(@object)
+ delete :destroy, :id => 12
+ end
+
+ it "should return an object for #current_object after DELETE /things/12" do
+ Thing.stubs(:find).returns(@object)
+ delete :destroy, :id => 12
+ controller.current_object.should == @object
+ end
+
+ it "should assign @thing to an object for DELETE /things/12" do
+ Thing.stubs(:find).returns(@object)
+ delete :destroy, :id => 12
+ assigns(:thing).should == @object
+ end
+
+ it "should destroy the new object for DELETE /things/12" do
+ Thing.stubs(:find).returns(@object)
+ @object.expects(:destroy)
+ delete :destroy, :id => 12
+ end
+
+ it "should set an appropriate flash notice for a successful DELETE /things/12" do
+ Thing.stubs(:find).returns(@object)
+ delete :destroy, :id => 12
+ flash[:notice].should == "Record deleted!"
+ end
+
+ it "should redirect to the object list for a successful DELETE /things/12" do
+ Thing.stubs(:find).returns(@object)
+ delete :destroy, :id => 12
+ response.should redirect_to('/things')
+ end
+
+ it "should set an appropriate flash error for an unsuccessful DELETE /things/12" do
+ Thing.stubs(:find).returns(@object)
+ @object.stubs(:destroy).returns(false)
+ delete :destroy, :id => 12
+ flash[:error].should == "There was a problem deleting!"
+ end
+
+ it "should give a failing response for an unsuccessful DELETE /things/12" do
+ Thing.stubs(:find).returns(@object)
+ @object.stubs(:destroy).returns(false)
+ delete :destroy, :id => 12
+ response.should_not be_success
+ end
+
+ it "should redirect to the previous page for an unsuccessful DELETE /things/12" do
+ Thing.stubs(:find).returns(@object)
+ @object.stubs(:destroy).returns(false)
+ delete :destroy, :id => 12
+ response.should redirect_to(:back)
+ end
+end
+
+describe "ThingsController", "with several parent objects", :type => :integration do
+ include RailsMocks
+ before :each do
+ mock_resourceful do
+ actions :all
+ belongs_to :person, :category
+ end
+ stub_const 'Person'
+ stub_const 'Category'
+
+ @objects = stub_list(5, 'Thing') do |t|
+ t.stubs(:save).returns(true)
+ end
+ @object = @objects.first
+ @person = stub('Person')
+ @category = stub('Category')
+ @fake_model = stub('parent_object.things')
+ end
+
+ ## No parent ids
+
+ it "should find all things on GET /things" do
+ Thing.expects(:find).with(:all).returns(@objects)
+ get :index
+ controller.current_objects.should == @objects
+ end
+
+ it "should find the thing with id 12 regardless of scoping on GET /things/12" do
+ Thing.expects(:find).with('12').returns(@object)
+ get :show, :id => 12
+ controller.current_object.should == @object
+ end
+
+ it "should create a new thing without a person on POST /things" do
+ Thing.expects(:new).with('name' => "Lamp").returns(@object)
+ post :create, :thing => {:name => "Lamp"}
+ controller.current_object.should == @object
+ end
+
+ ## Person ids
+
+ it "should assign the proper parent variables and accessors to the person with id 4 for GET /people/4/things" do
+ Person.stubs(:find).returns(@person)
+ @person.stubs(:things).returns(@fake_model)
+ @fake_model.stubs(:find).with(:all).returns(@objects)
+ get :index, :person_id => 4
+ controller.parent_object.should == @person
+ assigns(:person).should == @person
+ end
+
+ it "should find all the things belonging to the person with id 4 on GET /people/4/things" do
+ Person.expects(:find).with('4').returns(@person)
+ @person.expects(:things).at_least_once.returns(@fake_model)
+ @fake_model.expects(:find).with(:all).returns(@objects)
+ get :index, :person_id => 4
+ controller.current_objects.should == @objects
+ end
+
+ it "should find the thing with id 12 if it belongs to the person with id 4 on GET /person/4/things/12" do
+ Person.expects(:find).with('4').returns(@person)
+ @person.expects(:things).at_least_once.returns(@fake_model)
+ @fake_model.expects(:find).with('12').returns(@object)
+ get :show, :person_id => 4, :id => 12
+ controller.current_object.should == @object
+ end
+
+ it "should create a new thing belonging to the person with id 4 on POST /person/4/things" do
+ Person.expects(:find).with('4').returns(@person)
+ @person.expects(:things).at_least_once.returns(@fake_model)
+ @fake_model.expects(:build).with('name' => 'Lamp').returns(@object)
+ post :create, :person_id => 4, :thing => {:name => "Lamp"}
+ controller.current_object.should == @object
+ end
+
+ ## Category ids
+
+ it "should assign the proper parent variables and accessors to the category with id 4 for GET /people/4/things" do
+ Category.stubs(:find).returns(@category)
+ @category.stubs(:things).returns(@fake_model)
+ @fake_model.stubs(:find).with(:all).returns(@objects)
+ get :index, :category_id => 4
+ controller.parent_object.should == @category
+ assigns(:category).should == @category
+ end
+
+ it "should find all the things belonging to the category with id 4 on GET /people/4/things" do
+ Category.expects(:find).with('4').returns(@category)
+ @category.expects(:things).at_least_once.returns(@fake_model)
+ @fake_model.expects(:find).with(:all).returns(@objects)
+ get :index, :category_id => 4
+ controller.current_objects.should == @objects
+ end
+
+ it "should find the thing with id 12 if it belongs to the category with id 4 on GET /category/4/things/12" do
+ Category.expects(:find).with('4').returns(@category)
+ @category.expects(:things).at_least_once.returns(@fake_model)
+ @fake_model.expects(:find).with('12').returns(@object)
+ get :show, :category_id => 4, :id => 12
+ controller.current_object.should == @object
+ end
+
+ it "should create a new thing belonging to the category with id 4 on POST /category/4/things" do
+ Category.expects(:find).with('4').returns(@category)
+ @category.expects(:things).at_least_once.returns(@fake_model)
+ @fake_model.expects(:build).with('name' => 'Lamp').returns(@object)
+ post :create, :category_id => 4, :thing => {:name => "Lamp"}
+ controller.current_object.should == @object
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/maker_spec.rb b/vendor/plugins/make_resourceful/spec/maker_spec.rb
new file mode 100644
index 0000000..f295396
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/maker_spec.rb
@@ -0,0 +1,91 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe Resourceful::Maker, "when extended" do
+ include ControllerMocks
+ before(:each) { mock_kontroller }
+
+ it "should create an empty, inheritable callbacks hash" do
+ @kontroller.read_inheritable_attribute(:resourceful_callbacks).should == {}
+ end
+
+ it "should create an empty, inheritable responses hash" do
+ @kontroller.read_inheritable_attribute(:resourceful_responses).should == {}
+ end
+
+ it "should create an empty, inheritable parents array" do
+ @kontroller.read_inheritable_attribute(:parents).should == []
+ end
+
+ it "should create a made_resourceful variable set to false" do
+ @kontroller.read_inheritable_attribute(:made_resourceful).should be_false
+ end
+
+ it "should create a made_resourceful? method on the controller that returns the variable" do
+ @kontroller.should_not be_made_resourceful
+ @kontroller.write_inheritable_attribute(:made_resourceful, true)
+ @kontroller.should be_made_resourceful
+ end
+end
+
+describe Resourceful::Maker, "when made_resourceful" do
+ include ControllerMocks
+ before(:each) do
+ mock_kontroller
+ mock_builder
+ end
+
+ it "should include Resourceful::Base" do
+ @kontroller.expects(:include).with(Resourceful::Base)
+ @kontroller.make_resourceful {}
+ end
+
+ it "should use Resourceful::Builder to build the controller" do
+ Resourceful::Builder.expects(:new).with(@kontroller).returns(@builder)
+ @kontroller.make_resourceful {}
+ end
+
+ it "should evaluate the made_resourceful callbacks in the context of the builder" do
+ procs = (1..5).map { should_be_called { with(@builder) } }
+ Resourceful::Base.stubs(:made_resourceful).returns(procs)
+ @kontroller.make_resourceful {}
+ end
+
+ it "should evaluate the :include callback in the context of the builder" do
+ @kontroller.make_resourceful(:include => should_be_called { with(@builder) }) {}
+ end
+
+ it "should evaluate the given block in the context of the builder" do
+ @kontroller.make_resourceful(&(should_be_called { with(@builder) }))
+ end
+end
+
+describe Resourceful::Maker, "when made_resourceful with an inherited controller" do
+ include ControllerMocks
+ before(:each) do
+ mock_kontroller
+ mock_builder :inherited
+ end
+
+ it "should include Resourceful::Base" do
+ @kontroller.expects(:include).with(Resourceful::Base)
+ @kontroller.make_resourceful {}
+ end
+
+ it "should use Resourceful::Builder to build the controller" do
+ Resourceful::Builder.expects(:new).with(@kontroller).returns(@builder)
+ @kontroller.make_resourceful {}
+ end
+
+ it "should not evaluate the made_resourceful callbacks in the context of the builder" do
+ Resourceful::Base.expects(:made_resourceful).never
+ @kontroller.make_resourceful {}
+ end
+
+ it "should evaluate the :include callback in the context of the builder" do
+ @kontroller.make_resourceful(:include => should_be_called { with(@builder) }) {}
+ end
+
+ it "should evaluate the given block in the context of the builder" do
+ @kontroller.make_resourceful(&(should_be_called { with(@builder) }))
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/response_spec.rb b/vendor/plugins/make_resourceful/spec/response_spec.rb
new file mode 100644
index 0000000..c659d95
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/response_spec.rb
@@ -0,0 +1,37 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe Resourceful::Response, "when first created" do
+ before(:each) { @response = Resourceful::Response.new }
+
+ it "should have an empty formats array" do
+ @response.formats.should == []
+ end
+end
+
+describe Resourceful::Response, "with a few formats" do
+ before :each do
+ @response = Resourceful::Response.new
+ @response.html
+ @response.js {'javascript'}
+ @response.xml {'xml'}
+ end
+
+ it "should store the formats and blocks" do
+ @response.formats.should have_any {|f,p| f == :js && p.call == 'javascript'}
+ @response.formats.should have_any {|f,p| f == :xml && p.call == 'xml'}
+ end
+
+ it "should give formats without a block an empty block" do
+ @response.formats.should have_any {|f,p| f == :html && Proc === p && p.call.nil?}
+ end
+
+ it "shouldn't allow duplicate formats" do
+ @response.js {'not javascript'}
+ @response.formats.should have_any {|f,p| f == :js && p.call == 'javascript'}
+ @response.formats.should_not have_any {|f,p| f == :js && p.call == 'not javascript'}
+ end
+
+ it "should keep the formats in sorted order" do
+ @response.formats.map(&:first).should == [:html, :js, :xml]
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/responses_spec.rb b/vendor/plugins/make_resourceful/spec/responses_spec.rb
new file mode 100644
index 0000000..607ee79
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/responses_spec.rb
@@ -0,0 +1,314 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe 'Resourceful::Default::Responses', " with a _flash parameter for :error" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Responses
+ @flash = {}
+ @controller.stubs(:flash).returns(@flash)
+ @params = {:_flash => {:error => 'Oh no, an error!'}}
+ @controller.stubs(:params).returns(@params)
+ end
+
+ it "should set the flash for :error to the parameter's value when set_default_flash is called on :error" do
+ @controller.set_default_flash(:error, "Aw there's no error!")
+ @flash[:error].should == 'Oh no, an error!'
+ end
+
+ it "should set the flash for :message to the default value when set_default_flash is called on :message" do
+ @controller.set_default_flash(:message, "All jim dandy!")
+ @flash[:message].should == 'All jim dandy!'
+ end
+
+ it "shouldn't set the flash for :error when set_default_flash is called on :message" do
+ @controller.set_default_flash(:message, "All jim dandy!")
+ @flash[:error].should be_nil
+ end
+end
+
+describe 'Resourceful::Default::Responses', " with a _redirect parameter on :failure" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Responses
+ @params = {:_redirect_on => {:failure => 'http://hamptoncatlin.com/'}}
+ @controller.stubs(:params).returns(@params)
+ end
+
+ it "should set the redirect for :failure to the parameter's value when set_default_redirect is called on :failure" do
+ @controller.expects(:redirect_to).with('http://hamptoncatlin.com/')
+ @controller.set_default_redirect(:back, :status => :failure)
+ end
+
+ it "should set the redirect for :success to the default value when set_default_redirect is called on :success" do
+ @controller.expects(:redirect_to).with(:back)
+ @controller.set_default_redirect(:back, :status => :success)
+ end
+
+ it "shouldn't set the redirect for :failure when set_default_redirect is called on :success" do
+ @controller.expects(:redirect_to).with(:back)
+ @controller.expects(:redirect_to).with('http://hamptoncatlin.com/').never
+ @controller.set_default_redirect(:back, :status => :success)
+ end
+
+ it "should set the default redirect for :success by default" do
+ @controller.expects(:redirect_to).with(:back)
+ @controller.set_default_redirect(:back)
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for show' do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+ end
+
+ it "should have an empty HTML response" do
+ responses[:show].find { |f, p| f == :html }[1].call.should == nil
+ end
+
+ it "should have an empty JS response" do
+ responses[:show].find { |f, p| f == :js }[1].call.should == nil
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for index' do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+ end
+
+ it "should have an empty HTML response" do
+ responses[:index].find { |f, p| f == :html }[1].call.should == nil
+ end
+
+ it "should have an empty JS response" do
+ responses[:index].find { |f, p| f == :js }[1].call.should == nil
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for edit' do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+ end
+
+ it "should have an empty HTML response" do
+ responses[:edit].find { |f, p| f == :html }[1].call.should == nil
+ end
+
+ it "should have an empty JS response" do
+ responses[:edit].find { |f, p| f == :js }[1].call.should == nil
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for new' do
+ include ControllerMocks
+ before :each do
+ mock_kontroller
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+ end
+
+ it "should have an empty HTML response" do
+ responses[:new].find { |f, p| f == :html }[1].call.should == nil
+ end
+
+ it "should have an empty JS response" do
+ responses[:new].find { |f, p| f == :js }[1].call.should == nil
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for show_fails' do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Callbacks
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+ end
+
+ it "should give a 404 error for HTML" do
+ @controller.expects(:render).with(:text => "No item found", :status => 404)
+ @controller.scope(responses[:show_fails].find { |f, p| f == :html }[1]).call
+ end
+
+ it "should give a 404 error for JS" do
+ @controller.expects(:render).with(:text => "No item found", :status => 404)
+ @controller.scope(responses[:show_fails].find { |f, p| f == :js }[1]).call
+ end
+
+ it "should give a 404 error for XML" do
+ @controller.expects(:render).with(:text => "No item found", :status => 404)
+ @controller.scope(responses[:show_fails].find { |f, p| f == :xml }[1]).call
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for create' do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Callbacks
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+
+ [:set_default_flash, :set_default_redirect, :object_path].each(&@controller.method(:stubs))
+ end
+
+ it "should have an empty JS response" do
+ responses[:create].find { |f, p| f == :js }[1].call.should == nil
+ end
+
+ it "should flash a success message to :notice by default for HTML" do
+ @controller.expects(:set_default_flash).with(:notice, "Create successful!")
+ @controller.scope(responses[:create].find { |f, p| f == :html }[1]).call
+ end
+
+ it "should redirect to object_path by default for HTML" do
+ @controller.stubs(:object_path).returns("/posts/12")
+ @controller.expects(:set_default_redirect).with("/posts/12")
+ @controller.scope(responses[:create].find { |f, p| f == :html }[1]).call
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for create_fails' do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Callbacks
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+
+ [:set_default_flash, :render].each(&@controller.method(:stubs))
+ end
+
+ it "should have an empty JS response" do
+ responses[:create_fails].find { |f, p| f == :js }[1].call.should == nil
+ end
+
+ it "should flash a failure message to :error by default for HTML" do
+ @controller.expects(:set_default_flash).with(:error, "There was a problem!")
+ @controller.scope(responses[:create_fails].find { |f, p| f == :html }[1]).call
+ end
+
+ it "should render new with a 422 error for HTML" do
+ @controller.expects(:render).with(:action => :new, :status => 422)
+ @controller.scope(responses[:create_fails].find { |f, p| f == :html }[1]).call
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for update' do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Callbacks
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+
+ [:set_default_flash, :set_default_redirect, :object_path].each(&@controller.method(:stubs))
+ end
+
+ it "should have an empty JS response" do
+ responses[:update].find { |f, p| f == :js }[1].call.should == nil
+ end
+
+ it "should flash a success message to :notice by default for HTML" do
+ @controller.expects(:set_default_flash).with(:notice, "Save successful!")
+ @controller.scope(responses[:update].find { |f, p| f == :html }[1]).call
+ end
+
+ it "should redirect to object_path by default for HTML" do
+ @controller.stubs(:object_path).returns("/posts/12")
+ @controller.expects(:set_default_redirect).with("/posts/12")
+ @controller.scope(responses[:update].find { |f, p| f == :html }[1]).call
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for update_fails' do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Callbacks
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+
+ [:set_default_flash, :render].each(&@controller.method(:stubs))
+ end
+
+ it "should have an empty JS response" do
+ responses[:update_fails].find { |f, p| f == :js }[1].call.should == nil
+ end
+
+ it "should flash a failure message to :error by default for HTML" do
+ @controller.expects(:set_default_flash).with(:error, "There was a problem saving!")
+ @controller.scope(responses[:update_fails].find { |f, p| f == :html }[1]).call
+ end
+
+ it "should render edit with a 422 error for HTML" do
+ @controller.expects(:render).with(:action => :edit, :status => 422)
+ @controller.scope(responses[:update_fails].find { |f, p| f == :html }[1]).call
+ end
+end
+
+
+describe 'Resourceful::Default::Responses', ' for destroy' do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Callbacks
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+
+ [:set_default_flash, :set_default_redirect, :objects_path].each(&@controller.method(:stubs))
+ end
+
+ it "should have an empty JS response" do
+ responses[:destroy].find { |f, p| f == :js }[1].call.should == nil
+ end
+
+ it "should flash a success message to :notice by default for HTML" do
+ @controller.expects(:set_default_flash).with(:notice, "Record deleted!")
+ @controller.scope(responses[:destroy].find { |f, p| f == :html }[1]).call
+ end
+
+ it "should redirect to objects_path by default for HTML" do
+ @controller.stubs(:objects_path).returns("/posts")
+ @controller.expects(:set_default_redirect).with("/posts")
+ @controller.scope(responses[:destroy].find { |f, p| f == :html }[1]).call
+ end
+end
+
+describe 'Resourceful::Default::Responses', ' for destroy_fails' do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::Callbacks
+ create_builder
+ made_resourceful(Resourceful::Default::Responses)
+ @builder.apply
+
+ [:set_default_flash, :set_default_redirect, :render].each(&@controller.method(:stubs))
+ end
+
+ it "should have an empty JS response" do
+ responses[:destroy_fails].find { |f, p| f == :js }[1].call.should == nil
+ end
+
+ it "should flash a failure message to :error by default for HTML" do
+ @controller.expects(:set_default_flash).with(:error, "There was a problem deleting!")
+ @controller.scope(responses[:destroy_fails].find { |f, p| f == :html }[1]).call
+ end
+
+ it "should redirect back on failure by default for HTML" do
+ @controller.expects(:set_default_redirect).with(:back, :status => :failure)
+ @controller.scope(responses[:destroy_fails].find { |f, p| f == :html }[1]).call
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/rspec_on_rails/LICENSE b/vendor/plugins/make_resourceful/spec/rspec_on_rails/LICENSE
new file mode 100644
index 0000000..58453e3
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/rspec_on_rails/LICENSE
@@ -0,0 +1,35 @@
+All the code in this directory comes from the rspec_on_rails plugin.
+We've pilfered it as needed to make the make_resourceful specs easier to write.
+It was made available by its authors under the following license terms:
+
+====================================================================
+== RSpec
+Copyright (c) 2005-2007 The RSpec Development Team
+====================================================================
+== ARTS
+Copyright (c) 2006 Kevin Clark, Jake Howerton
+====================================================================
+== ZenTest
+Copyright (c) 2001-2006 Ryan Davis, Eric Hodel, Zen Spider Software
+====================================================================
+== AssertSelect
+Copyright (c) 2006 Assaf Arkin
+====================================================================
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/vendor/plugins/make_resourceful/spec/rspec_on_rails/redirect_to.rb b/vendor/plugins/make_resourceful/spec/rspec_on_rails/redirect_to.rb
new file mode 100644
index 0000000..4ebc93e
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/rspec_on_rails/redirect_to.rb
@@ -0,0 +1,81 @@
+require 'action_controller/url_rewriter'
+
+class RedirectTo
+ def initialize(request, expected)
+ @expected = expected
+ @request = request
+ end
+
+ def matches?(response)
+ @redirected = response.redirect?
+ @actual = response.redirect_url
+ return false unless @redirected
+ if @expected.instance_of? Hash
+ return false unless @actual =~ %r{^\w+://#{@request.host}}
+ return false unless actual_redirect_to_valid_route
+ return actual_hash == expected_hash
+ else
+ return @actual == expected_url
+ end
+ end
+
+ def actual_hash
+ hash_from_url @actual
+ end
+
+ def expected_hash
+ hash_from_url expected_url
+ end
+
+ def actual_redirect_to_valid_route
+ actual_hash
+ end
+
+ def hash_from_url(url)
+ query_hash(url).merge(path_hash(url)).with_indifferent_access
+ end
+
+ def path_hash(url)
+ path = url.sub(%r{^\w+://#{@request.host}}, "").split("?", 2)[0]
+ path = path.split("/")[1..-1] if ::Rails::VERSION::MINOR < 2
+ ActionController::Routing::Routes.recognize_path path
+ end
+
+ def query_hash(url)
+ query = url.split("?", 2)[1] || ""
+ if defined?(CGIMethods)
+ CGIMethods.parse_query_parameters(query)
+ else
+ ActionController::AbstractRequest.parse_query_parameters(query)
+ end
+ end
+
+ def expected_url
+ case @expected
+ when Hash
+ return ActionController::UrlRewriter.new(@request, {}).rewrite(@expected)
+ when :back
+ return @request.env['HTTP_REFERER']
+ when %r{^\w+://.*}
+ return @expected
+ else
+ return "http://#{@request.host}" + (@expected.split('')[0] == '/' ? '' : '/') + @expected
+ end
+ end
+
+ def failure_message
+ if @redirected
+ return %Q{expected redirect to #{@expected.inspect}, got redirect to #{@actual.inspect}}
+ else
+ return %Q{expected redirect to #{@expected.inspect}, got no redirect}
+ end
+ end
+
+ def negative_failure_message
+ return %Q{expected not to be redirected to #{@expected.inspect}, but was} if @redirected
+ end
+
+ def description
+ "redirect to #{@actual.inspect}"
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/rspec_on_rails/render_template.rb b/vendor/plugins/make_resourceful/spec/rspec_on_rails/render_template.rb
new file mode 100644
index 0000000..f073ff8
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/rspec_on_rails/render_template.rb
@@ -0,0 +1,28 @@
+
+class RenderTemplate
+
+ def initialize(expected, controller)
+ @controller = controller
+ @expected = expected
+ end
+
+ def matches?(response)
+ @actual = response.rendered_file
+ full_path(@actual) == full_path(@expected)
+ end
+
+ def failure_message
+ "expected #{@expected.inspect}, got #{@actual.inspect}"
+ end
+
+ def description
+ "render template #{@expected.inspect}"
+ end
+
+ private
+ def full_path(path)
+ return nil if path.nil?
+ path.include?('/') ? path : "#{@controller.class.to_s.underscore.gsub('_controller','')}/#{path}"
+ end
+
+end
diff --git a/vendor/plugins/make_resourceful/spec/serialize_spec.rb b/vendor/plugins/make_resourceful/spec/serialize_spec.rb
new file mode 100644
index 0000000..42cbdbf
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/serialize_spec.rb
@@ -0,0 +1,133 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe Resourceful::Serialize, ".normalize_attributes" do
+ it "should return nil if given nil" do
+ Resourceful::Serialize.normalize_attributes(nil).should be_nil
+ end
+
+ it "should return a basic hash if given a non-injectable attribute" do
+ Resourceful::Serialize.normalize_attributes(:foo).should == {:foo => nil}
+ Resourceful::Serialize.normalize_attributes(12).should == {12 => nil}
+ end
+
+ it "should return a basic hash with a symbol key if given a string attribute" do
+ Resourceful::Serialize.normalize_attributes("foo").should == {:foo => nil}
+ end
+
+ it "should preserve hashes" do
+ Resourceful::Serialize.normalize_attributes({:foo => nil, :bar => nil, :baz => nil}).should ==
+ {:foo => nil, :bar => nil, :baz => nil}
+ Resourceful::Serialize.normalize_attributes({:foo => 3, :bar => 1, :baz => 4}).should ==
+ {:foo => 3, :bar => 1, :baz => 4}
+ Resourceful::Serialize.normalize_attributes({:foo => 3, :bar => 1, :baz => [:foo, :bar]}).should ==
+ {:foo => 3, :bar => 1, :baz => [:foo, :bar]}
+ end
+
+ it "should merge injectable attributes into one big hash" do
+ Resourceful::Serialize.normalize_attributes([:foo, :bar, :baz]).should ==
+ {:foo => nil, :bar => nil, :baz => nil}
+ Resourceful::Serialize.normalize_attributes([:foo, :bar, {:baz => nil},
+ :boom, {:bop => nil, :blat => nil}]).should ==
+ {:foo => nil, :bar => nil, :baz => nil, :boom => nil, :bop => nil, :blat => nil}
+ Resourceful::Serialize.normalize_attributes([:foo, :bar, {:baz => 12},
+ :boom, {:bop => "foo", :blat => [:fee, :fi, :fo]}]).should ==
+ {:foo => nil, :bar => nil, :baz => 12, :boom => nil, :bop => "foo", :blat => [:fee, :fi, :fo]}
+ end
+end
+
+describe Array, " of non-serializable objects" do
+ before :each do
+ @array = [1, 2, 3, 4, "foo"]
+ end
+
+ it "should return itself for #to_serializable" do
+ @array.to_serializable(nil).should == @array
+ end
+
+ it "should raise an error for #serialize" do
+ lambda { @array.serialize(:yaml, :attributes => [:foo]) }.should raise_error("Not all elements respond to to_serializable")
+ end
+end
+
+describe Array, " of serializable objects" do
+ before :each do
+ @cat = stub_model("Cat")
+ @dog = stub_model("Dog")
+ @array = %w{brown yellow green}.zip(%w{rex rover fido}).
+ map { |c, d| @cat.new(:fur => c, :friend => @dog.new(:name => d)) }
+ end
+
+ it "should return an array of serializable hashes for #to_serializable" do
+ @array.to_serializable([:fur]).should == [{'fur' => 'brown'}, {'fur' => 'yellow'}, {'fur' => 'green'}]
+ end
+
+ it "should follow deep attributes for #to_serializable" do
+ @array.to_serializable([:fur, {:friend => :name}]).should ==
+ [{'fur' => 'brown', 'friend' => {'name' => 'rex'}},
+ {'fur' => 'yellow', 'friend' => {'name' => 'rover'}},
+ {'fur' => 'green', 'friend' => {'name' => 'fido'}}]
+ end
+
+ it "should raise an error if #serialize is called without the :attributes option" do
+ lambda { @array.serialize(:yaml, {}) }.should raise_error("Must specify :attributes option")
+ end
+
+ it "should serialize to a hash with a pluralized root for #serialize" do
+ YAML.load(@array.serialize(:yaml, :attributes => [:fur, {:friend => :name}])).should ==
+ {"cats" => [{'fur' => 'brown', 'friend' => {'name' => 'rex'}},
+ {'fur' => 'yellow', 'friend' => {'name' => 'rover'}},
+ {'fur' => 'green', 'friend' => {'name' => 'fido'}}]}
+ end
+
+ it "should serialize to an XML document with a pluralized root for #serialize(:xml, ...)" do
+ doc = REXML::Document.new(@array.serialize(:xml, :attributes => [:fur, {:friend => :name}]),
+ :ignore_whitespace_nodes => :all)
+ doc.root.name.should == "cats"
+ cats = doc.get_elements('/cats/cat')
+ cats.size.should == 3
+ cats.zip(%w{brown yellow green}, %w{rex rover fido}) do |cat, fur, dog|
+ cat.children.find { |e| e.name == "fur" }.text.should == fur
+ cat.children.find { |e| e.name == "friend" }.children[0].text.should == dog
+ end
+ end
+end
+
+describe ActiveRecord::Base, " with a few attributes and an association" do
+ before :each do
+ @person = stub_model("Person")
+ @party_hat = stub_model("PartyHat")
+ @model = @person.new(:name => "joe", :eye_color => "blue", :hairs => 567,
+ :party_hat => @party_hat.new(:color => 'blue', :size => 12, :pattern => 'stripey'))
+ end
+
+ it "should raise an error if #to_serializable is called without attributes" do
+ lambda { @model.to_serializable(nil) }.should raise_error("Must specify attributes for #<Person>.to_serializable")
+ end
+
+ it "should return an attributes hash for #to_serializable" do
+ @model.to_serializable([:name, :hairs, {:party_hat => [:color, :size]}]).should ==
+ {'name' => 'joe', 'hairs' => 567, 'party_hat' => {
+ 'color' => 'blue', 'size' => 12
+ }}
+ end
+
+ it "should raise an error if #serialize is called without the :attributes option" do
+ lambda { @model.serialize(:yaml, {}) }.should raise_error("Must specify :attributes option")
+ end
+
+ it "should serialize to a hash for #serialize" do
+ YAML.load(@model.serialize(:yaml, :attributes => [:hairs, :eye_color, {:party_hat => :size}])).should ==
+ {"person" => {'hairs' => 567, 'eye_color' => 'blue', 'party_hat' => {'size' => 12}}}
+ end
+
+ it "should serialize to an XML document for #serialize(:xml, ...)" do
+ doc = REXML::Document.new(@model.serialize(:xml, :attributes => [:name, :eye_color, {:party_hat => :pattern}]),
+ :ignore_whitespace_nodes => :all)
+ doc.root.name.should == "person"
+ doc.root.children.find { |e| e.name == "name" }.text.should == "joe"
+ doc.root.children.find { |e| e.name == "eye-color" }.text.should == "blue"
+
+ hat = doc.root.children.find { |e| e.name == "party-hat" }
+ hat.children.find { |e| e.name == "pattern" }.text.should == "stripey"
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/spec_helper.rb b/vendor/plugins/make_resourceful/spec/spec_helper.rb
new file mode 100644
index 0000000..6c5b15b
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/spec_helper.rb
@@ -0,0 +1,279 @@
+$: << File.dirname(__FILE__) + '/../lib'
+require 'rubygems'
+%w[spec action_pack active_record resourceful/maker
+ action_controller action_controller/test_process action_controller/integration
+ spec/rspec_on_rails/redirect_to spec/rspec_on_rails/render_template].each &method(:require)
+
+Spec::Runner.configure do |config|
+ config.mock_with :mocha
+end
+
+def should_be_called(&block)
+ pstub = stub
+ pstub.expects(:call).instance_eval(&(block || proc {}))
+ proc { |*args| pstub.call(*args) }
+end
+
+def stub_model(name)
+ model = Class.new do
+ include Resourceful::Serialize::Model
+
+ def self.to_s
+ @name
+ end
+
+ def initialize(attrs = {})
+ attrs.each do |k, v|
+ self.stubs(k).returns(v)
+ end
+ end
+
+ def inspect
+ "#<#{self.class.send(:instance_variable_get, '@name')}>"
+ end
+ end
+ model.send(:instance_variable_set, '@name', name)
+ model
+end
+
+def stub_const(name)
+ unless Object.const_defined?(name)
+ obj = Object.new
+ obj.metaclass.send(:define_method, :to_s) { name.to_s }
+ obj.metaclass.send(:alias_method, :inspect, :to_s)
+ Object.const_set(name, obj)
+ end
+ Object.const_get(name)
+end
+
+def stub_list(size, name = nil, &block)
+ list = Array.new(size) { |i| name ? stub("#{name}_#{i}") : stub }
+ list.each(&block) if block
+ list
+end
+
+module Spec::Matchers
+ def have_any(&proc)
+ satisfy { |a| a.any?(&proc) }
+ end
+end
+
+module ControllerMocks
+ def mock_kontroller(*to_extend)
+ options = to_extend.last.is_a?(Hash) ? to_extend.slice!(-1) : {}
+ @kontroller = Class.new
+ @kontroller.extend Resourceful::Maker
+ to_extend.each(&@kontroller.method(:extend))
+
+ @hidden_actions = Resourceful::ACTIONS.dup
+ @kontroller.stubs(:hidden_actions).returns(@hidden_actions)
+ @kontroller.stubs(:plural_action?).returns(false)
+ @kontroller.stubs(:include)
+ @kontroller.stubs(:before_filter)
+ @kontroller.stubs(:helper_method)
+ end
+
+ def mock_controller(*to_extend)
+ mock_kontroller
+ @controller = @kontroller.new
+ to_extend.each(&@controller.method(:extend))
+ end
+
+ def mock_builder(inherited = false)
+ @builder = stub
+ @builder.stubs(:response_for)
+ @builder.stubs(:apply)
+ @builder.stubs(:instance_eval).yields(@buildercc )
+ @builder.stubs(:inherited?).returns(inherited)
+ Resourceful::Base.stubs(:made_resourceful).returns([])
+ Resourceful::Builder.stubs(:new).returns(@builder)
+ end
+
+ def create_builder
+ @builder = Resourceful::Builder.new(@kontroller)
+ class << @builder
+ alias_method :made_resourceful, :instance_eval
+ end
+ end
+
+ def responses
+ @kontroller.read_inheritable_attribute(:resourceful_responses)
+ end
+
+ def callbacks
+ @kontroller.read_inheritable_attribute(:resourceful_callbacks)
+ end
+
+ def parents
+ @kontroller.read_inheritable_attribute(:parents)
+ end
+
+ # Evaluates the made_resourceful block of mod (a module)
+ # in the context of @builder.
+ # @builder should be initialized via create_builder.
+ def made_resourceful(mod)
+ mod.included(@builder)
+ end
+end
+
+module RailsMocks
+ attr_reader :response, :request, :controller, :kontroller
+
+ def included(mod)
+ require 'ruby-debug'
+ debugger
+ end
+
+ def mock_resourceful(options = {}, &block)
+ options = {
+ :name => "things"
+ }.merge options
+
+ init_kontroller options
+ init_routes options
+
+ stub_const(options[:name].singularize.camelize)
+ kontroller.make_resourceful(&block)
+
+ init_controller options
+ end
+
+ def assigns(name)
+ controller.instance_variable_get("@#{name}")
+ end
+
+ def redirect_to(opts)
+ RedirectTo.new(request, opts)
+ end
+
+ def render_template(path)
+ RenderTemplate.new(path.to_s, @controller)
+ end
+
+ private
+
+ def init_kontroller(options)
+ @kontroller = Class.new ActionController::Base
+ @kontroller.extend Resourceful::Maker
+
+ @kontroller.metaclass.send(:define_method, :controller_name) { options[:name] }
+ @kontroller.metaclass.send(:define_method, :controller_path) { options[:name] }
+ @kontroller.metaclass.send(:define_method, :inspect) { "#{options[:name].camelize}Controller" }
+ @kontroller.metaclass.send(:alias_method, :to_s, :inspect)
+
+ @kontroller.send(:define_method, :controller_name) { options[:name] }
+ @kontroller.send(:define_method, :controller_path) { options[:name] }
+ @kontroller.send(:define_method, :inspect) { "#<#{options[:name].camelize}Controller>" }
+ @kontroller.send(:alias_method, :to_s, :inspect)
+ @kontroller.send(:include, ControllerMethods)
+
+ @kontroller
+ end
+
+ def init_routes(options)
+ ActionController::Routing::Routes.clear!
+ route_block = options[:routes] || proc { |map| map.resources options[:name] }
+ ActionController::Routing::Routes.draw(&route_block)
+ end
+
+ def init_controller(options)
+ @controller = kontroller.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+
+ @controller.request = @request
+ @controller.response = @response
+ @request.accept = '*/*'
+ @request.env['HTTP_REFERER'] = 'http://test.host'
+
+ @controller
+ end
+
+ def action_params(action, params = {})
+ params.merge case action
+ when :show, :edit, :destroy: {:id => 12}
+ when :update: {:id => 12, :thing => {}}
+ when :create: {:thing => {}}
+ else {}
+ end
+ end
+
+ def action_method(action)
+ method case action
+ when :index, :show, :edit, :new: :get
+ when :update: :put
+ when :create: :post
+ when :destroy: :delete
+ end
+ end
+
+ module ControllerMethods
+ def render(options=nil, deprecated_status=nil, &block)
+ unless block_given?
+ @template.metaclass.class_eval do
+ define_method :file_exists? do true end
+ define_method :render_file do |*args|
+ @first_render ||= args[0]
+ end
+ end
+ end
+
+ super(options, deprecated_status, &block)
+ end
+ end
+end
+
+module Spec::Example::ExampleGroupMethods
+ def should_render_html(action)
+ it "should render HTML by default for #{action_string(action)}" do
+ action_method(action)[action, action_params(action)]
+ response.should be_success
+ response.content_type.should == 'text/html'
+ end
+ end
+
+ def should_render_js(action)
+ it "should render JS for #{action_string(action)}" do
+ action_method(action)[action, action_params(action, :format => 'js')]
+ response.should be_success
+ response.content_type.should == 'text/javascript'
+ end
+ end
+
+ def shouldnt_render_xml(action)
+ it "should render XML for #{action_string(action)}" do
+ action_method(action)[action, action_params(action, :format => 'xml')]
+ response.should_not be_success
+ response.code.should == '406'
+ end
+ end
+
+ def action_string(action)
+ case action
+ when :index: "GET /things"
+ when :show: "GET /things/12"
+ when :edit: "GET /things/12/edit"
+ when :update: "PUT /things/12"
+ when :create: "POST /things"
+ when :new: "GET /things/new"
+ when :destroy: "DELETE /things/12"
+ end
+ end
+end
+
+module Spec::Example
+ class IntegrationExampleGroup < Test::Unit::TestCase
+ include ExampleMethods
+ class << self
+ include ExampleGroupMethods
+ end
+
+ def initialize(defined_description, &implementation)
+ super()
+ @_defined_description = defined_description
+ @_implementation = implementation
+ end
+
+ ExampleGroupFactory.register(:integration, self)
+ end
+end
diff --git a/vendor/plugins/make_resourceful/spec/urls_spec.rb b/vendor/plugins/make_resourceful/spec/urls_spec.rb
new file mode 100644
index 0000000..73a1862
--- /dev/null
+++ b/vendor/plugins/make_resourceful/spec/urls_spec.rb
@@ -0,0 +1,276 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe Resourceful::Default::URLs, " for a controller with no parents or namespaces" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::URLs
+ @object = stub_model('Thing')
+ @controller.stubs(:current_object).returns(@object)
+
+ @controller.stubs(:current_model_name).returns('Thing')
+ @controller.stubs(:parent?).returns(false)
+ @controller.stubs(:namespaces).returns([])
+ end
+
+ it "should return nil for #url_helper_prefix" do
+ @controller.url_helper_prefix.should be_nil
+ end
+
+ it "should return the empty string for #collection_url_prefix" do
+ @controller.collection_url_prefix.should == ""
+ end
+
+ it "should get the path of current_object with #object_path" do
+ @controller.expects(:send).with('thing_path', @object)
+ @controller.object_path
+ end
+
+ it "should get the url of current_object with #object_url" do
+ @controller.expects(:send).with('thing_url', @object)
+ @controller.object_url
+ end
+
+ it "should get the path of the passed object with #object_path" do
+ model = stub_model('Thing')
+ @controller.expects(:send).with('thing_path', model)
+ @controller.object_path(model)
+ end
+
+ it "should get the url of the passed object with #object_url" do
+ model = stub_model('Thing')
+ @controller.expects(:send).with('thing_url', model)
+ @controller.object_url(model)
+ end
+
+ it "should get the path of current_object with #nested_object_path" do
+ @controller.expects(:send).with('thing_path', @object)
+ @controller.nested_object_path
+ end
+
+ it "should get the url of current_object with #nested_object_url" do
+ @controller.expects(:send).with('thing_url', @object)
+ @controller.nested_object_url
+ end
+
+ it "should get the path of the passed object with #nested_object_path" do
+ model = stub_model('Thing')
+ @controller.expects(:send).with('thing_path', model)
+ @controller.nested_object_path(model)
+ end
+
+ it "should get the url of the passed object with #nested_object_url" do
+ model = stub_model('Thing')
+ @controller.expects(:send).with('thing_url', model)
+ @controller.nested_object_url(model)
+ end
+
+ it "should get the edit path of current_object with #edit_object_path" do
+ @controller.expects(:send).with('edit_thing_path', @object)
+ @controller.edit_object_path
+ end
+
+ it "should get the edit url of current_object with #edit_object_url" do
+ @controller.expects(:send).with('edit_thing_url', @object)
+ @controller.edit_object_url
+ end
+
+ it "should get the edit path of the passed object with #edit_object_path" do
+ model = stub_model('Thing')
+ @controller.expects(:send).with('edit_thing_path', model)
+ @controller.edit_object_path(model)
+ end
+
+ it "should get the edit url of the passed object with #edit_object_url" do
+ model = stub_model('Thing')
+ @controller.expects(:send).with('edit_thing_url', model)
+ @controller.edit_object_url(model)
+ end
+
+ it "should get the plural path of the current model with #objects_path" do
+ @controller.expects(:send).with('things_path')
+ @controller.objects_path
+ end
+
+ it "should get the plural url of the current model with #objects_url" do
+ @controller.expects(:send).with('things_url')
+ @controller.objects_url
+ end
+
+ it "should get the new path of the current model with #new_object_path" do
+ @controller.expects(:send).with('new_thing_path')
+ @controller.new_object_path
+ end
+
+ it "should get the new url of the current model with #new_object_url" do
+ @controller.expects(:send).with('new_thing_url')
+ @controller.new_object_url
+ end
+end
+
+describe Resourceful::Default::URLs, " for a controller with a parent object" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::URLs
+ @object = stub_model('Thing')
+ @controller.stubs(:current_object).returns(@object)
+
+ @controller.stubs(:current_model_name).returns('Thing')
+
+ @person = stub_model('Person')
+ @controller.stubs(:parent_object).returns(@person)
+ @controller.stubs(:parent_name).returns('person')
+ @controller.stubs(:parent?).returns(true)
+ @controller.stubs(:namespaces).returns([])
+ end
+
+ it "should return nil for #url_helper_prefix" do
+ @controller.url_helper_prefix.should be_nil
+ end
+
+ it "should return the underscored parent name for #collection_url_prefix" do
+ @controller.collection_url_prefix.should == "person_"
+ end
+
+ it "should get the path of current_object with #object_path" do
+ @controller.expects(:send).with('thing_path', @object)
+ @controller.object_path
+ end
+
+ it "should get the nested path of current_object with #nested_object_path" do
+ @controller.expects(:send).with('person_thing_path', @person, @object)
+ @controller.nested_object_path
+ end
+
+ it "should get the nested url of current_object with #nested_object_url" do
+ @controller.expects(:send).with('person_thing_url', @person, @object)
+ @controller.nested_object_url
+ end
+
+ it "should get the nested path of the passed object with #nested_object_path" do
+ object = stub_model('Thing')
+ @controller.expects(:send).with('person_thing_path', @person, object)
+ @controller.nested_object_path object
+ end
+
+ it "should get the nested url of the passed object with #nested_object_url" do
+ object = stub_model('Thing')
+ @controller.expects(:send).with('person_thing_url', @person, object)
+ @controller.nested_object_url object
+ end
+
+ it "should get the plural path of the current model and its parent with #objects_path" do
+ @controller.expects(:send).with('person_things_path', @person)
+ @controller.objects_path
+ end
+
+ it "should get the edit path of the current model with #edit_object_path" do
+ @controller.expects(:send).with('edit_thing_path', @object)
+ @controller.edit_object_path
+ end
+
+ it "should get the new path of the current model and its parent with #new_object_path" do
+ @controller.expects(:send).with('new_person_thing_path', @person)
+ @controller.new_object_path
+ end
+
+ it "should get the path of the parent_object with #parent_path" do
+ @controller.expects(:send).with('person_path', @person)
+ @controller.parent_path
+ end
+
+ it "should get the url of the parent_object with #parent_url" do
+ @controller.expects(:send).with('person_url', @person)
+ @controller.parent_url
+ end
+
+ it "should get the path of the passed object with #parent_path" do
+ model = stub_model('Person')
+ @controller.expects(:send).with('person_path', model)
+ @controller.parent_path model
+ end
+
+ it "should get the url of the passed object with #parent_url" do
+ model = stub_model('Person')
+ @controller.expects(:send).with('person_url', model)
+ @controller.parent_url model
+ end
+end
+
+describe Resourceful::Default::URLs, " for a controller within a namespace" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::URLs
+ @object = stub_model('Thing')
+ @controller.stubs(:current_object).returns(@object)
+
+ @controller.stubs(:current_model_name).returns('Thing')
+
+ @controller.stubs(:parent?).returns(false)
+ @controller.stubs(:namespaces).returns([:admin, :main])
+ end
+
+ it "should return the underscored list of namespaces for #url_helper_prefix" do
+ @controller.url_helper_prefix.should == "admin_main_"
+ end
+
+ it "should get the namespaced path of current_object with #object_path" do
+ @controller.expects(:send).with('admin_main_thing_path', @object)
+ @controller.object_path
+ end
+
+ it "should get the namespaced plural path of the current model with #objects_path" do
+ @controller.expects(:send).with('admin_main_things_path')
+ @controller.objects_path
+ end
+
+ it "should get the edit path of the current model with #edit_object_path" do
+ @controller.expects(:send).with('edit_admin_main_thing_path', @object)
+ @controller.edit_object_path
+ end
+
+ it "should get the new path of the current model with #new_object_path" do
+ @controller.expects(:send).with('new_admin_main_thing_path')
+ @controller.new_object_path
+ end
+end
+
+describe Resourceful::Default::URLs, " for a controller with a parent object and within a namespace" do
+ include ControllerMocks
+ before :each do
+ mock_controller Resourceful::Default::URLs
+ @object = stub_model('Thing')
+ @controller.stubs(:current_object).returns(@object)
+
+ @controller.stubs(:current_model_name).returns('Thing')
+
+ @person = stub_model('Person')
+ @controller.stubs(:parent_object).returns(@person)
+ @controller.stubs(:parent_name).returns('person')
+ @controller.stubs(:parent?).returns(true)
+ @controller.stubs(:namespaces).returns([:admin, :main])
+ end
+
+ it "should return the underscored list of namespaces for #url_helper_prefix" do
+ @controller.url_helper_prefix.should == "admin_main_"
+ end
+
+ it "should get the namespaced path of current_object with #object_path" do
+ @controller.expects(:send).with('admin_main_thing_path', @object)
+ @controller.object_path
+ end
+
+ it "should get the namespaced plural path of the current model and its parent with #objects_path" do
+ @controller.expects(:send).with('admin_main_things_path', @person)
+ @controller.objects_path
+ end
+
+ it "should get the edit path of the current model with #edit_object_path" do
+ @controller.expects(:send).with('edit_admin_main_thing_path', @object)
+ @controller.edit_object_path
+ end
+
+ it "should get the new path of the current model and its parent with #new_object_path" do
+ @controller.expects(:send).with('new_admin_main_thing_path', @person)
+ @controller.new_object_path
+ end
+end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
16e1aec44d385089c676401f83291cf6d9a0c2b4
|
Getting this working slowly
|
diff --git a/log/.gitignore b/log/.gitignore
new file mode 100644
index 0000000..e69de29
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
b1d09f4b818f6134adffa02fc264ee32d94cde38
|
Hopefully ignoring log file
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f3a2cf2
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+log/*.log
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
7b3de9d484f2ba0f9ae700da2fb3c09be480450e
|
Added tagging search on actions.
|
diff --git a/app/models/action.rb b/app/models/action.rb
new file mode 100644
index 0000000..a0a60f1
--- /dev/null
+++ b/app/models/action.rb
@@ -0,0 +1,29 @@
+class Action < ActiveRecord::Base
+ belongs_to :feed
+
+ acts_as_taggable
+
+ def update_from_feed_item(item)
+ self.title = item.title
+ self.url = item.link
+ self.description = item.description
+ end
+
+ def description=(new_description)
+ write_attribute(:description, fix_quoted_html(new_description))
+ look_for_tags
+ end
+
+protected
+ def fix_quoted_html(text)
+ text.gsub(/\</, '<').gsub(/\>/, '>')
+ end
+
+ def look_for_tags
+ if feed.tag_finder
+ match = description.match(feed.tag_finder.to_s)
+ self.tag_list = match[1] if match and match[1]
+ puts "Found Tags: #{self.tag_list}"
+ end
+ end
+end
diff --git a/app/models/feed.rb b/app/models/feed.rb
index f3ef100..f8cfccd 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,2 +1,25 @@
+require 'rubygems'
+require 'simple-rss'
+require 'open-uri'
+
class Feed < ActiveRecord::Base
+ has_many :actions
+
+ def parse
+ feed.items.each do |item|
+ action = actions.find_or_create_by_url(item.link)
+ action.update_from_feed_item(item)
+ action.save!
+ end
+ end
+
+ def feed
+ @rss ||= SimpleRSS.parse(open(url))
+ end
+
+ class << self
+ def parse_all
+ find(:all).each { |feed| puts "Parsing #{feed.name}"; feed.parse }
+ end
+ end
end
diff --git a/db/migrate/002_create_actions.rb b/db/migrate/002_create_actions.rb
new file mode 100644
index 0000000..dbb3046
--- /dev/null
+++ b/db/migrate/002_create_actions.rb
@@ -0,0 +1,15 @@
+class CreateActions < ActiveRecord::Migration
+ def self.up
+ create_table :actions do |t|
+ t.text :description
+ t.string :url
+ t.text :title
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :actions
+ end
+end
diff --git a/db/migrate/003_add_feed_id_to_actions.rb b/db/migrate/003_add_feed_id_to_actions.rb
new file mode 100644
index 0000000..e9806e7
--- /dev/null
+++ b/db/migrate/003_add_feed_id_to_actions.rb
@@ -0,0 +1,9 @@
+class AddFeedIdToActions < ActiveRecord::Migration
+ def self.up
+ add_column :actions, :feed_id, :integer
+ end
+
+ def self.down
+ remove_column :actions, :feed_id
+ end
+end
diff --git a/db/migrate/004_acts_as_taggable_migration.rb b/db/migrate/004_acts_as_taggable_migration.rb
new file mode 100644
index 0000000..ea0c2cc
--- /dev/null
+++ b/db/migrate/004_acts_as_taggable_migration.rb
@@ -0,0 +1,26 @@
+class ActsAsTaggableMigration < ActiveRecord::Migration
+ def self.up
+ create_table :tags do |t|
+ t.column :name, :string
+ end
+
+ create_table :taggings do |t|
+ t.column :tag_id, :integer
+ t.column :taggable_id, :integer
+
+ # You should make sure that the column created is
+ # long enough to store the required class names.
+ t.column :taggable_type, :string
+
+ t.column :created_at, :datetime
+ end
+
+ add_index :taggings, :tag_id
+ add_index :taggings, [:taggable_id, :taggable_type]
+ end
+
+ def self.down
+ drop_table :taggings
+ drop_table :tags
+ end
+end
diff --git a/db/migrate/005_add_tag_finder_to_feeds.rb b/db/migrate/005_add_tag_finder_to_feeds.rb
new file mode 100644
index 0000000..7c501fe
--- /dev/null
+++ b/db/migrate/005_add_tag_finder_to_feeds.rb
@@ -0,0 +1,9 @@
+class AddTagFinderToFeeds < ActiveRecord::Migration
+ def self.up
+ add_column :feeds, :tag_finder, :string
+ end
+
+ def self.down
+ remove_column :feeds, :tag_finder
+ end
+end
diff --git a/spec/fixtures/actions.yml b/spec/fixtures/actions.yml
new file mode 100644
index 0000000..8b3269e
--- /dev/null
+++ b/spec/fixtures/actions.yml
@@ -0,0 +1,11 @@
+# # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+#
+# one:
+# description: MyText
+# url: MyString
+# title: MyText
+#
+# two:
+# description: MyText
+# url: MyString
+# title: MyText
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index 46befd0..cc71125 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,84 +1,102 @@
global_giving:
name: GlobalGiving
url: http://feeds.feedburner.com/GlobalGivingProjects
+ tag_finder:
last_accessed: <%= 1.day.ago %>
pledge_bank:
name: PledgeBank
url: http://everywhere.en-gb.pledgebank.com/rss/list
+ tag_finder:
last_accessed: <%= 1.day.ago %>
change_org_giving:
name: Change.org Giving Networks
url: http://www.change.org/giving_networks/rss
+ tag_finder: "<br />Tags: ([\w\s,]+)<br />"
last_accessed: <%= 1.day.ago %>
-change_org_canges:
+change_org_changes:
name: Change.org Changes
url: http://www.change.org/changes/rss
+ tag_finder: "<br />Tags: ([\w\s,]+)<br />"
last_accessed: <%= 1.day.ago %>
razoo_acts:
name: Razoo Acts
url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
+ tag_finder:
last_accessed: <%= 1.day.ago %>
razoo_goals:
name: Razoo Goals
url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
+ tag_finder:
last_accessed: <%= 1.day.ago %>
democracy_in_action:
name: DemocracyinAction
url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
+ tag_finder:
last_accessed: <%= 1.day.ago %>
care_2_petitions:
name: Care2 Petitions
url: http://www.thepetitionsite.com/browse-petitions/rss
+ tag_finder:
last_accessed: <%= 1.day.ago %>
-the_point:
- name: ThePoint
- url: https://www.thepoint.com/rss
- last_accessed: <%= 1.day.ago %>
+# https is causing failing right now
+# the_point:
+# name: ThePoint
+# url: http://www.thepoint.com/rss
+# tag_finder:
+# last_accessed: <%= 1.day.ago %>
give_meaning_proposals:
name: GiveMeaning Proposals
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
+ tag_finder: "\n\n Tags: ([\w\s,]+)"
last_accessed: <%= 1.day.ago %>
give_meaning_projects:
name: GiveMeaning Projects
url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
+ tag_finder: "\n\n Tags: ([\w\s,]+)"
last_accessed: <%= 1.day.ago %>
changing_the_present:
name: ChangingthePresent New Drives
url: http://www.changingthepresent.com/drives/rss
+ tag_finder:
last_accessed: <%= 1.day.ago %>
fundable:
name: Fundable
url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
+ tag_finder:
last_accessed: <%= 1.day.ago %>
bring_light:
name: BringLight
url: http://www.bringlight.com/feeds/all
+ tag_finder:
last_accessed: <%= 1.day.ago %>
kiva:
name: Kiva
url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
+ tag_finder:
last_accessed: <%= 1.day.ago %>
six_degrees:
name: SixDegrees
url: http://www.networkforgood.org/pca/badgefeed.aspx
+ tag_finder:
last_accessed: <%= 1.day.ago %>
first_giving:
name: Firstgiving
url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
+ tag_finder:
last_accessed: <%= 1.day.ago %>
diff --git a/spec/models/action_spec.rb b/spec/models/action_spec.rb
new file mode 100644
index 0000000..d8ce96a
--- /dev/null
+++ b/spec/models/action_spec.rb
@@ -0,0 +1,37 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe Action do
+ before(:each) do
+ @action = Action.new
+ end
+
+ it "should be valid" do
+ @action.should be_valid
+ end
+end
+
+describe "An Action" do
+ before(:each) do
+ @action = Action.new(:feed => feeds(:global_giving))
+ end
+
+ it "should convert > and < into < and > in the description" do
+ @action.description = 'This is <b>bold</b>'
+ @action.description.should eql('This is <b>bold</b>')
+ end
+
+ it "should allow itself to be tagged" do
+ @action.tags.should eql([])
+ @action.tag_list = 'Something, OrOther'
+ @action.save!
+ @action.tags.size.should equal(2)
+ end
+
+ it "should find tags in it's description" do
+ @action.tags.should eql([])
+ @action.feed.tag_finder = '<br />Tags: ([\w\s,]+)<br />'
+ @action.description = "Test hello <br />Tags: Something, OrOther<br /> world"
+ @action.save!
+ @action.tags.size.should equal(2)
+ end
+end
diff --git a/spec/models/feed_spec.rb b/spec/models/feed_spec.rb
index 3275c35..d87150e 100644
--- a/spec/models/feed_spec.rb
+++ b/spec/models/feed_spec.rb
@@ -1,11 +1,22 @@
require File.dirname(__FILE__) + '/../spec_helper'
describe Feed do
before(:each) do
@feed = Feed.new
end
it "should be valid" do
@feed.should be_valid
end
end
+
+describe "A feed" do
+ before(:each) do
+ @feed = feeds(:global_giving)
+ end
+
+ it "should make an HTTP request to it's URL when parse is called" do
+ # URI.stubs!(:open).and_returns(true)
+ @feed.parse
+ end
+end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 210d9d1..d8034c7 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,39 +1,39 @@
# This file is copied to ~/spec when you run 'ruby script/generate rspec'
# from the project root directory.
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'spec'
require 'spec/rails'
Spec::Runner.configure do |config|
# If you're not using ActiveRecord you should remove these
# lines, delete config/database.yml and disable :active_record
# in your config/boot.rb
config.use_transactional_fixtures = true
config.use_instantiated_fixtures = false
config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
# == Fixtures
#
# You can declare fixtures for each example_group like this:
# describe "...." do
# fixtures :table_a, :table_b
#
# Alternatively, if you prefer to declare them only once, you can
# do so right here. Just uncomment the next line and replace the fixture
# names with your fixtures.
#
- # config.global_fixtures = :table_a, :table_b
+ config.global_fixtures = :feeds
#
# If you declare global fixtures, be aware that they will be declared
# for all of your examples, even those that don't use them.
#
# == Mock Framework
#
# RSpec uses it's own mocking framework by default. If you prefer to
# use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/CHANGELOG b/vendor/plugins/acts_as_taggable_on_steroids/CHANGELOG
new file mode 100644
index 0000000..4c0b4f3
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/CHANGELOG
@@ -0,0 +1,158 @@
+[30 Jan 08]
+
+* Fix Tag.destroy_unused on Rails 2.0.
+
+[23 October 2007]
+
+* Make find_options_for_tag_counts and find_options_for_tagged_with dup their options.
+
+* Apply conditions properly in find_options_for_tag_counts.
+
+* Fix tag_cloud when no tags are present.
+
+[22 October 2007]
+
+* Fix find_tagged_with using :match_all and :include.
+
+* Use inner joins instead of left outer joins.
+
+[15 October 2007]
+
+* Make find_tagged_with correctly apply :conditions
+
+* Add Tag.destroy_unused option.
+
+[11 October 2007]
+
+* Make tag_counts work correctly with STI.
+
+[3 October 2007]
+
+* Improve documentation.
+
+* Fix TagsHelper and test.
+
+[2 October 2007]
+
+* Remove TagList.parse, use TagList.from instead.
+
+* Add :parse option to TagList#new, TagList#add, and TagList#remove.
+
+ tag_list = TagList.new("One, Two", :parse => true) # ["One", "Two"]
+
+ tag_list # ["One", "Two"]
+ tag_list.add("Three, Four", :parse => true) # ["One", "Two", "Three", "Four"]
+
+* Remove TagList#names.
+
+[29 September 2007]
+
+* Add TagsHelper to assist with generating tag clouds and provide a simple example.
+
+[27 September 2007]
+
+* Add #tag_counts method to get tag counts for a specific object's tags.
+
+* BACKWARDS INCOMPATIBILITY: Rename #find_options_for_tagged_with to #find_options_for_find_tagged_with
+
+[17 September 2007]
+
+* Fix clearing of cached tag list when all tags removed.
+
+[12 September 2007]
+
+* Make the TagList class inherit from Array.
+
+* Deprecate obsolete TagList#names.
+
+[6 September 2007]
+
+* Add TagList#include? and TagList#empty?
+
+[26 August 2006]
+
+* Remove deprecated Tag.delimiter. Use TagList.delimiter instead.
+
+[25 August 2007]
+
+* Make tag_counts work with has_many :through
+
+[23 August 2007]
+
+* Make search comparisons case-insensitive across different databases. [Moisés Machado]
+
+* Improve compatiblity with STI. [Moisés Machado]
+
+[25 July 2007]
+
+* Respect custom table names for the Tag and Tagging classes.
+
+* Fix the :exclude option for find_tagged_with
+
+[17 July 2007]
+
+* Make the migration work on edge rails
+
+[8 July 2007]
+
+* find_options_for_tagged_with should not alter its arguments
+
+[1 July 2007]
+
+* Fix incorrect tagging when the case of the tag list is changed.
+
+* Fix deprecated Tag.delimiter accessor.
+
+[23 June 2007]
+
+* Add validation to Tag model.
+
+* find_options_for_tagged_with should always return a hash.
+
+* find_tagged_with passing in no tags should return an empty array.
+
+* Improve compatibility with PostgreSQL.
+
+[21 June 2007]
+
+* Remove extra .rb from generated migration file name.
+
+[15 June 2007]
+
+* Introduce TagList class.
+
+* Various cleanups and improvements.
+
+* Use TagList.delimiter now, not Tag.delimiter. Tag.delimiter will be removed at some stage.
+
+[11 June 2007]
+
+* Restructure the creation of the options for find_tagged_with [Thijs Cadier]
+
+* Add an example migration with a generator.
+
+* Add caching.
+
+* Fix compatibility with Ruby < 1.8.6
+
+[23 April 2007]
+
+* Make tag_list to respect Tag.delimiter
+
+[31 March 2007]
+
+* Add Tag.delimiter accessor to change how tags are parsed.
+
+* Fix :include => :tags when used with find_tagged_with
+
+[7 March 2007]
+
+* Fix tag_counts for SQLServer [Brad Young]
+
+[21 Feb 2007]
+
+* Use scoping instead of TagCountsExtension [Michael Schuerig]
+
+[7 Jan 2007]
+
+* Add :match_all to find_tagged_with [Michael Sheakoski]
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/MIT-LICENSE b/vendor/plugins/acts_as_taggable_on_steroids/MIT-LICENSE
new file mode 100644
index 0000000..602bda2
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2006 Jonathan Viney
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/README b/vendor/plugins/acts_as_taggable_on_steroids/README
new file mode 100644
index 0000000..f8a8065
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/README
@@ -0,0 +1,142 @@
+= acts_as_taggable_on_steroids
+
+If you find this plugin useful, please consider a donation to show your support!
+
+ http://www.paypal.com/cgi-bin/webscr?cmd=_send-money
+
+ Email address: [email protected]
+
+== Instructions
+
+This plugin is based on acts_as_taggable by DHH but includes extras
+such as tests, smarter tag assignment, and tag cloud calculations.
+
+== Installation
+
+ ruby script/plugin install http://svn.viney.net.nz/things/rails/plugins/acts_as_taggable_on_steroids
+
+== Usage
+
+=== Prepare database
+
+Generate and apply the migration:
+
+ ruby script/generate acts_as_taggable_migration
+ rake db:migrate
+
+=== Basic tagging
+
+Let's suppose users have many posts and we want those posts to have tags.
+The first step is to add +acts_as_taggable+ to the Post class:
+
+ class Post < ActiveRecord::Base
+ acts_as_taggable
+
+ belongs_to :user
+ end
+
+We can now use the tagging methods provided by acts_as_taggable, <tt>#tag_list</tt> and <tt>#tag_list=</tt>. Both these
+methods work like regular attribute accessors.
+
+ p = Post.find(:first)
+ p.tag_list # []
+ p.tag_list = "Funny, Silly"
+ p.save
+ p.tag_list # ["Funny", "Silly"]
+
+You can also add or remove arrays of tags.
+
+ p.tag_list.add("Great", "Awful")
+ p.tag_list.remove("Funny")
+
+=== Finding tagged objects
+
+To retrieve objects tagged with a certain tag, use find_tagged_with.
+
+ Post.find_tagged_with('Funny, Silly')
+
+By default, find_tagged_with will find objects that have any of the given tags. To
+find only objects that are tagged with all the given tags, use match_all.
+
+ Post.find_tagged_with('Funny, Silly', :match_all => true)
+
+See <tt>ActiveRecord::Acts::Taggable::InstanceMethods</tt> for more methods and options.
+
+=== Tag cloud calculations
+
+To construct tag clouds, the frequency of each tag needs to be calculated.
+Because we specified +acts_as_taggable+ on the <tt>Post</tt> class, we can
+get a calculation of all the tag counts by using <tt>Post.tag_counts</tt>. But what if we wanted a tag count for
+an single user's posts? To achieve this we call tag_counts on the association:
+
+ User.find(:first).posts.tag_counts
+
+A helper is included to assist with generating tag clouds. Include it in your helper file:
+
+ module ApplicationHelper
+ include TagsHelper
+ end
+
+Here is an example that generates a tag cloud.
+
+Controller:
+
+ class PostController < ApplicationController
+ def tag_cloud
+ @tags = Post.tag_counts
+ end
+ end
+
+View:
+ <% tag_cloud @tags, %w(css1 css2 css3 css4) do |tag, css_class| %>
+ <%= link_to tag.name, { :action => :tag, :id => tag.name }, :class => css_class %>
+ <% end %>
+
+CSS:
+
+ .css1 { font-size: 1.0em; }
+ .css2 { font-size: 1.2em; }
+ .css3 { font-size: 1.4em; }
+ .css4 { font-size: 1.6em; }
+
+=== Caching
+
+It is useful to cache the list of tags to reduce the number of queries executed. To do this,
+add a column named <tt>cached_tag_list</tt> to the model which is being tagged. The column should be long enough to hold
+the full tag list and must have a default value of null, not an empty string.
+
+ class CachePostTagList < ActiveRecord::Migration
+ def self.up
+ add_column :posts, :cached_tag_list, :string
+ end
+ end
+
+ class Post < ActiveRecord::Base
+ acts_as_taggable
+
+ # The caching column defaults to cached_tag_list, but can be changed:
+ #
+ # set_cached_tag_list_column_name "my_caching_column_name"
+ end
+
+The details of the caching are handled for you. Just continue to use the tag_list accessor as you normally would.
+Note that the cached tag list will not be updated if you directly create Tagging objects or manually append to the
+<tt>tags</tt> or <tt>taggings</tt> associations. To update the cached tag list you should call <tt>save_cached_tag_list</tt> manually.
+
+=== Delimiter
+
+If you want to change the delimiter used to parse and present tags, set TagList.delimiter.
+For example, to use spaces instead of commas, add the following to config/environment.rb:
+
+ TagList.delimiter = " "
+
+=== Unused tags
+
+Set Tag.destroy_unused to remove tags when they are no longer being
+used to tag any objects. Defaults to false.
+
+ Tag.destroy_unused = true
+
+=== Other
+
+Problems, comments, and suggestions all welcome. [email protected]
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/Rakefile b/vendor/plugins/acts_as_taggable_on_steroids/Rakefile
new file mode 100644
index 0000000..d2c0003
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/Rakefile
@@ -0,0 +1,22 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the acts_as_taggable_on_steroids plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the acts_as_taggable_on_steroids plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'Acts As Taggable On Steroids'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/generators/acts_as_taggable_migration/acts_as_taggable_migration_generator.rb b/vendor/plugins/acts_as_taggable_on_steroids/generators/acts_as_taggable_migration/acts_as_taggable_migration_generator.rb
new file mode 100644
index 0000000..be9b39c
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/generators/acts_as_taggable_migration/acts_as_taggable_migration_generator.rb
@@ -0,0 +1,11 @@
+class ActsAsTaggableMigrationGenerator < Rails::Generator::Base
+ def manifest
+ record do |m|
+ m.migration_template 'migration.rb', 'db/migrate'
+ end
+ end
+
+ def file_name
+ "acts_as_taggable_migration"
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/generators/acts_as_taggable_migration/templates/migration.rb b/vendor/plugins/acts_as_taggable_on_steroids/generators/acts_as_taggable_migration/templates/migration.rb
new file mode 100644
index 0000000..ea0c2cc
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/generators/acts_as_taggable_migration/templates/migration.rb
@@ -0,0 +1,26 @@
+class ActsAsTaggableMigration < ActiveRecord::Migration
+ def self.up
+ create_table :tags do |t|
+ t.column :name, :string
+ end
+
+ create_table :taggings do |t|
+ t.column :tag_id, :integer
+ t.column :taggable_id, :integer
+
+ # You should make sure that the column created is
+ # long enough to store the required class names.
+ t.column :taggable_type, :string
+
+ t.column :created_at, :datetime
+ end
+
+ add_index :taggings, :tag_id
+ add_index :taggings, [:taggable_id, :taggable_type]
+ end
+
+ def self.down
+ drop_table :taggings
+ drop_table :tags
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/init.rb b/vendor/plugins/acts_as_taggable_on_steroids/init.rb
new file mode 100644
index 0000000..64505b9
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/init.rb
@@ -0,0 +1 @@
+require File.dirname(__FILE__) + '/lib/acts_as_taggable'
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/lib/acts_as_taggable.rb b/vendor/plugins/acts_as_taggable_on_steroids/lib/acts_as_taggable.rb
new file mode 100644
index 0000000..9502d7c
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/lib/acts_as_taggable.rb
@@ -0,0 +1,201 @@
+module ActiveRecord #:nodoc:
+ module Acts #:nodoc:
+ module Taggable #:nodoc:
+ def self.included(base)
+ base.extend(ClassMethods)
+ end
+
+ module ClassMethods
+ def acts_as_taggable
+ has_many :taggings, :as => :taggable, :dependent => :destroy, :include => :tag
+ has_many :tags, :through => :taggings
+
+ before_save :save_cached_tag_list
+ after_save :save_tags
+
+ include ActiveRecord::Acts::Taggable::InstanceMethods
+ extend ActiveRecord::Acts::Taggable::SingletonMethods
+
+ alias_method_chain :reload, :tag_list
+ end
+
+ def cached_tag_list_column_name
+ "cached_tag_list"
+ end
+
+ def set_cached_tag_list_column_name(value = nil, &block)
+ define_attr_method :cached_tag_list_column_name, value, &block
+ end
+ end
+
+ module SingletonMethods
+ # Pass either a tag string, or an array of strings or tags
+ #
+ # Options:
+ # :exclude - Find models that are not tagged with the given tags
+ # :match_all - Find models that match all of the given tags, not just one
+ # :conditions - A piece of SQL conditions to add to the query
+ def find_tagged_with(*args)
+ options = find_options_for_find_tagged_with(*args)
+ options.blank? ? [] : find(:all, options)
+ end
+
+ def find_options_for_find_tagged_with(tags, options = {})
+ tags = tags.is_a?(Array) ? TagList.new(tags.map(&:to_s)) : TagList.from(tags)
+ options = options.dup
+
+ return {} if tags.empty?
+
+ conditions = []
+ conditions << sanitize_sql(options.delete(:conditions)) if options[:conditions]
+
+ taggings_alias, tags_alias = "#{table_name}_taggings", "#{table_name}_tags"
+
+ if options.delete(:exclude)
+ conditions << <<-END
+ #{table_name}.id NOT IN
+ (SELECT #{Tagging.table_name}.taggable_id FROM #{Tagging.table_name}
+ INNER JOIN #{Tag.table_name} ON #{Tagging.table_name}.tag_id = #{Tag.table_name}.id
+ WHERE #{tags_condition(tags)} AND #{Tagging.table_name}.taggable_type = #{quote_value(base_class.name)})
+ END
+ else
+ if options.delete(:match_all)
+ conditions << <<-END
+ (SELECT COUNT(*) FROM #{Tagging.table_name}
+ INNER JOIN #{Tag.table_name} ON #{Tagging.table_name}.tag_id = #{Tag.table_name}.id
+ WHERE #{Tagging.table_name}.taggable_type = #{quote_value(base_class.name)} AND
+ taggable_id = #{table_name}.id AND
+ #{tags_condition(tags)}) = #{tags.size}
+ END
+ else
+ conditions << tags_condition(tags, tags_alias)
+ end
+ end
+
+ { :select => "DISTINCT #{table_name}.*",
+ :joins => "INNER JOIN #{Tagging.table_name} #{taggings_alias} ON #{taggings_alias}.taggable_id = #{table_name}.#{primary_key} AND #{taggings_alias}.taggable_type = #{quote_value(base_class.name)} " +
+ "INNER JOIN #{Tag.table_name} #{tags_alias} ON #{tags_alias}.id = #{taggings_alias}.tag_id",
+ :conditions => conditions.join(" AND ")
+ }.reverse_merge!(options)
+ end
+
+ # Calculate the tag counts for all tags.
+ #
+ # Options:
+ # :start_at - Restrict the tags to those created after a certain time
+ # :end_at - Restrict the tags to those created before a certain time
+ # :conditions - A piece of SQL conditions to add to the query
+ # :limit - The maximum number of tags to return
+ # :order - A piece of SQL to order by. Eg 'tags.count desc' or 'taggings.created_at desc'
+ # :at_least - Exclude tags with a frequency less than the given value
+ # :at_most - Exclude tags with a frequency greater than the given value
+ def tag_counts(options = {})
+ Tag.find(:all, find_options_for_tag_counts(options))
+ end
+
+ def find_options_for_tag_counts(options = {})
+ options.assert_valid_keys :start_at, :end_at, :conditions, :at_least, :at_most, :order, :limit
+ options = options.dup
+
+ scope = scope(:find)
+ start_at = sanitize_sql(["#{Tagging.table_name}.created_at >= ?", options.delete(:start_at)]) if options[:start_at]
+ end_at = sanitize_sql(["#{Tagging.table_name}.created_at <= ?", options.delete(:end_at)]) if options[:end_at]
+
+ conditions = [
+ "#{Tagging.table_name}.taggable_type = #{quote_value(base_class.name)}",
+ options.delete(:conditions),
+ scope && scope[:conditions],
+ start_at,
+ end_at
+ ]
+
+ conditions << type_condition unless descends_from_active_record?
+ conditions.compact!
+ conditions = conditions.join(' AND ')
+
+ joins = ["INNER JOIN #{Tagging.table_name} ON #{Tag.table_name}.id = #{Tagging.table_name}.tag_id"]
+ joins << "INNER JOIN #{table_name} ON #{table_name}.#{primary_key} = #{Tagging.table_name}.taggable_id"
+ joins << scope[:joins] if scope && scope[:joins]
+
+ at_least = sanitize_sql(['COUNT(*) >= ?', options.delete(:at_least)]) if options[:at_least]
+ at_most = sanitize_sql(['COUNT(*) <= ?', options.delete(:at_most)]) if options[:at_most]
+ having = [at_least, at_most].compact.join(' AND ')
+ group_by = "#{Tag.table_name}.id, #{Tag.table_name}.name HAVING COUNT(*) > 0"
+ group_by << " AND #{having}" unless having.blank?
+
+ { :select => "#{Tag.table_name}.id, #{Tag.table_name}.name, COUNT(*) AS count",
+ :joins => joins.join(" "),
+ :conditions => conditions,
+ :group => group_by
+ }.reverse_merge!(options)
+ end
+
+ def caching_tag_list?
+ column_names.include?(cached_tag_list_column_name)
+ end
+
+ private
+ def tags_condition(tags, table_name = Tag.table_name)
+ condition = tags.map { |t| sanitize_sql(["#{table_name}.name LIKE ?", t]) }.join(" OR ")
+ "(" + condition + ")"
+ end
+ end
+
+ module InstanceMethods
+ def tag_list
+ return @tag_list if @tag_list
+
+ if self.class.caching_tag_list? and !(cached_value = send(self.class.cached_tag_list_column_name)).nil?
+ @tag_list = TagList.from(cached_value)
+ else
+ @tag_list = TagList.new(*tags.map(&:name))
+ end
+ end
+
+ def tag_list=(value)
+ @tag_list = TagList.from(value)
+ end
+
+ def save_cached_tag_list
+ if self.class.caching_tag_list?
+ self[self.class.cached_tag_list_column_name] = tag_list.to_s
+ end
+ end
+
+ def save_tags
+ return unless @tag_list
+
+ new_tag_names = @tag_list - tags.map(&:name)
+ old_tags = tags.reject { |tag| @tag_list.include?(tag.name) }
+
+ self.class.transaction do
+ if old_tags.any?
+ taggings.find(:all, :conditions => ["tag_id IN (?)", old_tags.map(&:id)]).each(&:destroy)
+ taggings.reset
+ end
+
+ new_tag_names.each do |new_tag_name|
+ tags << Tag.find_or_create_with_like_by_name(new_tag_name)
+ end
+ end
+
+ true
+ end
+
+ # Calculate the tag counts for the tags used by this model.
+ #
+ # The possible options are the same as the tag_counts class method, excluding :conditions.
+ def tag_counts(options = {})
+ self.class.tag_counts({ :conditions => self.class.send(:tags_condition, tag_list) }.reverse_merge!(options))
+ end
+
+ def reload_with_tag_list(*args) #:nodoc:
+ @tag_list = nil
+ reload_without_tag_list(*args)
+ end
+ end
+ end
+ end
+end
+
+ActiveRecord::Base.send(:include, ActiveRecord::Acts::Taggable)
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/lib/tag.rb b/vendor/plugins/acts_as_taggable_on_steroids/lib/tag.rb
new file mode 100644
index 0000000..91859d5
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/lib/tag.rb
@@ -0,0 +1,26 @@
+class Tag < ActiveRecord::Base
+ has_many :taggings
+
+ validates_presence_of :name
+ validates_uniqueness_of :name
+
+ cattr_accessor :destroy_unused
+ self.destroy_unused = false
+
+ # LIKE is used for cross-database case-insensitivity
+ def self.find_or_create_with_like_by_name(name)
+ find(:first, :conditions => ["name LIKE ?", name]) || create(:name => name)
+ end
+
+ def ==(object)
+ super || (object.is_a?(Tag) && name == object.name)
+ end
+
+ def to_s
+ name
+ end
+
+ def count
+ read_attribute(:count).to_i
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/lib/tag_counts_extension.rb b/vendor/plugins/acts_as_taggable_on_steroids/lib/tag_counts_extension.rb
new file mode 100644
index 0000000..a1d13b8
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/lib/tag_counts_extension.rb
@@ -0,0 +1,3 @@
+# Deprecated
+module TagCountsExtension #:nodoc:
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/lib/tag_list.rb b/vendor/plugins/acts_as_taggable_on_steroids/lib/tag_list.rb
new file mode 100644
index 0000000..e840432
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/lib/tag_list.rb
@@ -0,0 +1,85 @@
+class TagList < Array
+ cattr_accessor :delimiter
+ self.delimiter = ','
+
+ def initialize(*args)
+ add(*args)
+ end
+
+ # Add tags to the tag_list. Duplicate or blank tags will be ignored.
+ #
+ # tag_list.add("Fun", "Happy")
+ #
+ # Use the <tt>:parse</tt> option to add an unparsed tag string.
+ #
+ # tag_list.add("Fun, Happy", :parse => true)
+ def add(*names)
+ extract_and_apply_options!(names)
+ concat(names)
+ clean!
+ self
+ end
+
+ # Remove specific tags from the tag_list.
+ #
+ # tag_list.remove("Sad", "Lonely")
+ #
+ # Like #add, the <tt>:parse</tt> option can be used to remove multiple tags in a string.
+ #
+ # tag_list.remove("Sad, Lonely", :parse => true)
+ def remove(*names)
+ extract_and_apply_options!(names)
+ delete_if { |name| names.include?(name) }
+ self
+ end
+
+ # Transform the tag_list into a tag string suitable for edting in a form.
+ # The tags are joined with <tt>TagList.delimiter</tt> and quoted if necessary.
+ #
+ # tag_list = TagList.new("Round", "Square,Cube")
+ # tag_list.to_s # 'Round, "Square,Cube"'
+ def to_s
+ clean!
+
+ map do |name|
+ name.include?(delimiter) ? "\"#{name}\"" : name
+ end.join(delimiter.ends_with?(" ") ? delimiter : "#{delimiter} ")
+ end
+
+ private
+ # Remove whitespace, duplicates, and blanks.
+ def clean!
+ reject!(&:blank?)
+ map!(&:strip)
+ uniq!
+ end
+
+ def extract_and_apply_options!(args)
+ options = args.last.is_a?(Hash) ? args.pop : {}
+ options.assert_valid_keys :parse
+
+ if options[:parse]
+ args.map! { |a| self.class.from(a) }
+ end
+
+ args.flatten!
+ end
+
+ class << self
+ # Returns a new TagList using the given tag string.
+ #
+ # tag_list = TagList.from("One , Two, Three")
+ # tag_list # ["One", "Two", "Three"]
+ def from(string)
+ returning new do |tag_list|
+ string = string.to_s.dup
+
+ # Parse the quoted tags
+ string.gsub!(/"(.*?)"\s*#{delimiter}?\s*/) { tag_list << $1; "" }
+ string.gsub!(/'(.*?)'\s*#{delimiter}?\s*/) { tag_list << $1; "" }
+
+ tag_list.add(string.split(delimiter))
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/lib/tagging.rb b/vendor/plugins/acts_as_taggable_on_steroids/lib/tagging.rb
new file mode 100644
index 0000000..87bc44d
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/lib/tagging.rb
@@ -0,0 +1,12 @@
+class Tagging < ActiveRecord::Base #:nodoc:
+ belongs_to :tag
+ belongs_to :taggable, :polymorphic => true
+
+ def after_destroy
+ if Tag.destroy_unused
+ if tag.taggings.count.zero?
+ tag.destroy
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/lib/tags_helper.rb b/vendor/plugins/acts_as_taggable_on_steroids/lib/tags_helper.rb
new file mode 100644
index 0000000..d5644b7
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/lib/tags_helper.rb
@@ -0,0 +1,13 @@
+module TagsHelper
+ # See the README for an example using tag_cloud.
+ def tag_cloud(tags, classes)
+ return if tags.empty?
+
+ max_count = tags.sort_by(&:count).last.count.to_f
+
+ tags.each do |tag|
+ index = ((tag.count / max_count) * (classes.size - 1)).round
+ yield tag, classes[index]
+ end
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/abstract_unit.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/abstract_unit.rb
new file mode 100644
index 0000000..42e277a
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/abstract_unit.rb
@@ -0,0 +1,97 @@
+require 'test/unit'
+
+begin
+ require File.dirname(__FILE__) + '/../../../../config/environment'
+rescue LoadError
+ require 'rubygems'
+ gem 'activerecord'
+ gem 'actionpack'
+ require 'active_record'
+ require 'action_controller'
+end
+
+# Search for fixtures first
+fixture_path = File.dirname(__FILE__) + '/fixtures/'
+Dependencies.load_paths.insert(0, fixture_path)
+
+require 'active_record/fixtures'
+
+require File.dirname(__FILE__) + '/../lib/acts_as_taggable'
+require_dependency File.dirname(__FILE__) + '/../lib/tag_list'
+require_dependency File.dirname(__FILE__) + '/../lib/tags_helper'
+
+ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + '/debug.log')
+ActiveRecord::Base.configurations = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
+ActiveRecord::Base.establish_connection(ENV['DB'] || 'mysql')
+
+load(File.dirname(__FILE__) + '/schema.rb')
+
+Test::Unit::TestCase.fixture_path = fixture_path
+
+class Test::Unit::TestCase #:nodoc:
+ self.use_transactional_fixtures = true
+ self.use_instantiated_fixtures = false
+
+ def assert_equivalent(expected, actual, message = nil)
+ if expected.first.is_a?(ActiveRecord::Base)
+ assert_equal expected.sort_by(&:id), actual.sort_by(&:id), message
+ else
+ assert_equal expected.sort, actual.sort, message
+ end
+ end
+
+ def assert_tag_counts(tags, expected_values)
+ # Map the tag fixture names to real tag names
+ expected_values = expected_values.inject({}) do |hash, (tag, count)|
+ hash[tags(tag).name] = count
+ hash
+ end
+
+ tags.each do |tag|
+ value = expected_values.delete(tag.name)
+
+ assert_not_nil value, "Expected count for #{tag.name} was not provided"
+ assert_equal value, tag.count, "Expected value of #{value} for #{tag.name}, but was #{tag.count}"
+ end
+
+ unless expected_values.empty?
+ assert false, "The following tag counts were not present: #{expected_values.inspect}"
+ end
+ end
+
+ def assert_queries(num = 1)
+ $query_count = 0
+ yield
+ ensure
+ assert_equal num, $query_count, "#{$query_count} instead of #{num} queries were executed."
+ end
+
+ def assert_no_queries(&block)
+ assert_queries(0, &block)
+ end
+
+ # From Rails trunk
+ def assert_difference(expressions, difference = 1, message = nil, &block)
+ expression_evaluations = [expressions].flatten.collect{|expression| lambda { eval(expression, block.binding) } }
+
+ original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression.call }
+ yield
+ expression_evaluations.each_with_index do |expression, i|
+ assert_equal original_values[i] + difference, expression.call, message
+ end
+ end
+
+ def assert_no_difference(expressions, message = nil, &block)
+ assert_difference expressions, 0, message, &block
+ end
+end
+
+ActiveRecord::Base.connection.class.class_eval do
+ def execute_with_counting(sql, name = nil, &block)
+ $query_count ||= 0
+ $query_count += 1
+ execute_without_counting(sql, name, &block)
+ end
+
+ alias_method_chain :execute, :counting
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/acts_as_taggable_test.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/acts_as_taggable_test.rb
new file mode 100644
index 0000000..90ea3c4
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/acts_as_taggable_test.rb
@@ -0,0 +1,347 @@
+require File.dirname(__FILE__) + '/abstract_unit'
+
+class ActsAsTaggableOnSteroidsTest < Test::Unit::TestCase
+ fixtures :tags, :taggings, :posts, :users, :photos, :subscriptions, :magazines
+
+ def test_find_tagged_with
+ assert_equivalent [posts(:jonathan_sky), posts(:sam_flowers)], Post.find_tagged_with('"Very good"')
+ assert_equal Post.find_tagged_with('"Very good"'), Post.find_tagged_with(['Very good'])
+ assert_equal Post.find_tagged_with('"Very good"'), Post.find_tagged_with([tags(:good)])
+
+ assert_equivalent [photos(:jonathan_dog), photos(:sam_flower), photos(:sam_sky)], Photo.find_tagged_with('Nature')
+ assert_equal Photo.find_tagged_with('Nature'), Photo.find_tagged_with(['Nature'])
+ assert_equal Photo.find_tagged_with('Nature'), Photo.find_tagged_with([tags(:nature)])
+
+ assert_equivalent [photos(:jonathan_bad_cat), photos(:jonathan_dog), photos(:jonathan_questioning_dog)], Photo.find_tagged_with('"Crazy animal" Bad')
+ assert_equal Photo.find_tagged_with('"Crazy animal" Bad'), Photo.find_tagged_with(['Crazy animal', 'Bad'])
+ assert_equal Photo.find_tagged_with('"Crazy animal" Bad'), Photo.find_tagged_with([tags(:animal), tags(:bad)])
+ end
+
+ def test_find_tagged_with_nothing
+ assert_equal [], Post.find_tagged_with("")
+ assert_equal [], Post.find_tagged_with([])
+ end
+
+ def test_find_tagged_with_nonexistant_tags
+ assert_equal [], Post.find_tagged_with('ABCDEFG')
+ assert_equal [], Photo.find_tagged_with(['HIJKLM'])
+ assert_equal [], Photo.find_tagged_with([Tag.new(:name => 'unsaved tag')])
+ end
+
+ def test_find_tagged_with_match_all
+ assert_equivalent [photos(:jonathan_dog)], Photo.find_tagged_with('Crazy animal, "Nature"', :match_all => true)
+ end
+
+ def test_find_tagged_with_match_all_and_include
+ assert_equivalent [posts(:jonathan_sky), posts(:sam_flowers)], Post.find_tagged_with(['Very good', 'Nature'], :match_all => true, :include => :tags)
+ end
+
+ def test_find_tagged_with_conditions
+ assert_equal [], Post.find_tagged_with('"Very good", Nature', :conditions => '1=0')
+ end
+
+ def test_find_tagged_with_duplicates_options_hash
+ options = { :conditions => '1=1' }.freeze
+ assert_nothing_raised { Post.find_tagged_with("Nature", options) }
+ end
+
+ def test_find_tagged_with_exclusions
+ assert_equivalent [photos(:jonathan_questioning_dog), photos(:jonathan_bad_cat)], Photo.find_tagged_with("Nature", :exclude => true)
+ assert_equivalent [posts(:jonathan_grass), posts(:jonathan_rain), posts(:jonathan_cloudy), posts(:jonathan_still_cloudy)], Post.find_tagged_with("'Very good', Bad", :exclude => true)
+ end
+
+ def test_find_options_for_find_tagged_with_no_tags_returns_empty_hash
+ assert_equal Hash.new, Post.find_options_for_find_tagged_with("")
+ assert_equal Hash.new, Post.find_options_for_find_tagged_with([nil])
+ end
+
+ def test_find_options_for_find_tagged_with_leaves_arguments_unchanged
+ original_tags = photos(:jonathan_questioning_dog).tags.dup
+ Photo.find_options_for_find_tagged_with(photos(:jonathan_questioning_dog).tags)
+ assert_equal original_tags, photos(:jonathan_questioning_dog).tags
+ end
+
+ def test_find_options_for_find_tagged_with_respects_custom_table_name
+ Tagging.table_name = "categorisations"
+ Tag.table_name = "categories"
+
+ options = Photo.find_options_for_find_tagged_with("Hello")
+
+ assert_no_match(/ taggings /, options[:joins])
+ assert_no_match(/ tags /, options[:joins])
+
+ assert_match(/ categorisations /, options[:joins])
+ assert_match(/ categories /, options[:joins])
+ ensure
+ Tagging.table_name = "taggings"
+ Tag.table_name = "tags"
+ end
+
+ def test_include_tags_on_find_tagged_with
+ assert_nothing_raised do
+ Photo.find_tagged_with('Nature', :include => :tags)
+ Photo.find_tagged_with("Nature", :include => { :taggings => :tag })
+ end
+ end
+
+ def test_basic_tag_counts_on_class
+ assert_tag_counts Post.tag_counts, :good => 2, :nature => 7, :question => 1, :bad => 1
+ assert_tag_counts Photo.tag_counts, :good => 1, :nature => 3, :question => 1, :bad => 1, :animal => 3
+ end
+
+ def test_tag_counts_on_class_with_date_conditions
+ assert_tag_counts Post.tag_counts(:start_at => Date.new(2006, 8, 4)), :good => 1, :nature => 5, :question => 1, :bad => 1
+ assert_tag_counts Post.tag_counts(:end_at => Date.new(2006, 8, 6)), :good => 1, :nature => 4, :question => 1
+ assert_tag_counts Post.tag_counts(:start_at => Date.new(2006, 8, 5), :end_at => Date.new(2006, 8, 10)), :good => 1, :nature => 4, :bad => 1
+
+ assert_tag_counts Photo.tag_counts(:start_at => Date.new(2006, 8, 12), :end_at => Date.new(2006, 8, 19)), :good => 1, :nature => 2, :bad => 1, :question => 1, :animal => 3
+ end
+
+ def test_tag_counts_on_class_with_frequencies
+ assert_tag_counts Photo.tag_counts(:at_least => 2), :nature => 3, :animal => 3
+ assert_tag_counts Photo.tag_counts(:at_most => 2), :good => 1, :question => 1, :bad => 1
+ end
+
+ def test_tag_counts_on_class_with_frequencies_and_conditions
+ assert_tag_counts Photo.tag_counts(:at_least => 2, :conditions => '1=1'), :nature => 3, :animal => 3
+ end
+
+ def test_tag_counts_duplicates_options_hash
+ options = { :at_least => 2, :conditions => '1=1' }.freeze
+ assert_nothing_raised { Photo.tag_counts(options) }
+ end
+
+ def test_tag_counts_with_limit
+ assert_equal 2, Photo.tag_counts(:limit => 2).size
+ assert_equal 1, Post.tag_counts(:at_least => 4, :limit => 2).size
+ end
+
+ def test_tag_counts_with_limit_and_order
+ assert_equal [tags(:nature), tags(:good)], Post.tag_counts(:order => 'count desc', :limit => 2)
+ end
+
+ def test_tag_counts_on_association
+ assert_tag_counts users(:jonathan).posts.tag_counts, :good => 1, :nature => 5, :question => 1
+ assert_tag_counts users(:sam).posts.tag_counts, :good => 1, :nature => 2, :bad => 1
+
+ assert_tag_counts users(:jonathan).photos.tag_counts, :animal => 3, :nature => 1, :question => 1, :bad => 1
+ assert_tag_counts users(:sam).photos.tag_counts, :nature => 2, :good => 1
+ end
+
+ def test_tag_counts_on_association_with_options
+ assert_equal [], users(:jonathan).posts.tag_counts(:conditions => '1=0')
+ assert_tag_counts users(:jonathan).posts.tag_counts(:at_most => 2), :good => 1, :question => 1
+ end
+
+ def test_tag_counts_on_has_many_through
+ assert_tag_counts users(:jonathan).magazines.tag_counts, :good => 1
+ end
+
+ def test_tag_counts_respects_custom_table_names
+ Tagging.table_name = "categorisations"
+ Tag.table_name = "categories"
+
+ options = Photo.find_options_for_tag_counts(:start_at => 2.weeks.ago, :end_at => Date.today)
+ sql = options.values.join(' ')
+
+ assert_no_match /taggings/, sql
+ assert_no_match /tags/, sql
+
+ assert_match /categorisations/, sql
+ assert_match /categories/, sql
+ ensure
+ Tagging.table_name = "taggings"
+ Tag.table_name = "tags"
+ end
+
+ def test_tag_list_reader
+ assert_equivalent ["Very good", "Nature"], posts(:jonathan_sky).tag_list
+ assert_equivalent ["Bad", "Crazy animal"], photos(:jonathan_bad_cat).tag_list
+ end
+
+ def test_reassign_tag_list
+ assert_equivalent ["Nature", "Question"], posts(:jonathan_rain).tag_list
+ posts(:jonathan_rain).taggings.reload
+
+ # Only an update of the posts table should be executed
+ assert_queries 1 do
+ posts(:jonathan_rain).update_attributes!(:tag_list => posts(:jonathan_rain).tag_list.to_s)
+ end
+
+ assert_equivalent ["Nature", "Question"], posts(:jonathan_rain).tag_list
+ end
+
+ def test_new_tags
+ assert_equivalent ["Very good", "Nature"], posts(:jonathan_sky).tag_list
+ posts(:jonathan_sky).update_attributes!(:tag_list => "#{posts(:jonathan_sky).tag_list}, One, Two")
+ assert_equivalent ["Very good", "Nature", "One", "Two"], posts(:jonathan_sky).tag_list
+ end
+
+ def test_remove_tag
+ assert_equivalent ["Very good", "Nature"], posts(:jonathan_sky).tag_list
+ posts(:jonathan_sky).update_attributes!(:tag_list => "Nature")
+ assert_equivalent ["Nature"], posts(:jonathan_sky).tag_list
+ end
+
+ def test_change_case_of_tags
+ original_tag_names = photos(:jonathan_questioning_dog).tag_list
+ photos(:jonathan_questioning_dog).update_attributes!(:tag_list => photos(:jonathan_questioning_dog).tag_list.to_s.upcase)
+
+ # The new tag list is not uppercase becuase the AR finders are not case-sensitive
+ # and find the old tags when re-tagging with the uppercase tags.
+ assert_equivalent original_tag_names, photos(:jonathan_questioning_dog).reload.tag_list
+ end
+
+ def test_remove_and_add_tag
+ assert_equivalent ["Very good", "Nature"], posts(:jonathan_sky).tag_list
+ posts(:jonathan_sky).update_attributes!(:tag_list => "Nature, Beautiful")
+ assert_equivalent ["Nature", "Beautiful"], posts(:jonathan_sky).tag_list
+ end
+
+ def test_tags_not_saved_if_validation_fails
+ assert_equivalent ["Very good", "Nature"], posts(:jonathan_sky).tag_list
+ assert !posts(:jonathan_sky).update_attributes(:tag_list => "One, Two", :text => "")
+ assert_equivalent ["Very good", "Nature"], Post.find(posts(:jonathan_sky).id).tag_list
+ end
+
+ def test_tag_list_accessors_on_new_record
+ p = Post.new(:text => 'Test')
+
+ assert p.tag_list.blank?
+ p.tag_list = "One, Two"
+ assert_equal "One, Two", p.tag_list.to_s
+ end
+
+ def test_clear_tag_list_with_nil
+ p = photos(:jonathan_questioning_dog)
+
+ assert !p.tag_list.blank?
+ assert p.update_attributes(:tag_list => nil)
+ assert p.tag_list.blank?
+
+ assert p.reload.tag_list.blank?
+ end
+
+ def test_clear_tag_list_with_string
+ p = photos(:jonathan_questioning_dog)
+
+ assert !p.tag_list.blank?
+ assert p.update_attributes(:tag_list => ' ')
+ assert p.tag_list.blank?
+
+ assert p.reload.tag_list.blank?
+ end
+
+ def test_tag_list_reset_on_reload
+ p = photos(:jonathan_questioning_dog)
+ assert !p.tag_list.blank?
+ p.tag_list = nil
+ assert p.tag_list.blank?
+ assert !p.reload.tag_list.blank?
+ end
+
+ def test_instance_tag_counts
+ assert_tag_counts posts(:jonathan_sky).tag_counts, :good => 2, :nature => 7
+ end
+
+ def test_tag_list_populated_when_cache_nil
+ assert_nil posts(:jonathan_sky).cached_tag_list
+ posts(:jonathan_sky).save!
+ assert_equal posts(:jonathan_sky).tag_list.to_s, posts(:jonathan_sky).cached_tag_list
+ end
+
+ def test_cached_tag_list_used
+ posts(:jonathan_sky).save!
+ posts(:jonathan_sky).reload
+
+ assert_no_queries do
+ assert_equivalent ["Very good", "Nature"], posts(:jonathan_sky).tag_list
+ end
+ end
+
+ def test_cached_tag_list_not_used
+ # Load fixture and column information
+ posts(:jonathan_sky).taggings(:reload)
+
+ assert_queries 1 do
+ # Tags association will be loaded
+ posts(:jonathan_sky).tag_list
+ end
+ end
+
+ def test_cached_tag_list_updated
+ assert_nil posts(:jonathan_sky).cached_tag_list
+ posts(:jonathan_sky).save!
+ assert_equivalent ["Very good", "Nature"], TagList.from(posts(:jonathan_sky).cached_tag_list)
+ posts(:jonathan_sky).update_attributes!(:tag_list => "None")
+
+ assert_equal 'None', posts(:jonathan_sky).cached_tag_list
+ assert_equal 'None', posts(:jonathan_sky).reload.cached_tag_list
+ end
+
+ def test_clearing_cached_tag_list
+ # Generate the cached tag list
+ posts(:jonathan_sky).save!
+
+ posts(:jonathan_sky).update_attributes!(:tag_list => "")
+ assert_equal "", posts(:jonathan_sky).cached_tag_list
+ end
+
+ def test_find_tagged_with_using_sti
+ special_post = SpecialPost.create!(:text => "Test", :tag_list => "Random")
+
+ assert_equal [special_post], SpecialPost.find_tagged_with("Random")
+ assert Post.find_tagged_with("Random").include?(special_post)
+ end
+
+ def test_tag_counts_using_sti
+ SpecialPost.create!(:text => "Test", :tag_list => "Nature")
+
+ assert_tag_counts SpecialPost.tag_counts, :nature => 1
+ end
+
+ def test_case_insensitivity
+ assert_difference "Tag.count", 1 do
+ Post.create!(:text => "Test", :tag_list => "one")
+ Post.create!(:text => "Test", :tag_list => "One")
+ end
+
+ assert_equal Post.find_tagged_with("Nature"), Post.find_tagged_with("nature")
+ end
+
+ def test_tag_not_destroyed_when_unused
+ posts(:jonathan_sky).tag_list.add("Random")
+ posts(:jonathan_sky).save!
+
+ assert_no_difference 'Tag.count' do
+ posts(:jonathan_sky).tag_list.remove("Random")
+ posts(:jonathan_sky).save!
+ end
+ end
+
+ def test_tag_destroyed_when_unused
+ Tag.destroy_unused = true
+
+ posts(:jonathan_sky).tag_list.add("Random")
+ posts(:jonathan_sky).save!
+
+ assert_difference 'Tag.count', -1 do
+ posts(:jonathan_sky).tag_list.remove("Random")
+ posts(:jonathan_sky).save!
+ end
+ ensure
+ Tag.destroy_unused = false
+ end
+end
+
+class ActsAsTaggableOnSteroidsFormTest < Test::Unit::TestCase
+ fixtures :tags, :taggings, :posts, :users, :photos
+
+ include ActionView::Helpers::FormHelper
+
+ def test_tag_list_contents
+ fields_for :post, posts(:jonathan_sky) do |f|
+ assert_match /Very good, Nature/, f.text_field(:tag_list)
+ end
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/database.yml b/vendor/plugins/acts_as_taggable_on_steroids/test/database.yml
new file mode 100644
index 0000000..47c3736
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/database.yml
@@ -0,0 +1,10 @@
+mysql:
+ :adapter: mysql
+ :host: localhost
+ :username: rails
+ :password:
+ :database: rails_plugin_test
+
+sqlite3:
+ :adapter: sqlite3
+ :database: ':memory:'
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/magazine.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/magazine.rb
new file mode 100644
index 0000000..554afe4
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/magazine.rb
@@ -0,0 +1,3 @@
+class Magazine < ActiveRecord::Base
+ acts_as_taggable
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/magazines.yml b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/magazines.yml
new file mode 100644
index 0000000..044ce6d
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/magazines.yml
@@ -0,0 +1,7 @@
+ruby:
+ id: 1
+ name: Ruby
+
+rails:
+ id: 2
+ name: Rails
\ No newline at end of file
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/photo.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/photo.rb
new file mode 100644
index 0000000..224957f
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/photo.rb
@@ -0,0 +1,8 @@
+class Photo < ActiveRecord::Base
+ acts_as_taggable
+
+ belongs_to :user
+end
+
+class SpecialPhoto < Photo
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/photos.yml b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/photos.yml
new file mode 100644
index 0000000..25a4118
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/photos.yml
@@ -0,0 +1,24 @@
+jonathan_dog:
+ id: 1
+ user_id: 1
+ title: A small dog
+
+jonathan_questioning_dog:
+ id: 2
+ user_id: 1
+ title: What does this dog want?
+
+jonathan_bad_cat:
+ id: 3
+ user_id: 1
+ title: Bad cat
+
+sam_flower:
+ id: 4
+ user_id: 2
+ title: Flower
+
+sam_sky:
+ id: 5
+ user_id: 2
+ title: Sky
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/post.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/post.rb
new file mode 100644
index 0000000..bee100a
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/post.rb
@@ -0,0 +1,7 @@
+class Post < ActiveRecord::Base
+ acts_as_taggable
+
+ belongs_to :user
+
+ validates_presence_of :text
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/posts.yml b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/posts.yml
new file mode 100644
index 0000000..79f50f5
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/posts.yml
@@ -0,0 +1,34 @@
+jonathan_sky:
+ id: 1
+ user_id: 1
+ text: The sky is particularly blue today
+
+jonathan_grass:
+ id: 2
+ user_id: 1
+ text: The grass seems very green
+
+jonathan_rain:
+ id: 3
+ user_id: 1
+ text: Why does the rain fall?
+
+jonathan_cloudy:
+ id: 4
+ user_id: 1
+ text: Is it cloudy?
+
+jonathan_still_cloudy:
+ id: 5
+ user_id: 1
+ text: Is it still cloudy?
+
+sam_ground:
+ id: 6
+ user_id: 2
+ text: The ground is looking too brown
+
+sam_flowers:
+ id: 7
+ user_id: 2
+ text: Why are the flowers dead?
\ No newline at end of file
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/special_post.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/special_post.rb
new file mode 100644
index 0000000..366a0d5
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/special_post.rb
@@ -0,0 +1,2 @@
+class SpecialPost < Post
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/subscription.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/subscription.rb
new file mode 100644
index 0000000..e975cb7
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/subscription.rb
@@ -0,0 +1,4 @@
+class Subscription < ActiveRecord::Base
+ belongs_to :user
+ belongs_to :magazine
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/subscriptions.yml b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/subscriptions.yml
new file mode 100644
index 0000000..1b5e68a
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/subscriptions.yml
@@ -0,0 +1,3 @@
+jonathan_rails:
+ user_id: 1
+ magazine_id: 1
\ No newline at end of file
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/taggings.yml b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/taggings.yml
new file mode 100644
index 0000000..01e599b
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/taggings.yml
@@ -0,0 +1,149 @@
+# Posts
+jonathan_sky_good:
+ id: 1
+ tag_id: 1
+ taggable_id: 1
+ taggable_type: Post
+ created_at: 2006-08-01
+
+jonathan_sky_nature:
+ id: 2
+ tag_id: 3
+ taggable_id: 1
+ taggable_type: Post
+ created_at: 2006-08-02
+
+jonathan_grass_nature:
+ id: 3
+ tag_id: 3
+ taggable_id: 2
+ taggable_type: Post
+ created_at: 2006-08-03
+
+jonathan_rain_question:
+ id: 4
+ tag_id: 4
+ taggable_id: 3
+ taggable_type: Post
+ created_at: 2006-08-04
+
+jonathan_rain_nature:
+ id: 5
+ tag_id: 3
+ taggable_id: 3
+ taggable_type: Post
+ created_at: 2006-08-05
+
+jonathan_cloudy_nature:
+ id: 6
+ tag_id: 3
+ taggable_id: 4
+ taggable_type: Post
+ created_at: 2006-08-06
+
+jonathan_still_cloudy_nature:
+ id: 7
+ tag_id: 3
+ taggable_id: 5
+ taggable_type: Post
+ created_at: 2006-08-07
+
+sam_ground_nature:
+ id: 8
+ tag_id: 3
+ taggable_id: 6
+ taggable_type: Post
+ created_at: 2006-08-08
+
+sam_ground_bad:
+ id: 9
+ tag_id: 2
+ taggable_id: 6
+ taggable_type: Post
+ created_at: 2006-08-09
+
+sam_flowers_good:
+ id: 10
+ tag_id: 1
+ taggable_id: 7
+ taggable_type: Post
+ created_at: 2006-08-10
+
+sam_flowers_nature:
+ id: 11
+ tag_id: 3
+ taggable_id: 7
+ taggable_type: Post
+ created_at: 2006-08-11
+
+# Photos
+jonathan_dog_animal:
+ id: 12
+ tag_id: 5
+ taggable_id: 1
+ taggable_type: Photo
+ created_at: 2006-08-12
+
+jonathan_dog_nature:
+ id: 13
+ tag_id: 3
+ taggable_id: 1
+ taggable_type: Photo
+ created_at: 2006-08-13
+
+jonathan_questioning_dog_animal:
+ id: 14
+ tag_id: 5
+ taggable_id: 2
+ taggable_type: Photo
+ created_at: 2006-08-14
+
+jonathan_questioning_dog_question:
+ id: 15
+ tag_id: 4
+ taggable_id: 2
+ taggable_type: Photo
+ created_at: 2006-08-15
+
+jonathan_bad_cat_bad:
+ id: 16
+ tag_id: 2
+ taggable_id: 3
+ taggable_type: Photo
+ created_at: 2006-08-16
+
+jonathan_bad_cat_animal:
+ id: 17
+ tag_id: 5
+ taggable_id: 3
+ taggable_type: Photo
+ created_at: 2006-08-17
+
+sam_flower_nature:
+ id: 18
+ tag_id: 3
+ taggable_id: 4
+ taggable_type: Photo
+ created_at: 2006-08-18
+
+sam_flower_good:
+ id: 19
+ tag_id: 1
+ taggable_id: 4
+ taggable_type: Photo
+ created_at: 2006-08-19
+
+sam_sky_nature:
+ id: 20
+ tag_id: 3
+ taggable_id: 5
+ taggable_type: Photo
+ created_at: 2006-08-20
+
+# Magazines
+ruby_good:
+ id: 50
+ tag_id: 1
+ taggable_id: 1
+ taggable_type: Magazine
+ created_at: 2007-08-25
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/tags.yml b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/tags.yml
new file mode 100644
index 0000000..b8f8367
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/tags.yml
@@ -0,0 +1,19 @@
+good:
+ id: 1
+ name: Very good
+
+bad:
+ id: 2
+ name: Bad
+
+nature:
+ id: 3
+ name: Nature
+
+question:
+ id: 4
+ name: Question
+
+animal:
+ id: 5
+ name: Crazy animal
\ No newline at end of file
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/user.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/user.rb
new file mode 100644
index 0000000..8c0f787
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/user.rb
@@ -0,0 +1,7 @@
+class User < ActiveRecord::Base
+ has_many :posts
+ has_many :photos
+
+ has_many :subscriptions
+ has_many :magazines, :through => :subscriptions
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/users.yml b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/users.yml
new file mode 100644
index 0000000..da94fea
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/fixtures/users.yml
@@ -0,0 +1,7 @@
+jonathan:
+ id: 1
+ name: Jonathan
+
+sam:
+ id: 2
+ name: Sam
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/schema.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/schema.rb
new file mode 100644
index 0000000..b190f6b
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/schema.rb
@@ -0,0 +1,37 @@
+ActiveRecord::Schema.define :version => 0 do
+ create_table :tags, :force => true do |t|
+ t.column :name, :string
+ end
+
+ create_table :taggings, :force => true do |t|
+ t.column :tag_id, :integer
+ t.column :taggable_id, :integer
+ t.column :taggable_type, :string
+ t.column :created_at, :datetime
+ end
+
+ create_table :users, :force => true do |t|
+ t.column :name, :string
+ end
+
+ create_table :posts, :force => true do |t|
+ t.column :text, :text
+ t.column :cached_tag_list, :string
+ t.column :user_id, :integer
+ t.column :type, :string
+ end
+
+ create_table :photos, :force => true do |t|
+ t.column :title, :string
+ t.column :user_id, :integer
+ end
+
+ create_table :subscriptions, :force => true do |t|
+ t.column :user_id, :integer
+ t.column :magazine_id, :integer
+ end
+
+ create_table :magazines, :force => true do |t|
+ t.column :name, :string
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/tag_list_test.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/tag_list_test.rb
new file mode 100644
index 0000000..54aa427
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/tag_list_test.rb
@@ -0,0 +1,101 @@
+require File.dirname(__FILE__) + '/abstract_unit'
+
+class TagListTest < Test::Unit::TestCase
+ def test_from_leaves_string_unchanged
+ tags = '"One ", Two'
+ original = tags.dup
+ TagList.from(tags)
+ assert_equal tags, original
+ end
+
+ def test_from_single_name
+ assert_equal %w(Fun), TagList.from("Fun")
+ assert_equal %w(Fun), TagList.from('"Fun"')
+ end
+
+ def test_from_blank
+ assert_equal [], TagList.from(nil)
+ assert_equal [], TagList.from("")
+ end
+
+ def test_from_single_quoted_tag
+ assert_equal ['with, comma'], TagList.from('"with, comma"')
+ end
+
+ def test_spaces_do_not_delineate
+ assert_equal ['A B', 'C'], TagList.from('A B, C')
+ end
+
+ def test_from_multiple_tags
+ assert_equivalent %w(Alpha Beta Delta Gamma), TagList.from("Alpha, Beta, Delta, Gamma")
+ end
+
+ def test_from_multiple_tags_with_quotes
+ assert_equivalent %w(Alpha Beta Delta Gamma), TagList.from('Alpha, "Beta", Gamma , "Delta"')
+ end
+
+ def test_from_with_single_quotes
+ assert_equivalent ['A B', 'C'], TagList.from("'A B', C")
+ end
+
+ def test_from_multiple_tags_with_quote_and_commas
+ assert_equivalent ['Alpha, Beta', 'Delta', 'Gamma, something'], TagList.from('"Alpha, Beta", Delta, "Gamma, something"')
+ end
+
+ def test_from_removes_white_space
+ assert_equivalent %w(Alpha Beta), TagList.from('" Alpha ", "Beta "')
+ assert_equivalent %w(Alpha Beta), TagList.from(' Alpha, Beta ')
+ end
+
+ def test_alternative_delimiter
+ TagList.delimiter = " "
+
+ assert_equal %w(One Two), TagList.from("One Two")
+ assert_equal ['One two', 'three', 'four'], TagList.from('"One two" three four')
+ ensure
+ TagList.delimiter = ","
+ end
+
+ def test_duplicate_tags_removed
+ assert_equal %w(One), TagList.from("One, One")
+ end
+
+ def test_to_s_with_commas
+ assert_equal "Question, Crazy Animal", TagList.new("Question", "Crazy Animal").to_s
+ end
+
+ def test_to_s_with_alternative_delimiter
+ TagList.delimiter = " "
+
+ assert_equal '"Crazy Animal" Question', TagList.new("Crazy Animal", "Question").to_s
+ ensure
+ TagList.delimiter = ","
+ end
+
+ def test_add
+ tag_list = TagList.new("One")
+ assert_equal %w(One), tag_list
+
+ assert_equal %w(One Two), tag_list.add("Two")
+ assert_equal %w(One Two Three), tag_list.add(["Three"])
+ end
+
+ def test_remove
+ tag_list = TagList.new("One", "Two")
+ assert_equal %w(Two), tag_list.remove("One")
+ assert_equal %w(), tag_list.remove(["Two"])
+ end
+
+ def test_new_with_parsing
+ assert_equal %w(One Two), TagList.new("One, Two", :parse => true)
+ end
+
+ def test_add_with_parsing
+ assert_equal %w(One Two), TagList.new.add("One, Two", :parse => true)
+ end
+
+ def test_remove_with_parsing
+ tag_list = TagList.from("Three, Four, Five")
+ assert_equal %w(Four), tag_list.remove("Three, Five", :parse => true)
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/tag_test.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/tag_test.rb
new file mode 100644
index 0000000..4ca577d
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/tag_test.rb
@@ -0,0 +1,34 @@
+require File.dirname(__FILE__) + '/abstract_unit'
+
+class TagTest < Test::Unit::TestCase
+ fixtures :tags, :taggings, :users, :photos, :posts
+
+ def test_name_required
+ t = Tag.create
+ assert_match /blank/, t.errors[:name].to_s
+ end
+
+ def test_name_unique
+ t = Tag.create!(:name => "My tag")
+ duplicate = t.clone
+
+ assert !duplicate.save
+ assert_match /taken/, duplicate.errors[:name].to_s
+ end
+
+ def test_taggings
+ assert_equivalent [taggings(:jonathan_sky_good), taggings(:sam_flowers_good), taggings(:sam_flower_good), taggings(:ruby_good)], tags(:good).taggings
+ assert_equivalent [taggings(:sam_ground_bad), taggings(:jonathan_bad_cat_bad)], tags(:bad).taggings
+ end
+
+ def test_to_s
+ assert_equal tags(:good).name, tags(:good).to_s
+ end
+
+ def test_equality
+ assert_equal tags(:good), tags(:good)
+ assert_equal Tag.find(1), Tag.find(1)
+ assert_equal Tag.new(:name => 'A'), Tag.new(:name => 'A')
+ assert_not_equal Tag.new(:name => 'A'), Tag.new(:name => 'B')
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/tagging_test.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/tagging_test.rb
new file mode 100644
index 0000000..172b8e2
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/tagging_test.rb
@@ -0,0 +1,13 @@
+require File.dirname(__FILE__) + '/abstract_unit'
+
+class TaggingTest < Test::Unit::TestCase
+ fixtures :tags, :taggings, :posts
+
+ def test_tag
+ assert_equal tags(:good), taggings(:jonathan_sky_good).tag
+ end
+
+ def test_taggable
+ assert_equal posts(:jonathan_sky), taggings(:jonathan_sky_good).taggable
+ end
+end
diff --git a/vendor/plugins/acts_as_taggable_on_steroids/test/tags_helper_test.rb b/vendor/plugins/acts_as_taggable_on_steroids/test/tags_helper_test.rb
new file mode 100644
index 0000000..9c3ce53
--- /dev/null
+++ b/vendor/plugins/acts_as_taggable_on_steroids/test/tags_helper_test.rb
@@ -0,0 +1,28 @@
+require File.dirname(__FILE__) + '/abstract_unit'
+
+class TagsHelperTest < Test::Unit::TestCase
+ fixtures :tags, :taggings, :posts
+
+ include TagsHelper
+
+ def test_tag_cloud
+ cloud_elements = []
+
+ tag_cloud Post.tag_counts, %w(css1 css2 css3 css4) do |tag, css_class|
+ cloud_elements << [tag, css_class]
+ end
+
+ assert_equal [
+ [tags(:good), "css2"],
+ [tags(:bad), "css1"],
+ [tags(:nature), "css4"],
+ [tags(:question), "css1"]
+ ], cloud_elements
+ end
+
+ def test_tag_cloud_when_no_tags
+ tag_cloud SpecialPost.tag_counts, %w(css1) do
+ assert false, "tag_cloud should not yield"
+ end
+ end
+end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
776f940d2184b74fa323f4982992f97c0a0651f9
|
Putting real feeds in as fixtures
|
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
index b71f0ca..46befd0 100644
--- a/spec/fixtures/feeds.yml
+++ b/spec/fixtures/feeds.yml
@@ -1,11 +1,84 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+global_giving:
+ name: GlobalGiving
+ url: http://feeds.feedburner.com/GlobalGivingProjects
+ last_accessed: <%= 1.day.ago %>
-one:
- name: MyString
- url: MyString
- last_accessed: 2008-03-09 16:12:49
+pledge_bank:
+ name: PledgeBank
+ url: http://everywhere.en-gb.pledgebank.com/rss/list
+ last_accessed: <%= 1.day.ago %>
-two:
- name: MyString
- url: MyString
- last_accessed: 2008-03-09 16:12:49
+change_org_giving:
+ name: Change.org Giving Networks
+ url: http://www.change.org/giving_networks/rss
+ last_accessed: <%= 1.day.ago %>
+
+change_org_canges:
+ name: Change.org Changes
+ url: http://www.change.org/changes/rss
+ last_accessed: <%= 1.day.ago %>
+
+razoo_acts:
+ name: Razoo Acts
+ url: http://beta.razoo.com/browse/acts?sort=new.d&filter=ne&format=xml
+ last_accessed: <%= 1.day.ago %>
+
+razoo_goals:
+ name: Razoo Goals
+ url: http://beta.razoo.com/browse/goals?sort=new.d&format=xml
+ last_accessed: <%= 1.day.ago %>
+
+democracy_in_action:
+ name: DemocracyinAction
+ url: http://salsa.democracyinaction.org/dia/network/pfp.jsp
+ last_accessed: <%= 1.day.ago %>
+
+care_2_petitions:
+ name: Care2 Petitions
+ url: http://www.thepetitionsite.com/browse-petitions/rss
+ last_accessed: <%= 1.day.ago %>
+
+the_point:
+ name: ThePoint
+ url: https://www.thepoint.com/rss
+ last_accessed: <%= 1.day.ago %>
+
+give_meaning_proposals:
+ name: GiveMeaning Proposals
+ url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=proposals&sortby=DateAdded&dir=Desc&pagesize=50
+ last_accessed: <%= 1.day.ago %>
+
+give_meaning_projects:
+ name: GiveMeaning Projects
+ url: http://www.givemeaning.com/SaveAnything/SearchAssetsRSS.aspx?Community=%2fWorld&Cause=0&type=projects&sortby=DateAdded&dir=Desc&pagesize=50
+ last_accessed: <%= 1.day.ago %>
+
+changing_the_present:
+ name: ChangingthePresent New Drives
+ url: http://www.changingthepresent.com/drives/rss
+ last_accessed: <%= 1.day.ago %>
+
+fundable:
+ name: Fundable
+ url: http://www.fundable.org/search_rss?SearchableText=&portal_type%3Alist=GroupAction&review_state=public&review_state=private&sort_on=created&sort_order=descending
+ last_accessed: <%= 1.day.ago %>
+
+bring_light:
+ name: BringLight
+ url: http://www.bringlight.com/feeds/all
+ last_accessed: <%= 1.day.ago %>
+
+kiva:
+ name: Kiva
+ url: http://www.kiva.org/app.php?page=rss&action=businesses&status=fundRaising
+ last_accessed: <%= 1.day.ago %>
+
+six_degrees:
+ name: SixDegrees
+ url: http://www.networkforgood.org/pca/badgefeed.aspx
+ last_accessed: <%= 1.day.ago %>
+
+first_giving:
+ name: Firstgiving
+ url: http://feeds.firstgiving.com/rss/fundraisers/quickview.rss
+ last_accessed: <%= 1.day.ago %>
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
bc69357f7c7b8cb4b366839a51d4e802ff27ba41
|
Files from generating Feed model
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
new file mode 100644
index 0000000..f3ef100
--- /dev/null
+++ b/app/models/feed.rb
@@ -0,0 +1,2 @@
+class Feed < ActiveRecord::Base
+end
diff --git a/db/migrate/001_create_feeds.rb b/db/migrate/001_create_feeds.rb
new file mode 100644
index 0000000..b695185
--- /dev/null
+++ b/db/migrate/001_create_feeds.rb
@@ -0,0 +1,15 @@
+class CreateFeeds < ActiveRecord::Migration
+ def self.up
+ create_table :feeds do |t|
+ t.string :name
+ t.string :url
+ t.datetime :last_accessed
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :feeds
+ end
+end
diff --git a/spec/fixtures/feeds.yml b/spec/fixtures/feeds.yml
new file mode 100644
index 0000000..b71f0ca
--- /dev/null
+++ b/spec/fixtures/feeds.yml
@@ -0,0 +1,11 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+one:
+ name: MyString
+ url: MyString
+ last_accessed: 2008-03-09 16:12:49
+
+two:
+ name: MyString
+ url: MyString
+ last_accessed: 2008-03-09 16:12:49
diff --git a/spec/models/feed_spec.rb b/spec/models/feed_spec.rb
new file mode 100644
index 0000000..3275c35
--- /dev/null
+++ b/spec/models/feed_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe Feed do
+ before(:each) do
+ @feed = Feed.new
+ end
+
+ it "should be valid" do
+ @feed.should be_valid
+ end
+end
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
889dc89558a521ed5e501bc65f6f932f92aedd98
|
Ran script/generate rspec to get these
|
diff --git a/script/spec b/script/spec
new file mode 100755
index 0000000..d815565
--- /dev/null
+++ b/script/spec
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../vendor/plugins/rspec/lib"))
+require 'spec'
+exit ::Spec::Runner::CommandLine.run(::Spec::Runner::OptionParser.parse(ARGV, STDERR, STDOUT))
diff --git a/script/spec_server b/script/spec_server
new file mode 100755
index 0000000..3787a39
--- /dev/null
+++ b/script/spec_server
@@ -0,0 +1,102 @@
+#!/usr/bin/env ruby
+$LOAD_PATH.unshift File.dirname(__FILE__) + '/../../rspec/lib' # For svn
+$LOAD_PATH.unshift File.dirname(__FILE__) + '/../vendor/plugins/rspec/lib' # For rspec installed as plugin
+require 'rubygems'
+require 'drb/drb'
+require 'rbconfig'
+require 'spec'
+require 'optparse'
+
+# This is based on Florian Weber's TDDMate
+module Spec
+ module Runner
+ class RailsSpecServer
+ def run(argv, stderr, stdout)
+ $stdout = stdout
+ $stderr = stderr
+
+ base = ActiveRecord::Base
+ def base.clear_reloadable_connections!
+ active_connections.each do |name, conn|
+ if conn.requires_reloading?
+ conn.disconnect!
+ active_connections.delete(name)
+ end
+ end
+ end
+
+ if ActionController.const_defined?(:Dispatcher)
+ dispatcher = ::ActionController::Dispatcher.new($stdout)
+ dispatcher.cleanup_application(true)
+ elsif ::Dispatcher.respond_to?(:reset_application!)
+ ::Dispatcher.reset_application!
+ else
+ raise "Application reloading failed"
+ end
+ ::Dependencies.mechanism = :load
+ require_dependency('application.rb') unless Object.const_defined?(:ApplicationController)
+ load File.dirname(__FILE__) + '/../spec/spec_helper.rb'
+
+ ::Spec::Runner::CommandLine.run(
+ ::Spec::Runner::OptionParser.parse(
+ argv,
+ $stderr,
+ $stdout
+ )
+ )
+ end
+ end
+ end
+end
+puts "Loading Rails environment"
+
+ENV["RAILS_ENV"] = "test"
+require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
+require 'dispatcher'
+
+def restart_test_server
+ puts "restarting"
+ config = ::Config::CONFIG
+ ruby = File::join(config['bindir'], config['ruby_install_name']) + config['EXEEXT']
+ command_line = [ruby, $0, ARGV].flatten.join(' ')
+ exec(command_line)
+end
+
+def daemonize(pid_file = nil)
+ return yield if $DEBUG
+ pid = Process.fork{
+ Process.setsid
+ Dir.chdir(RAILS_ROOT)
+ trap("SIGINT"){ exit! 0 }
+ trap("SIGTERM"){ exit! 0 }
+ trap("SIGHUP"){ restart_test_server }
+ File.open("/dev/null"){|f|
+ STDERR.reopen f
+ STDIN.reopen f
+ STDOUT.reopen f
+ }
+ yield
+ }
+ puts "spec_server launched. (PID: %d)" % pid
+ File.open(pid_file,"w"){|f| f.puts pid } if pid_file
+ exit! 0
+end
+
+options = Hash.new
+opts = OptionParser.new
+opts.on("-d", "--daemon"){|v| options[:daemon] = true }
+opts.on("-p", "--pid PIDFILE"){|v| options[:pid] = v }
+opts.parse!(ARGV)
+
+puts "Ready"
+exec_server = lambda {
+ trap("USR2") { restart_test_server } if Signal.list.has_key?("USR2")
+ DRb.start_service("druby://localhost:8989", Spec::Runner::RailsSpecServer.new)
+ DRb.thread.join
+}
+
+if options[:daemon]
+ daemonize(options[:pid], &exec_server)
+else
+ exec_server.call
+end
diff --git a/spec/rcov.opts b/spec/rcov.opts
new file mode 100644
index 0000000..baf694c
--- /dev/null
+++ b/spec/rcov.opts
@@ -0,0 +1,2 @@
+--exclude "spec/*,gems/*"
+--rails
\ No newline at end of file
diff --git a/spec/spec.opts b/spec/spec.opts
new file mode 100644
index 0000000..d8c8db5
--- /dev/null
+++ b/spec/spec.opts
@@ -0,0 +1,6 @@
+--colour
+--format
+progress
+--loadby
+mtime
+--reverse
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
new file mode 100644
index 0000000..210d9d1
--- /dev/null
+++ b/spec/spec_helper.rb
@@ -0,0 +1,39 @@
+# This file is copied to ~/spec when you run 'ruby script/generate rspec'
+# from the project root directory.
+ENV["RAILS_ENV"] = "test"
+require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
+require 'spec'
+require 'spec/rails'
+
+Spec::Runner.configure do |config|
+ # If you're not using ActiveRecord you should remove these
+ # lines, delete config/database.yml and disable :active_record
+ # in your config/boot.rb
+ config.use_transactional_fixtures = true
+ config.use_instantiated_fixtures = false
+ config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
+
+ # == Fixtures
+ #
+ # You can declare fixtures for each example_group like this:
+ # describe "...." do
+ # fixtures :table_a, :table_b
+ #
+ # Alternatively, if you prefer to declare them only once, you can
+ # do so right here. Just uncomment the next line and replace the fixture
+ # names with your fixtures.
+ #
+ # config.global_fixtures = :table_a, :table_b
+ #
+ # If you declare global fixtures, be aware that they will be declared
+ # for all of your examples, even those that don't use them.
+ #
+ # == Mock Framework
+ #
+ # RSpec uses it's own mocking framework by default. If you prefer to
+ # use mocha, flexmock or RR, uncomment the appropriate line:
+ #
+ # config.mock_with :mocha
+ # config.mock_with :flexmock
+ # config.mock_with :rr
+end
diff --git a/stories/all.rb b/stories/all.rb
new file mode 100644
index 0000000..2e8f46a
--- /dev/null
+++ b/stories/all.rb
@@ -0,0 +1,4 @@
+dir = File.dirname(__FILE__)
+Dir[File.expand_path("#{dir}/**/*.rb")].uniq.each do |file|
+ require file
+end
\ No newline at end of file
diff --git a/stories/helper.rb b/stories/helper.rb
new file mode 100644
index 0000000..da7a13a
--- /dev/null
+++ b/stories/helper.rb
@@ -0,0 +1,3 @@
+ENV["RAILS_ENV"] = "test"
+require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
+require 'spec/rails/story_adapter'
\ No newline at end of file
|
cdb/socialactions-mashup-rssa-crawler-and-api
|
aa812ced98b7003e4c21341360f52c46de9d9fd2
|
Adding rspec_on_rails plugin
|
diff --git a/vendor/plugins/rspec_on_rails/MIT-LICENSE b/vendor/plugins/rspec_on_rails/MIT-LICENSE
new file mode 100644
index 0000000..239d8e7
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/MIT-LICENSE
@@ -0,0 +1,31 @@
+====================================================================
+== RSpec
+Copyright (c) 2005-2007 The RSpec Development Team
+====================================================================
+== ARTS
+Copyright (c) 2006 Kevin Clark, Jake Howerton
+====================================================================
+== ZenTest
+Copyright (c) 2001-2006 Ryan Davis, Eric Hodel, Zen Spider Software
+====================================================================
+== AssertSelect
+Copyright (c) 2006 Assaf Arkin
+====================================================================
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/vendor/plugins/rspec_on_rails/README b/vendor/plugins/rspec_on_rails/README
new file mode 100644
index 0000000..9008b8a
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/README
@@ -0,0 +1,3 @@
+See the rdoc for Spec::Rails for usage documentation.
+
+See ~/rspec/README for instructions on running rspec_on_rails' examples.
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/Rakefile b/vendor/plugins/rspec_on_rails/Rakefile
new file mode 100644
index 0000000..39b5d22
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/Rakefile
@@ -0,0 +1,9 @@
+require 'rake'
+require 'rake/rdoctask'
+
+desc 'Generate RDoc'
+rd = Rake::RDocTask.new do |rdoc|
+ rdoc.rdoc_dir = '../doc/output/rdoc-rails'
+ rdoc.options << '--title' << 'Spec::Rails' << '--line-numbers' << '--inline-source' << '--main' << 'Spec::Rails'
+ rdoc.rdoc_files.include('MIT-LICENSE', 'lib/**/*.rb')
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/CHANGES b/vendor/plugins/rspec_on_rails/generators/rspec/CHANGES
new file mode 100644
index 0000000..69f3709
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec/CHANGES
@@ -0,0 +1 @@
+Please refer to the CHANGES file for RSpec's core
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/rspec_generator.rb b/vendor/plugins/rspec_on_rails/generators/rspec/rspec_generator.rb
new file mode 100644
index 0000000..d5512e3
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec/rspec_generator.rb
@@ -0,0 +1,35 @@
+require 'rbconfig'
+
+# This generator bootstraps a Rails project for use with RSpec
+class RspecGenerator < Rails::Generator::Base
+ DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'],
+ Config::CONFIG['ruby_install_name'])
+
+ def initialize(runtime_args, runtime_options = {})
+ super
+ end
+
+ def manifest
+ record do |m|
+ script_options = { :chmod => 0755, :shebang => options[:shebang] == DEFAULT_SHEBANG ? nil : options[:shebang] }
+
+ m.directory 'spec'
+ m.template 'spec_helper.rb', 'spec/spec_helper.rb'
+ m.file 'spec.opts', 'spec/spec.opts'
+ m.file 'rcov.opts', 'spec/rcov.opts'
+ m.file 'script/spec_server', 'script/spec_server', script_options
+ m.file 'script/spec', 'script/spec', script_options
+
+ m.directory 'stories'
+ m.file 'all_stories.rb', 'stories/all.rb'
+ m.file 'stories_helper.rb', 'stories/helper.rb'
+ end
+ end
+
+protected
+
+ def banner
+ "Usage: #{$0} rspec"
+ end
+
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/templates/all_stories.rb b/vendor/plugins/rspec_on_rails/generators/rspec/templates/all_stories.rb
new file mode 100644
index 0000000..2e8f46a
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec/templates/all_stories.rb
@@ -0,0 +1,4 @@
+dir = File.dirname(__FILE__)
+Dir[File.expand_path("#{dir}/**/*.rb")].uniq.each do |file|
+ require file
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/templates/previous_failures.txt b/vendor/plugins/rspec_on_rails/generators/rspec/templates/previous_failures.txt
new file mode 100644
index 0000000..e69de29
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/templates/rcov.opts b/vendor/plugins/rspec_on_rails/generators/rspec/templates/rcov.opts
new file mode 100644
index 0000000..baf694c
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec/templates/rcov.opts
@@ -0,0 +1,2 @@
+--exclude "spec/*,gems/*"
+--rails
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/templates/script/spec b/vendor/plugins/rspec_on_rails/generators/rspec/templates/script/spec
new file mode 100644
index 0000000..d815565
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec/templates/script/spec
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../vendor/plugins/rspec/lib"))
+require 'spec'
+exit ::Spec::Runner::CommandLine.run(::Spec::Runner::OptionParser.parse(ARGV, STDERR, STDOUT))
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/templates/script/spec_server b/vendor/plugins/rspec_on_rails/generators/rspec/templates/script/spec_server
new file mode 100644
index 0000000..3787a39
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec/templates/script/spec_server
@@ -0,0 +1,102 @@
+#!/usr/bin/env ruby
+$LOAD_PATH.unshift File.dirname(__FILE__) + '/../../rspec/lib' # For svn
+$LOAD_PATH.unshift File.dirname(__FILE__) + '/../vendor/plugins/rspec/lib' # For rspec installed as plugin
+require 'rubygems'
+require 'drb/drb'
+require 'rbconfig'
+require 'spec'
+require 'optparse'
+
+# This is based on Florian Weber's TDDMate
+module Spec
+ module Runner
+ class RailsSpecServer
+ def run(argv, stderr, stdout)
+ $stdout = stdout
+ $stderr = stderr
+
+ base = ActiveRecord::Base
+ def base.clear_reloadable_connections!
+ active_connections.each do |name, conn|
+ if conn.requires_reloading?
+ conn.disconnect!
+ active_connections.delete(name)
+ end
+ end
+ end
+
+ if ActionController.const_defined?(:Dispatcher)
+ dispatcher = ::ActionController::Dispatcher.new($stdout)
+ dispatcher.cleanup_application(true)
+ elsif ::Dispatcher.respond_to?(:reset_application!)
+ ::Dispatcher.reset_application!
+ else
+ raise "Application reloading failed"
+ end
+ ::Dependencies.mechanism = :load
+ require_dependency('application.rb') unless Object.const_defined?(:ApplicationController)
+ load File.dirname(__FILE__) + '/../spec/spec_helper.rb'
+
+ ::Spec::Runner::CommandLine.run(
+ ::Spec::Runner::OptionParser.parse(
+ argv,
+ $stderr,
+ $stdout
+ )
+ )
+ end
+ end
+ end
+end
+puts "Loading Rails environment"
+
+ENV["RAILS_ENV"] = "test"
+require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
+require 'dispatcher'
+
+def restart_test_server
+ puts "restarting"
+ config = ::Config::CONFIG
+ ruby = File::join(config['bindir'], config['ruby_install_name']) + config['EXEEXT']
+ command_line = [ruby, $0, ARGV].flatten.join(' ')
+ exec(command_line)
+end
+
+def daemonize(pid_file = nil)
+ return yield if $DEBUG
+ pid = Process.fork{
+ Process.setsid
+ Dir.chdir(RAILS_ROOT)
+ trap("SIGINT"){ exit! 0 }
+ trap("SIGTERM"){ exit! 0 }
+ trap("SIGHUP"){ restart_test_server }
+ File.open("/dev/null"){|f|
+ STDERR.reopen f
+ STDIN.reopen f
+ STDOUT.reopen f
+ }
+ yield
+ }
+ puts "spec_server launched. (PID: %d)" % pid
+ File.open(pid_file,"w"){|f| f.puts pid } if pid_file
+ exit! 0
+end
+
+options = Hash.new
+opts = OptionParser.new
+opts.on("-d", "--daemon"){|v| options[:daemon] = true }
+opts.on("-p", "--pid PIDFILE"){|v| options[:pid] = v }
+opts.parse!(ARGV)
+
+puts "Ready"
+exec_server = lambda {
+ trap("USR2") { restart_test_server } if Signal.list.has_key?("USR2")
+ DRb.start_service("druby://localhost:8989", Spec::Runner::RailsSpecServer.new)
+ DRb.thread.join
+}
+
+if options[:daemon]
+ daemonize(options[:pid], &exec_server)
+else
+ exec_server.call
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/templates/spec.opts b/vendor/plugins/rspec_on_rails/generators/rspec/templates/spec.opts
new file mode 100644
index 0000000..d8c8db5
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec/templates/spec.opts
@@ -0,0 +1,6 @@
+--colour
+--format
+progress
+--loadby
+mtime
+--reverse
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/templates/spec_helper.rb b/vendor/plugins/rspec_on_rails/generators/rspec/templates/spec_helper.rb
new file mode 100644
index 0000000..210d9d1
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec/templates/spec_helper.rb
@@ -0,0 +1,39 @@
+# This file is copied to ~/spec when you run 'ruby script/generate rspec'
+# from the project root directory.
+ENV["RAILS_ENV"] = "test"
+require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
+require 'spec'
+require 'spec/rails'
+
+Spec::Runner.configure do |config|
+ # If you're not using ActiveRecord you should remove these
+ # lines, delete config/database.yml and disable :active_record
+ # in your config/boot.rb
+ config.use_transactional_fixtures = true
+ config.use_instantiated_fixtures = false
+ config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
+
+ # == Fixtures
+ #
+ # You can declare fixtures for each example_group like this:
+ # describe "...." do
+ # fixtures :table_a, :table_b
+ #
+ # Alternatively, if you prefer to declare them only once, you can
+ # do so right here. Just uncomment the next line and replace the fixture
+ # names with your fixtures.
+ #
+ # config.global_fixtures = :table_a, :table_b
+ #
+ # If you declare global fixtures, be aware that they will be declared
+ # for all of your examples, even those that don't use them.
+ #
+ # == Mock Framework
+ #
+ # RSpec uses it's own mocking framework by default. If you prefer to
+ # use mocha, flexmock or RR, uncomment the appropriate line:
+ #
+ # config.mock_with :mocha
+ # config.mock_with :flexmock
+ # config.mock_with :rr
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec/templates/stories_helper.rb b/vendor/plugins/rspec_on_rails/generators/rspec/templates/stories_helper.rb
new file mode 100644
index 0000000..da7a13a
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec/templates/stories_helper.rb
@@ -0,0 +1,3 @@
+ENV["RAILS_ENV"] = "test"
+require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
+require 'spec/rails/story_adapter'
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_controller/USAGE b/vendor/plugins/rspec_on_rails/generators/rspec_controller/USAGE
new file mode 100644
index 0000000..1546c32
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_controller/USAGE
@@ -0,0 +1,33 @@
+Description:
+ The rspec_controller generator creates stub specs and files for a new
+ controller and its views.
+
+ The generator takes a controller name and a list of views as arguments.
+ The controller name may be given in CamelCase or under_score and should
+ not be suffixed with 'Controller'. To create a controller within a
+ module, specify the controller name as 'module/controller'.
+
+ The generator creates stubs for a controller (and spec), a view (and spec)
+ for each view in the argument list, plus a helper.
+
+Example:
+ ./script/generate rspec_controller dog bark fetch
+ ...
+ create spec/controllers/dog_controller_spec.rb
+ create app/controllers/dog_controller.rb
+ create app/helpers/dog_helper.rb
+ create spec/views/dog/bark_view_spec.rb
+ create app/views/dog/bark.rhtml
+ create spec/views/dog/fetch_view_spec.rb
+ create app/views/dog/fetch.rhtml
+
+Modules Example:
+ ./script/generate rspec_controller 'pets/dog' bark fetch
+ ...
+ create spec/controllers/pets/dog_controller_spec.rb
+ create app/controllers/pets/dog_controller.rb
+ create app/helpers/pets/dog_helper.rb
+ create spec/views/pets/dog/bark_view_spec.rb
+ create app/views/pets/dog/bark.rhtml
+ create spec/views/pets/dog/fetch_view_spec.rb
+ create app/views/pets/dog/fetch.rhtml
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_controller/rspec_controller_generator.rb b/vendor/plugins/rspec_on_rails/generators/rspec_controller/rspec_controller_generator.rb
new file mode 100644
index 0000000..9334830
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_controller/rspec_controller_generator.rb
@@ -0,0 +1,49 @@
+require 'rails_generator/generators/components/controller/controller_generator'
+
+class RspecControllerGenerator < ControllerGenerator
+
+ def manifest
+ record do |m|
+ # Check for class naming collisions.
+ m.class_collisions class_path, "#{class_name}Controller", "#{class_name}Helper"
+
+ # Controller, helper, views, and spec directories.
+ m.directory File.join('app/controllers', class_path)
+ m.directory File.join('app/helpers', class_path)
+ m.directory File.join('app/views', class_path, file_name)
+ m.directory File.join('spec/controllers', class_path)
+ m.directory File.join('spec/helpers', class_path)
+ m.directory File.join('spec/views', class_path, file_name)
+
+ if Rails::VERSION::STRING < "2.0.0"
+ @default_file_extension = "rhtml"
+ else
+ @default_file_extension = "html.erb"
+ end
+
+ # Controller spec, class, and helper.
+ m.template 'controller_spec.rb',
+ File.join('spec/controllers', class_path, "#{file_name}_controller_spec.rb")
+
+ m.template 'helper_spec.rb',
+ File.join('spec/helpers', class_path, "#{file_name}_helper_spec.rb")
+
+ m.template 'controller:controller.rb',
+ File.join('app/controllers', class_path, "#{file_name}_controller.rb")
+
+ m.template 'controller:helper.rb',
+ File.join('app/helpers', class_path, "#{file_name}_helper.rb")
+
+ # Spec and view template for each action.
+ actions.each do |action|
+ m.template 'view_spec.rb',
+ File.join('spec/views', class_path, file_name, "#{action}.#{@default_file_extension}_spec.rb"),
+ :assigns => { :action => action, :model => file_name }
+ path = File.join('app/views', class_path, file_name, "#{action}.#{@default_file_extension}")
+ m.template "controller:view.#{@default_file_extension}",
+ path,
+ :assigns => { :action => action, :path => path }
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_controller/templates/controller_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_controller/templates/controller_spec.rb
new file mode 100644
index 0000000..e79549e
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_controller/templates/controller_spec.rb
@@ -0,0 +1,25 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper'
+
+describe <%= class_name %>Controller do
+
+<% if actions.empty? -%>
+ #Delete this example and add some real ones
+<% else -%>
+ #Delete these examples and add some real ones
+<% end -%>
+ it "should use <%= class_name %>Controller" do
+ controller.should be_an_instance_of(<%= class_name %>Controller)
+ end
+
+<% unless actions.empty? -%>
+<% for action in actions -%>
+
+ describe "GET '<%= action %>'" do
+ it "should be successful" do
+ get '<%= action %>'
+ response.should be_success
+ end
+ end
+<% end -%>
+<% end -%>
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_controller/templates/helper_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_controller/templates/helper_spec.rb
new file mode 100644
index 0000000..e9dabcd
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_controller/templates/helper_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper'
+
+describe <%= class_name %>Helper do
+
+ #Delete this example and add some real ones or delete this file
+ it "should include the <%= class_name %>Helper" do
+ included_modules = self.metaclass.send :included_modules
+ included_modules.should include(<%= class_name %>Helper)
+ end
+
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_controller/templates/view_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_controller/templates/view_spec.rb
new file mode 100644
index 0000000..4d9e7dc
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_controller/templates/view_spec.rb
@@ -0,0 +1,12 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper'
+
+describe "/<%= class_name.underscore %>/<%= action %>" do
+ before(:each) do
+ render '<%= class_name.underscore %>/<%= action %>'
+ end
+
+ #Delete this example and add some real ones or delete this file
+ it "should tell you where to find the file" do
+ response.should have_tag('p', /Find me in app\/views\/<%= class_name.underscore %>\/<%= action %>/)
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_model/USAGE b/vendor/plugins/rspec_on_rails/generators/rspec_model/USAGE
new file mode 100644
index 0000000..a7b7814
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_model/USAGE
@@ -0,0 +1,18 @@
+Description:
+ The rspec_model generator creates stubs for a new model.
+
+ The generator takes a model name as its argument. The model name may be
+ given in CamelCase or under_score and should not be suffixed with 'Model'.
+
+ The generator creates a model class in app/models, an RSpec spec in
+ spec/models, database fixtures in spec/fixtures/plural_name.yml, and a migration
+ in db/migrate.
+
+Example:
+ ./script/generate rspec_model Account
+
+ This will create an Account model:
+ Model: app/models/account.rb
+ Spec: spec/models/account_spec.rb
+ Fixtures: spec/fixtures/accounts.yml
+ Migration: db/migrate/XXX_add_accounts.rb
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_model/rspec_model_generator.rb b/vendor/plugins/rspec_on_rails/generators/rspec_model/rspec_model_generator.rb
new file mode 100644
index 0000000..7f5e349
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_model/rspec_model_generator.rb
@@ -0,0 +1,30 @@
+require 'rails_generator/generators/components/model/model_generator'
+
+class RspecModelGenerator < ModelGenerator
+
+ def manifest
+
+ record do |m|
+ # Check for class naming collisions.
+ m.class_collisions class_path, class_name
+
+ # Model, spec, and fixture directories.
+ m.directory File.join('app/models', class_path)
+ m.directory File.join('spec/models', class_path)
+ m.directory File.join('spec/fixtures', class_path)
+
+ # Model class, spec and fixtures.
+ m.template 'model:model.rb', File.join('app/models', class_path, "#{file_name}.rb")
+ m.template 'model:fixtures.yml', File.join('spec/fixtures', class_path, "#{table_name}.yml")
+ m.template 'model_spec.rb', File.join('spec/models', class_path, "#{file_name}_spec.rb")
+
+ unless options[:skip_migration]
+ m.migration_template 'model:migration.rb', 'db/migrate', :assigns => {
+ :migration_name => "Create#{class_name.pluralize.gsub(/::/, '')}"
+ }, :migration_file_name => "create_#{file_path.gsub(/\//, '_').pluralize}"
+ end
+
+ end
+ end
+
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_model/templates/model_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_model/templates/model_spec.rb
new file mode 100644
index 0000000..83aa88b
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_model/templates/model_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper'
+
+describe <%= class_name %> do
+ before(:each) do
+ @<%= file_name %> = <%= class_name %>.new
+ end
+
+ it "should be valid" do
+ @<%= file_name %>.should be_valid
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/rspec_scaffold_generator.rb b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/rspec_scaffold_generator.rb
new file mode 100644
index 0000000..0dab825
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/rspec_scaffold_generator.rb
@@ -0,0 +1,167 @@
+class RspecScaffoldGenerator < Rails::Generator::NamedBase
+ default_options :skip_migration => false
+
+ attr_reader :controller_name,
+ :controller_class_path,
+ :controller_file_path,
+ :controller_class_nesting,
+ :controller_class_nesting_depth,
+ :controller_class_name,
+ :controller_singular_name,
+ :controller_plural_name,
+ :resource_edit_path,
+ :default_file_extension
+ alias_method :controller_file_name, :controller_singular_name
+ alias_method :controller_table_name, :controller_plural_name
+
+ def initialize(runtime_args, runtime_options = {})
+ super
+
+ @controller_name = @name.pluralize
+
+ base_name, @controller_class_path, @controller_file_path, @controller_class_nesting, @controller_class_nesting_depth = extract_modules(@controller_name)
+ @controller_class_name_without_nesting, @controller_singular_name, @controller_plural_name = inflect_names(base_name)
+
+ if @controller_class_nesting.empty?
+ @controller_class_name = @controller_class_name_without_nesting
+ else
+ @controller_class_name = "#{@controller_class_nesting}::#{@controller_class_name_without_nesting}"
+ end
+
+ if Rails::VERSION::STRING < "2.0.0"
+ @resource_generator = "scaffold_resource"
+ @default_file_extension = "rhtml"
+ else
+ @resource_generator = "scaffold"
+ @default_file_extension = "html.erb"
+ end
+
+ if ActionController::Base.respond_to?(:resource_action_separator)
+ @resource_edit_path = "/edit"
+ else
+ @resource_edit_path = ";edit"
+ end
+ end
+
+ def manifest
+ record do |m|
+
+ # Check for class naming collisions.
+ m.class_collisions(controller_class_path, "#{controller_class_name}Controller", "#{controller_class_name}Helper")
+ m.class_collisions(class_path, "#{class_name}")
+
+ # Controller, helper, views, and spec directories.
+ m.directory(File.join('app/models', class_path))
+ m.directory(File.join('app/controllers', controller_class_path))
+ m.directory(File.join('app/helpers', controller_class_path))
+ m.directory(File.join('app/views', controller_class_path, controller_file_name))
+ m.directory(File.join('spec/controllers', controller_class_path))
+ m.directory(File.join('spec/models', class_path))
+ m.directory(File.join('spec/helpers', class_path))
+ m.directory File.join('spec/fixtures', class_path)
+ m.directory File.join('spec/views', controller_class_path, controller_file_name)
+
+ # Controller spec, class, and helper.
+ m.template 'rspec_scaffold:routing_spec.rb',
+ File.join('spec/controllers', controller_class_path, "#{controller_file_name}_routing_spec.rb")
+
+ m.template 'rspec_scaffold:controller_spec.rb',
+ File.join('spec/controllers', controller_class_path, "#{controller_file_name}_controller_spec.rb")
+
+ m.template "#{@resource_generator}:controller.rb",
+ File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb")
+
+ m.template 'rspec_scaffold:helper_spec.rb',
+ File.join('spec/helpers', class_path, "#{controller_file_name}_helper_spec.rb")
+
+ m.template "#{@resource_generator}:helper.rb",
+ File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb")
+
+ for action in scaffold_views
+ m.template(
+ "#{@resource_generator}:view_#{action}.#{@default_file_extension}",
+ File.join('app/views', controller_class_path, controller_file_name, "#{action}.#{default_file_extension}")
+ )
+ end
+
+ # Model class, unit test, and fixtures.
+ m.template 'model:model.rb', File.join('app/models', class_path, "#{file_name}.rb")
+ m.template 'model:fixtures.yml', File.join('spec/fixtures', class_path, "#{table_name}.yml")
+ m.template 'rspec_model:model_spec.rb', File.join('spec/models', class_path, "#{file_name}_spec.rb")
+
+ # View specs
+ m.template "rspec_scaffold:edit_erb_spec.rb",
+ File.join('spec/views', controller_class_path, controller_file_name, "edit.#{default_file_extension}_spec.rb")
+ m.template "rspec_scaffold:index_erb_spec.rb",
+ File.join('spec/views', controller_class_path, controller_file_name, "index.#{default_file_extension}_spec.rb")
+ m.template "rspec_scaffold:new_erb_spec.rb",
+ File.join('spec/views', controller_class_path, controller_file_name, "new.#{default_file_extension}_spec.rb")
+ m.template "rspec_scaffold:show_erb_spec.rb",
+ File.join('spec/views', controller_class_path, controller_file_name, "show.#{default_file_extension}_spec.rb")
+
+ unless options[:skip_migration]
+ m.migration_template(
+ 'model:migration.rb', 'db/migrate',
+ :assigns => {
+ :migration_name => "Create#{class_name.pluralize.gsub(/::/, '')}",
+ :attributes => attributes
+ },
+ :migration_file_name => "create_#{file_path.gsub(/\//, '_').pluralize}"
+ )
+ end
+
+ m.route_resources controller_file_name
+
+ end
+ end
+
+ protected
+ # Override with your own usage banner.
+ def banner
+ "Usage: #{$0} rspec_scaffold ModelName [field:type field:type]"
+ end
+
+ def add_options!(opt)
+ opt.separator ''
+ opt.separator 'Options:'
+ opt.on("--skip-migration",
+ "Don't generate a migration file for this model") { |v| options[:skip_migration] = v }
+ end
+
+ def scaffold_views
+ %w[ index show new edit ]
+ end
+
+ def model_name
+ class_name.demodulize
+ end
+end
+
+module Rails
+ module Generator
+ class GeneratedAttribute
+ def default_value
+ @default_value ||= case type
+ when :int, :integer then "\"1\""
+ when :float then "\"1.5\""
+ when :decimal then "\"9.99\""
+ when :datetime, :timestamp, :time then "Time.now"
+ when :date then "Date.today"
+ when :string then "\"MyString\""
+ when :text then "\"MyText\""
+ when :boolean then "false"
+ else
+ ""
+ end
+ end
+
+ def input_type
+ @input_type ||= case type
+ when :text then "textarea"
+ else
+ "input"
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/controller_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/controller_spec.rb
new file mode 100644
index 0000000..7481907
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/controller_spec.rb
@@ -0,0 +1,313 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper'
+
+describe <%= controller_class_name %>Controller do
+ describe "handling GET /<%= table_name %>" do
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>)
+ <%= class_name %>.stub!(:find).and_return([@<%= file_name %>])
+ end
+
+ def do_get
+ get :index
+ end
+
+ it "should be successful" do
+ do_get
+ response.should be_success
+ end
+
+ it "should render index template" do
+ do_get
+ response.should render_template('index')
+ end
+
+ it "should find all <%= table_name %>" do
+ <%= class_name %>.should_receive(:find).with(:all).and_return([@<%= file_name %>])
+ do_get
+ end
+
+ it "should assign the found <%= table_name %> for the view" do
+ do_get
+ assigns[:<%= table_name %>].should == [@<%= file_name %>]
+ end
+ end
+
+ describe "handling GET /<%= table_name %>.xml" do
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>, :to_xml => "XML")
+ <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
+ end
+
+ def do_get
+ @request.env["HTTP_ACCEPT"] = "application/xml"
+ get :index
+ end
+
+ it "should be successful" do
+ do_get
+ response.should be_success
+ end
+
+ it "should find all <%= table_name %>" do
+ <%= class_name %>.should_receive(:find).with(:all).and_return([@<%= file_name %>])
+ do_get
+ end
+
+ it "should render the found <%= table_name %> as xml" do
+ @<%= file_name %>.should_receive(:to_xml).and_return("XML")
+ do_get
+ response.body.should == "XML"
+ end
+ end
+
+ describe "handling GET /<%= table_name %>/1" do
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>)
+ <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
+ end
+
+ def do_get
+ get :show, :id => "1"
+ end
+
+ it "should be successful" do
+ do_get
+ response.should be_success
+ end
+
+ it "should render show template" do
+ do_get
+ response.should render_template('show')
+ end
+
+ it "should find the <%= file_name %> requested" do
+ <%= class_name %>.should_receive(:find).with("1").and_return(@<%= file_name %>)
+ do_get
+ end
+
+ it "should assign the found <%= file_name %> for the view" do
+ do_get
+ assigns[:<%= file_name %>].should equal(@<%= file_name %>)
+ end
+ end
+
+ describe "handling GET /<%= table_name %>/1.xml" do
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>, :to_xml => "XML")
+ <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
+ end
+
+ def do_get
+ @request.env["HTTP_ACCEPT"] = "application/xml"
+ get :show, :id => "1"
+ end
+
+ it "should be successful" do
+ do_get
+ response.should be_success
+ end
+
+ it "should find the <%= file_name %> requested" do
+ <%= class_name %>.should_receive(:find).with("1").and_return(@<%= file_name %>)
+ do_get
+ end
+
+ it "should render the found <%= file_name %> as xml" do
+ @<%= file_name %>.should_receive(:to_xml).and_return("XML")
+ do_get
+ response.body.should == "XML"
+ end
+ end
+
+ describe "handling GET /<%= table_name %>/new" do
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>)
+ <%= class_name %>.stub!(:new).and_return(@<%= file_name %>)
+ end
+
+ def do_get
+ get :new
+ end
+
+ it "should be successful" do
+ do_get
+ response.should be_success
+ end
+
+ it "should render new template" do
+ do_get
+ response.should render_template('new')
+ end
+
+ it "should create an new <%= file_name %>" do
+ <%= class_name %>.should_receive(:new).and_return(@<%= file_name %>)
+ do_get
+ end
+
+ it "should not save the new <%= file_name %>" do
+ @<%= file_name %>.should_not_receive(:save)
+ do_get
+ end
+
+ it "should assign the new <%= file_name %> for the view" do
+ do_get
+ assigns[:<%= file_name %>].should equal(@<%= file_name %>)
+ end
+ end
+
+ describe "handling GET /<%= table_name %>/1/edit" do
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>)
+ <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
+ end
+
+ def do_get
+ get :edit, :id => "1"
+ end
+
+ it "should be successful" do
+ do_get
+ response.should be_success
+ end
+
+ it "should render edit template" do
+ do_get
+ response.should render_template('edit')
+ end
+
+ it "should find the <%= file_name %> requested" do
+ <%= class_name %>.should_receive(:find).and_return(@<%= file_name %>)
+ do_get
+ end
+
+ it "should assign the found <%= class_name %> for the view" do
+ do_get
+ assigns[:<%= file_name %>].should equal(@<%= file_name %>)
+ end
+ end
+
+ describe "handling POST /<%= table_name %>" do
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>, :to_param => "1")
+ <%= class_name %>.stub!(:new).and_return(@<%= file_name %>)
+ end
+
+ describe "with successful save" do
+
+ def do_post
+ @<%= file_name %>.should_receive(:save).and_return(true)
+ post :create, :<%= file_name %> => {}
+ end
+
+ it "should create a new <%= file_name %>" do
+ <%= class_name %>.should_receive(:new).with({}).and_return(@<%= file_name %>)
+ do_post
+ end
+
+ it "should redirect to the new <%= file_name %>" do
+ do_post
+ response.should redirect_to(<%= table_name.singularize %>_url("1"))
+ end
+
+ end
+
+ describe "with failed save" do
+
+ def do_post
+ @<%= file_name %>.should_receive(:save).and_return(false)
+ post :create, :<%= file_name %> => {}
+ end
+
+ it "should re-render 'new'" do
+ do_post
+ response.should render_template('new')
+ end
+
+ end
+ end
+
+ describe "handling PUT /<%= table_name %>/1" do
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>, :to_param => "1")
+ <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
+ end
+
+ describe "with successful update" do
+
+ def do_put
+ @<%= file_name %>.should_receive(:update_attributes).and_return(true)
+ put :update, :id => "1"
+ end
+
+ it "should find the <%= file_name %> requested" do
+ <%= class_name %>.should_receive(:find).with("1").and_return(@<%= file_name %>)
+ do_put
+ end
+
+ it "should update the found <%= file_name %>" do
+ do_put
+ assigns(:<%= file_name %>).should equal(@<%= file_name %>)
+ end
+
+ it "should assign the found <%= file_name %> for the view" do
+ do_put
+ assigns(:<%= file_name %>).should equal(@<%= file_name %>)
+ end
+
+ it "should redirect to the <%= file_name %>" do
+ do_put
+ response.should redirect_to(<%= table_name.singularize %>_url("1"))
+ end
+
+ end
+
+ describe "with failed update" do
+
+ def do_put
+ @<%= file_name %>.should_receive(:update_attributes).and_return(false)
+ put :update, :id => "1"
+ end
+
+ it "should re-render 'edit'" do
+ do_put
+ response.should render_template('edit')
+ end
+
+ end
+ end
+
+ describe "handling DELETE /<%= table_name %>/1" do
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>, :destroy => true)
+ <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
+ end
+
+ def do_delete
+ delete :destroy, :id => "1"
+ end
+
+ it "should find the <%= file_name %> requested" do
+ <%= class_name %>.should_receive(:find).with("1").and_return(@<%= file_name %>)
+ do_delete
+ end
+
+ it "should call destroy on the found <%= file_name %>" do
+ @<%= file_name %>.should_receive(:destroy)
+ do_delete
+ end
+
+ it "should redirect to the <%= table_name %> list" do
+ do_delete
+ response.should redirect_to(<%= table_name %>_url)
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/edit_erb_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/edit_erb_spec.rb
new file mode 100644
index 0000000..931abf8
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/edit_erb_spec.rb
@@ -0,0 +1,25 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper'
+
+describe "/<%= table_name %>/edit.<%= default_file_extension %>" do
+ include <%= controller_class_name %>Helper
+
+ before do
+ @<%= file_name %> = mock_model(<%= class_name %>)
+<% for attribute in attributes -%>
+ @<%= file_name %>.stub!(:<%= attribute.name %>).and_return(<%= attribute.default_value %>)
+<% end -%>
+ assigns[:<%= file_name %>] = @<%= file_name %>
+ end
+
+ it "should render edit form" do
+ render "/<%= table_name %>/edit.<%= default_file_extension %>"
+
+ response.should have_tag("form[action=#{<%= file_name %>_path(@<%= file_name %>)}][method=post]") do
+<% for attribute in attributes -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
+ with_tag('<%= attribute.input_type -%>#<%= file_name %>_<%= attribute.name %>[name=?]', "<%= file_name %>[<%= attribute.name %>]")
+<% end -%><% end -%>
+ end
+ end
+end
+
+
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/helper_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/helper_spec.rb
new file mode 100644
index 0000000..85cf795
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/helper_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper'
+
+describe <%= controller_class_name %>Helper do
+
+ #Delete this example and add some real ones or delete this file
+ it "should include the <%= class_name %>Helper" do
+ included_modules = self.metaclass.send :included_modules
+ included_modules.should include(<%= controller_class_name %>Helper)
+ end
+
+end
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/index_erb_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/index_erb_spec.rb
new file mode 100644
index 0000000..9d61c6f
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/index_erb_spec.rb
@@ -0,0 +1,22 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper'
+
+describe "/<%= table_name %>/index.<%= default_file_extension %>" do
+ include <%= controller_class_name %>Helper
+
+ before(:each) do
+<% [98,99].each do |id| -%>
+ <%= file_name %>_<%= id %> = mock_model(<%= class_name %>)
+<% for attribute in attributes -%>
+ <%= file_name %>_<%= id %>.should_receive(:<%= attribute.name %>).and_return(<%= attribute.default_value %>)
+<% end -%><% end %>
+ assigns[:<%= table_name %>] = [<%= file_name %>_98, <%= file_name %>_99]
+ end
+
+ it "should render list of <%= table_name %>" do
+ render "/<%= table_name %>/index.<%= default_file_extension %>"
+<% for attribute in attributes -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
+ response.should have_tag("tr>td", <%= attribute.default_value %>, 2)
+<% end -%><% end -%>
+ end
+end
+
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/new_erb_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/new_erb_spec.rb
new file mode 100644
index 0000000..2ae085a
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/new_erb_spec.rb
@@ -0,0 +1,26 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper'
+
+describe "/<%= table_name %>/new.<%= default_file_extension %>" do
+ include <%= controller_class_name %>Helper
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>)
+ @<%= file_name %>.stub!(:new_record?).and_return(true)
+<% for attribute in attributes -%>
+ @<%= file_name %>.stub!(:<%= attribute.name %>).and_return(<%= attribute.default_value %>)
+<% end -%>
+ assigns[:<%= file_name %>] = @<%= file_name %>
+ end
+
+ it "should render new form" do
+ render "/<%= table_name %>/new.<%= default_file_extension %>"
+
+ response.should have_tag("form[action=?][method=post]", <%= table_name %>_path) do
+<% for attribute in attributes -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
+ with_tag("<%= attribute.input_type -%>#<%= file_name %>_<%= attribute.name %>[name=?]", "<%= file_name %>[<%= attribute.name %>]")
+<% end -%><% end -%>
+ end
+ end
+end
+
+
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/routing_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/routing_spec.rb
new file mode 100644
index 0000000..a6da049
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/routing_spec.rb
@@ -0,0 +1,61 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper'
+
+describe <%= controller_class_name %>Controller do
+ describe "route generation" do
+
+ it "should map { :controller => '<%= table_name %>', :action => 'index' } to /<%= table_name %>" do
+ route_for(:controller => "<%= table_name %>", :action => "index").should == "/<%= table_name %>"
+ end
+
+ it "should map { :controller => '<%= table_name %>', :action => 'new' } to /<%= table_name %>/new" do
+ route_for(:controller => "<%= table_name %>", :action => "new").should == "/<%= table_name %>/new"
+ end
+
+ it "should map { :controller => '<%= table_name %>', :action => 'show', :id => 1 } to /<%= table_name %>/1" do
+ route_for(:controller => "<%= table_name %>", :action => "show", :id => 1).should == "/<%= table_name %>/1"
+ end
+
+ it "should map { :controller => '<%= table_name %>', :action => 'edit', :id => 1 } to /<%= table_name %>/1<%= resource_edit_path %>" do
+ route_for(:controller => "<%= table_name %>", :action => "edit", :id => 1).should == "/<%= table_name %>/1<%= resource_edit_path %>"
+ end
+
+ it "should map { :controller => '<%= table_name %>', :action => 'update', :id => 1} to /<%= table_name %>/1" do
+ route_for(:controller => "<%= table_name %>", :action => "update", :id => 1).should == "/<%= table_name %>/1"
+ end
+
+ it "should map { :controller => '<%= table_name %>', :action => 'destroy', :id => 1} to /<%= table_name %>/1" do
+ route_for(:controller => "<%= table_name %>", :action => "destroy", :id => 1).should == "/<%= table_name %>/1"
+ end
+ end
+
+ describe "route recognition" do
+
+ it "should generate params { :controller => '<%= table_name %>', action => 'index' } from GET /<%= table_name %>" do
+ params_from(:get, "/<%= table_name %>").should == {:controller => "<%= table_name %>", :action => "index"}
+ end
+
+ it "should generate params { :controller => '<%= table_name %>', action => 'new' } from GET /<%= table_name %>/new" do
+ params_from(:get, "/<%= table_name %>/new").should == {:controller => "<%= table_name %>", :action => "new"}
+ end
+
+ it "should generate params { :controller => '<%= table_name %>', action => 'create' } from POST /<%= table_name %>" do
+ params_from(:post, "/<%= table_name %>").should == {:controller => "<%= table_name %>", :action => "create"}
+ end
+
+ it "should generate params { :controller => '<%= table_name %>', action => 'show', id => '1' } from GET /<%= table_name %>/1" do
+ params_from(:get, "/<%= table_name %>/1").should == {:controller => "<%= table_name %>", :action => "show", :id => "1"}
+ end
+
+ it "should generate params { :controller => '<%= table_name %>', action => 'edit', id => '1' } from GET /<%= table_name %>/1;edit" do
+ params_from(:get, "/<%= table_name %>/1<%= resource_edit_path %>").should == {:controller => "<%= table_name %>", :action => "edit", :id => "1"}
+ end
+
+ it "should generate params { :controller => '<%= table_name %>', action => 'update', id => '1' } from PUT /<%= table_name %>/1" do
+ params_from(:put, "/<%= table_name %>/1").should == {:controller => "<%= table_name %>", :action => "update", :id => "1"}
+ end
+
+ it "should generate params { :controller => '<%= table_name %>', action => 'destroy', id => '1' } from DELETE /<%= table_name %>/1" do
+ params_from(:delete, "/<%= table_name %>/1").should == {:controller => "<%= table_name %>", :action => "destroy", :id => "1"}
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/show_erb_spec.rb b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/show_erb_spec.rb
new file mode 100644
index 0000000..53de983
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/generators/rspec_scaffold/templates/show_erb_spec.rb
@@ -0,0 +1,22 @@
+require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper'
+
+describe "/<%= table_name %>/show.<%= default_file_extension %>" do
+ include <%= controller_class_name %>Helper
+
+ before(:each) do
+ @<%= file_name %> = mock_model(<%= class_name %>)
+<% for attribute in attributes -%>
+ @<%= file_name %>.stub!(:<%= attribute.name %>).and_return(<%= attribute.default_value %>)
+<% end -%>
+
+ assigns[:<%= file_name %>] = @<%= file_name %>
+ end
+
+ it "should render attributes in <p>" do
+ render "/<%= table_name %>/show.<%= default_file_extension %>"
+<% for attribute in attributes -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
+ response.should have_text(/<%= Regexp.escape(attribute.default_value)[1..-2]%>/)
+<% end -%><% end -%>
+ end
+end
+
diff --git a/vendor/plugins/rspec_on_rails/init.rb b/vendor/plugins/rspec_on_rails/init.rb
new file mode 100644
index 0000000..6262f03
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/init.rb
@@ -0,0 +1,9 @@
+# Placeholder to satisfy Rails.
+#
+# Do NOT add any require statements to this file. Doing
+# so will cause Rails to load this plugin all of the time.
+#
+# Running 'ruby script/generate rspec' will
+# generate spec/spec_helper.rb, which includes the necessary
+# require statements and configuration. This file should
+# be required by all of your spec files.
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/lib/autotest/discover.rb b/vendor/plugins/rspec_on_rails/lib/autotest/discover.rb
new file mode 100644
index 0000000..8e6968e
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/autotest/discover.rb
@@ -0,0 +1 @@
+# This needs to be here for >= ZenTest-3.9.0 to add this directory to the load path.
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/lib/autotest/rails_rspec.rb b/vendor/plugins/rspec_on_rails/lib/autotest/rails_rspec.rb
new file mode 100644
index 0000000..50594bf
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/autotest/rails_rspec.rb
@@ -0,0 +1,81 @@
+# (c) Copyright 2006 Nick Sieger <[email protected]>
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation files
+# (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, sublicense, and/or sell copies of the Software,
+# and to permit persons to whom the Software is furnished to do so,
+# subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+$:.push(*Dir["vendor/rails/*/lib"])
+
+require 'active_support'
+require 'autotest/rspec'
+
+Autotest.add_hook :initialize do |at|
+ %w{^config/ ^coverage/ ^db/ ^doc/ ^log/ ^public/ ^script ^vendor/rails ^vendor/plugins previous_failures.txt}.each do |exception|
+ at.add_exception(exception)
+ end
+
+ at.clear_mappings
+
+ at.add_mapping(%r%^(test|spec)/fixtures/(.*).yml$%) { |_, m|
+ ["spec/models/#{m[2].singularize}_spec.rb"] + at.files_matching(%r%^spec\/views\/#{m[2]}/.*_spec\.rb$%)
+ }
+ at.add_mapping(%r%^spec/(models|controllers|views|helpers|lib)/.*rb$%) { |filename, _|
+ filename
+ }
+ at.add_mapping(%r%^app/models/(.*)\.rb$%) { |_, m|
+ ["spec/models/#{m[1]}_spec.rb"]
+ }
+ at.add_mapping(%r%^app/views/(.*)$%) { |_, m|
+ at.files_matching %r%^spec/views/#{m[1]}_spec.rb$%
+ }
+ at.add_mapping(%r%^app/controllers/(.*)\.rb$%) { |_, m|
+ if m[1] == "application"
+ at.files_matching %r%^spec/controllers/.*_spec\.rb$%
+ else
+ ["spec/controllers/#{m[1]}_spec.rb"]
+ end
+ }
+ at.add_mapping(%r%^app/helpers/(.*)_helper\.rb$%) { |_, m|
+ if m[1] == "application" then
+ at.files_matching(%r%^spec/(views|helpers)/.*_spec\.rb$%)
+ else
+ ["spec/helpers/#{m[1]}_helper_spec.rb"] + at.files_matching(%r%^spec\/views\/#{m[1]}/.*_spec\.rb$%)
+ end
+ }
+ at.add_mapping(%r%^config/routes\.rb$%) {
+ at.files_matching %r%^spec/(controllers|views|helpers)/.*_spec\.rb$%
+ }
+ at.add_mapping(%r%^config/database\.yml$%) { |_, m|
+ at.files_matching %r%^spec/models/.*_spec\.rb$%
+ }
+ at.add_mapping(%r%^(spec/(spec_helper|shared/.*)|config/(boot|environment(s/test)?))\.rb$%) {
+ at.files_matching %r%^spec/(models|controllers|views|helpers)/.*_spec\.rb$%
+ }
+ at.add_mapping(%r%^lib/(.*)\.rb$%) { |_, m|
+ ["spec/lib/#{m[1]}_spec.rb"]
+ }
+end
+
+class Autotest::RailsRspec < Autotest::Rspec
+
+ def spec_command
+ "script/spec"
+ end
+
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails.rb
new file mode 100644
index 0000000..be8a6c4
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails.rb
@@ -0,0 +1,51 @@
+silence_warnings { RAILS_ENV = "test" }
+
+require 'application'
+require 'action_controller/test_process'
+require 'action_controller/integration'
+require 'active_record/fixtures' if defined?(ActiveRecord::Base)
+require 'test/unit'
+
+require 'spec'
+
+require 'spec/rails/extensions'
+require 'spec/rails/example'
+require 'spec/rails/version'
+require 'spec/rails/matchers'
+
+module Spec
+ # = Spec::Rails
+ #
+ # Spec::Rails (a.k.a. RSpec on Rails) is a Ruby on Rails plugin that allows you to drive the development
+ # of your RoR application using RSpec, a framework that aims to enable Example Driven Development
+ # in Ruby.
+ #
+ # == Features
+ #
+ # * Use RSpec to independently specify Rails Models, Views, Controllers and Helpers
+ # * Integrated fixture loading
+ # * Special generators for Resources, Models, Views and Controllers that generate Specs instead of Tests.
+ #
+ # == Vision
+ #
+ # For people for whom TDD is a brand new concept, the testing support built into Ruby on Rails
+ # is a huge leap forward. The fact that it is built right in is fantastic, and Ruby on Rails
+ # apps are generally much easier to maintain than they might have been without such support.
+ #
+ # For those of us coming from a history with TDD, and now BDD, the existing support presents some problems related to dependencies across specs. To that end, RSpec on Rails supports 4 types of specs. Weâve also built in first class mocking and stubbing support in order to break dependencies across these different concerns.
+ #
+ # == More Information
+ #
+ # See Spec::Rails::Runner for information about the different kinds of contexts
+ # you can use to spec the different Rails components
+ #
+ # See Spec::Rails::Expectations for information about Rails-specific expectations
+ # you can set on responses and models, etc.
+ #
+ # == License
+ #
+ # RSpec on Rails is licensed under the same license as RSpec itself,
+ # the MIT-LICENSE.
+ module Rails
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example.rb
new file mode 100644
index 0000000..64a72a9
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example.rb
@@ -0,0 +1,47 @@
+dir = File.dirname(__FILE__)
+
+require 'spec/rails/example/ivar_proxy'
+require 'spec/rails/example/assigns_hash_proxy'
+
+require "spec/rails/example/render_observer"
+require "spec/rails/example/rails_example_group"
+require "spec/rails/example/model_example_group"
+require "spec/rails/example/functional_example_group"
+require "spec/rails/example/controller_example_group"
+require "spec/rails/example/helper_example_group"
+require "spec/rails/example/view_example_group"
+
+module Spec
+ module Rails
+ # Spec::Rails::Example extends Spec::Example (RSpec's core Example module) to provide
+ # Rails-specific contexts for describing Rails Models, Views, Controllers and Helpers.
+ #
+ # == Model Examples
+ #
+ # These are the equivalent of unit tests in Rails' built in testing. Ironically (for the traditional TDD'er) these are the only specs that we feel should actually interact with the database.
+ #
+ # See Spec::Rails::Example::ModelExampleGroup
+ #
+ # == Controller Examples
+ #
+ # These align somewhat with functional tests in rails, except that they do not actually render views (though you can force rendering of views if you prefer). Instead of setting expectations about what goes on a page, you set expectations about what templates get rendered.
+ #
+ # See Spec::Rails::Example::ControllerExampleGroup
+ #
+ # == View Examples
+ #
+ # This is the other half of Rails functional testing. View specs allow you to set up assigns and render
+ # a template. By assigning mock model data, you can specify view behaviour with no dependency on a database
+ # or your real models.
+ #
+ # See Spec::Rails::Example::ViewExampleGroup
+ #
+ # == Helper Examples
+ #
+ # These let you specify directly methods that live in your helpers.
+ #
+ # See Spec::Rails::Example::HelperExampleGroup
+ module Example
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example/assigns_hash_proxy.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/assigns_hash_proxy.rb
new file mode 100644
index 0000000..1d121f7
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/assigns_hash_proxy.rb
@@ -0,0 +1,42 @@
+module Spec
+ module Rails
+ module Example
+ class AssignsHashProxy #:nodoc:
+ def initialize(object)
+ @object = object
+ end
+
+ def [](ivar)
+ if assigns.include?(ivar.to_s)
+ assigns[ivar.to_s]
+ elsif assigns.include?(ivar)
+ assigns[ivar]
+ else
+ nil
+ end
+ end
+
+ def []=(ivar, val)
+ assigns[ivar.to_s] = val
+ end
+
+ def delete(name)
+ assigns.delete(name.to_s)
+ end
+
+ def each(&block)
+ assigns.each &block
+ end
+
+ def has_key?(key)
+ assigns.key?(key.to_s)
+ end
+
+ protected
+ def assigns
+ @object.assigns
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example/controller_example_group.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/controller_example_group.rb
new file mode 100644
index 0000000..c0a7756
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/controller_example_group.rb
@@ -0,0 +1,255 @@
+module Spec
+ module Rails
+ module Example
+ # Controller Examples live in $RAILS_ROOT/spec/controllers/.
+ #
+ # Controller Examples use Spec::Rails::Example::ControllerExampleGroup, which supports running specs for
+ # Controllers in two modes, which represent the tension between the more granular
+ # testing common in TDD and the more high level testing built into
+ # rails. BDD sits somewhere in between: we want to a balance between
+ # specs that are close enough to the code to enable quick fault
+ # isolation and far enough away from the code to enable refactoring
+ # with minimal changes to the existing specs.
+ #
+ # == Isolation mode (default)
+ #
+ # No dependencies on views because none are ever rendered. The
+ # benefit of this mode is that can spec the controller completely
+ # independent of the view, allowing that responsibility to be
+ # handled later, or by somebody else. Combined w/ separate view
+ # specs, this also provides better fault isolation.
+ #
+ # == Integration mode
+ #
+ # To run in this mode, include the +integrate_views+ declaration
+ # in your controller context:
+ #
+ # describe ThingController do
+ # integrate_views
+ # ...
+ #
+ # In this mode, controller specs are run in the same way that
+ # rails functional tests run - one set of tests for both the
+ # controllers and the views. The benefit of this approach is that
+ # you get wider coverage from each spec. Experienced rails
+ # developers may find this an easier approach to begin with, however
+ # we encourage you to explore using the isolation mode and revel
+ # in its benefits.
+ #
+ # == Expecting Errors
+ #
+ # Rspec on Rails will raise errors that occur in controller actions.
+ # In contrast, Rails will swallow errors that are raised in controller
+ # actions and return an error code in the header. If you wish to override
+ # Rspec and have Rail's default behaviour,tell the controller to use
+ # rails error handling ...
+ #
+ # before(:each) do
+ # controller.use_rails_error_handling!
+ # end
+ #
+ # When using Rail's error handling, you can expect error codes in headers ...
+ #
+ # it "should return an error in the header" do
+ # response.should be_error
+ # end
+ #
+ # it "should return a 501" do
+ # response.response_code.should == 501
+ # end
+ #
+ # it "should return a 501" do
+ # response.code.should == "501"
+ # end
+ class ControllerExampleGroup < FunctionalExampleGroup
+ class << self
+
+ # Use this to instruct RSpec to render views in your controller examples (Integration Mode).
+ #
+ # describe ThingController do
+ # integrate_views
+ # ...
+ #
+ # See Spec::Rails::Example::ControllerExampleGroup for more information about
+ # Integration and Isolation modes.
+ def integrate_views
+ @integrate_views = true
+ end
+ def integrate_views? # :nodoc:
+ @integrate_views
+ end
+
+ # You MUST provide a controller_name within the context of
+ # your controller specs:
+ #
+ # describe "ThingController" do
+ # controller_name :thing
+ # ...
+ def controller_name(name)
+ @controller_class_name = "#{name}_controller".camelize
+ end
+ attr_accessor :controller_class_name # :nodoc:
+ end
+
+ before(:each) do
+ # Some Rails apps explicitly disable ActionMailer in environment.rb
+ if defined?(ActionMailer)
+ @deliveries = []
+ ActionMailer::Base.deliveries = @deliveries
+ end
+
+ unless @controller.class.ancestors.include?(ActionController::Base)
+ Spec::Expectations.fail_with <<-EOE
+ You have to declare the controller name in controller specs. For example:
+ describe "The ExampleController" do
+ controller_name "example" #invokes the ExampleController
+ end
+ EOE
+ end
+ @controller.metaclass.class_eval do
+ def controller_path #:nodoc:
+ self.class.name.underscore.gsub('_controller', '')
+ end
+ include ControllerInstanceMethods
+ end
+ @controller.integrate_views! if @integrate_views
+ @controller.session = session
+ end
+
+ attr_reader :response, :request, :controller
+
+ def initialize(defined_description, &implementation) #:nodoc:
+ super
+ controller_class_name = self.class.controller_class_name
+ if controller_class_name
+ @controller_class_name = controller_class_name.to_s
+ else
+ @controller_class_name = self.class.described_type.to_s
+ end
+ @integrate_views = self.class.integrate_views?
+ end
+
+ # Uses ActionController::Routing::Routes to generate
+ # the correct route for a given set of options.
+ # == Example
+ # route_for(:controller => 'registrations', :action => 'edit', :id => 1)
+ # => '/registrations/1;edit'
+ def route_for(options)
+ ensure_that_routes_are_loaded
+ ActionController::Routing::Routes.generate(options)
+ end
+
+ # Uses ActionController::Routing::Routes to parse
+ # an incoming path so the parameters it generates can be checked
+ # == Example
+ # params_from(:get, '/registrations/1;edit')
+ # => :controller => 'registrations', :action => 'edit', :id => 1
+ def params_from(method, path)
+ ensure_that_routes_are_loaded
+ ActionController::Routing::Routes.recognize_path(path, :method => method)
+ end
+
+ protected
+ def _controller_ivar_proxy
+ @controller_ivar_proxy ||= AssignsHashProxy.new @controller
+ end
+
+ private
+ def ensure_that_routes_are_loaded
+ ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
+ end
+
+ module ControllerInstanceMethods #:nodoc:
+ include Spec::Rails::Example::RenderObserver
+
+ # === render(options = nil, deprecated_status = nil, &block)
+ #
+ # This gets added to the controller's singleton meta class,
+ # allowing Controller Examples to run in two modes, freely switching
+ # from context to context.
+ def render(options=nil, deprecated_status=nil, &block)
+ unless block_given?
+ unless integrate_views?
+ @template.metaclass.class_eval do
+ define_method :file_exists? do
+ true
+ end
+ define_method :render_file do |*args|
+ @first_render ||= args[0]
+ end
+ end
+ end
+ end
+
+ if matching_message_expectation_exists(options)
+ expect_render_mock_proxy.render(options, &block)
+ @performed_render = true
+ else
+ unless matching_stub_exists(options)
+ super(options, deprecated_status, &block)
+ end
+ end
+ end
+
+ private
+ def matching_message_expectation_exists(options)
+ expect_render_mock_proxy.send(:__mock_proxy).send(:find_matching_expectation, :render, options)
+ end
+
+ def matching_stub_exists(options)
+ expect_render_mock_proxy.send(:__mock_proxy).send(:find_matching_method_stub, :render, options)
+ end
+
+ public
+ if self.respond_to?(:should_receive) && self.respond_to?(:stub!)
+ self.send :alias_method, :orig_should_receive, :should_receive
+ self.send :alias_method, :orig_stub!, :stub!
+ def raise_with_disable_message(old_method, new_method)
+ raise %Q|
+ controller.#{old_method}(:render) has been disabled because it
+ can often produce unexpected results. Instead, you should
+ use the following (before the action):
+
+ controller.#{new_method}(*args)
+
+ See the rdoc for #{new_method} for more information.
+ |
+ end
+ def should_receive(*args)
+ if args[0] == :render
+ raise_with_disable_message("should_receive", "expect_render")
+ else
+ orig_should_receive(*args)
+ end
+ end
+ def stub!(*args)
+ if args[0] == :render
+ raise_with_disable_message("stub!", "stub_render")
+ else
+ orig_stub!(*args)
+ end
+ end
+ end
+
+ def response(&block)
+ # NOTE - we're setting @update for the assert_select_spec - kinda weird, huh?
+ @update = block
+ @_response || @response
+ end
+
+ def integrate_views!
+ @integrate_views = true
+ end
+
+ private
+
+ def integrate_views?
+ @integrate_views
+ end
+ end
+
+ Spec::Example::ExampleGroupFactory.register(:controller, self)
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example/functional_example_group.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/functional_example_group.rb
new file mode 100644
index 0000000..2fa0f19
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/functional_example_group.rb
@@ -0,0 +1,66 @@
+module Spec
+ module Rails
+ module Example
+ class FunctionalExampleGroup < RailsExampleGroup
+ include ActionController::TestProcess
+ include ActionController::Assertions
+
+ attr_reader :request, :response
+ before(:each) do
+ @controller_class = Object.path2class @controller_class_name
+ raise "Can't determine controller class for #{@controller_class_name}" if @controller_class.nil?
+
+ @controller = @controller_class.new
+
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ def params
+ request.parameters
+ end
+
+ def flash
+ response.flash
+ end
+
+ def session
+ request.session
+ end
+
+ # :call-seq:
+ # assigns()
+ #
+ # Hash of instance variables to values that are made available to
+ # views. == Examples
+ #
+ # #in thing_controller.rb
+ # def new
+ # @thing = Thing.new
+ # end
+ #
+ # #in thing_controller_spec
+ # get 'new'
+ # assigns[:registration].should == Thing.new
+ #--
+ # NOTE - Even though docs only use assigns[:key] format, this supports
+ # assigns(:key) in order to avoid breaking old specs.
+ #++
+ def assigns(key = nil)
+ if key.nil?
+ @controller.assigns
+ _controller_ivar_proxy
+ else
+ @controller.assigns[key]
+ _controller_ivar_proxy[key]
+ end
+ end
+
+ protected
+ def _controller_ivar_proxy
+ @controller_ivar_proxy ||= IvarProxy.new @controller
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example/helper_example_group.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/helper_example_group.rb
new file mode 100644
index 0000000..10c1ab0
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/helper_example_group.rb
@@ -0,0 +1,82 @@
+module Spec
+ module Rails
+ module Example
+ # Helper Specs live in $RAILS_ROOT/spec/helpers/.
+ #
+ # Helper Specs use Spec::Rails::Example::HelperExampleGroup, which allows you to
+ # include your Helper directly in the context and write specs directly
+ # against its methods.
+ #
+ # HelperExampleGroup also includes the standard lot of ActionView::Helpers in case your
+ # helpers rely on any of those.
+ #
+ # == Example
+ #
+ # class ThingHelper
+ # def number_of_things
+ # Thing.count
+ # end
+ # end
+ #
+ # describe "ThingHelper example_group" do
+ # include ThingHelper
+ # it "should tell you the number of things" do
+ # Thing.should_receive(:count).and_return(37)
+ # number_of_things.should == 37
+ # end
+ # end
+ class HelperExampleGroup < FunctionalExampleGroup
+ class << self
+ # The helper name....
+ def helper_name(name=nil)
+ send :include, "#{name}_helper".camelize.constantize
+ end
+ end
+
+ # Reverse the load order so that custom helpers which
+ # are defined last are also loaded last.
+ ActionView::Base.included_modules.reverse.each do |mod|
+ include mod if mod.parents.include?(ActionView::Helpers)
+ end
+
+ before(:all) do
+ @controller_class_name = 'Spec::Rails::Example::HelperBehaviourController'
+ end
+
+ before(:each) do
+ @controller.request = @request
+ @controller.url = ActionController::UrlRewriter.new @request, {} # url_for
+
+ @flash = ActionController::Flash::FlashHash.new
+ session['flash'] = @flash
+
+ ActionView::Helpers::AssetTagHelper::reset_javascript_include_default
+ end
+
+ def flash
+ @flash
+ end
+
+ def eval_erb(text)
+ ERB.new(text).result(binding)
+ end
+
+
+ # TODO: BT - Helper Examples should proxy method_missing to a Rails View instance.
+ # When that is done, remove this method
+ def protect_against_forgery?
+ false
+ end
+
+ Spec::Example::ExampleGroupFactory.register(:helper, self)
+ end
+
+ class HelperBehaviourController < ApplicationController #:nodoc:
+ attr_accessor :request, :url
+
+ # Re-raise errors
+ def rescue_action(e); raise e; end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example/ivar_proxy.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/ivar_proxy.rb
new file mode 100644
index 0000000..bf9b790
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/ivar_proxy.rb
@@ -0,0 +1,62 @@
+##
+# A wrapper that allows instance variables to be manipulated using +[]+ and
+# +[]=+
+
+module Spec
+ module Rails
+ module Example
+ class IvarProxy #:nodoc:
+
+ ##
+ # Wraps +object+ allowing its instance variables to be manipulated.
+
+ def initialize(object)
+ @object = object
+ end
+
+ ##
+ # Retrieves +ivar+ from the wrapped object.
+
+ def [](ivar)
+ get_variable "@#{ivar}"
+ end
+
+ ##
+ # Sets +ivar+ to +val+ on the wrapped object.
+
+ def []=(ivar, val)
+ set_variable "@#{ivar}", val
+ end
+
+ def each
+ @object.instance_variables.each do |variable_full_name|
+ variable_name = variable_full_name[1...variable_full_name.length]
+ yield variable_name, get_variable(variable_full_name)
+ end
+ end
+
+ def delete(key)
+ var_name = "@#{key}"
+ if @object.instance_variables.include?(var_name)
+ @object.send(:remove_instance_variable, var_name)
+ else
+ return nil
+ end
+ end
+
+ def has_key?(key)
+ @object.instance_variables.include?("@#{key}")
+ end
+
+ protected
+ def get_variable(name)
+ @object.instance_variable_get name
+ end
+
+ def set_variable(name, value)
+ @object.instance_variable_set name, value
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example/model_example_group.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/model_example_group.rb
new file mode 100644
index 0000000..3bdab25
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/model_example_group.rb
@@ -0,0 +1,14 @@
+module Spec
+ module Rails
+ module Example
+ # Model examples live in $RAILS_ROOT/spec/models/.
+ #
+ # Model examples use Spec::Rails::Example::ModelExampleGroup, which
+ # provides support for fixtures and some custom expectations via extensions
+ # to ActiveRecord::Base.
+ class ModelExampleGroup < RailsExampleGroup
+ Spec::Example::ExampleGroupFactory.register(:model, self)
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example/rails_example_group.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/rails_example_group.rb
new file mode 100644
index 0000000..a3df05a
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/rails_example_group.rb
@@ -0,0 +1,68 @@
+require 'spec/interop/test'
+
+ActionView::Base.cache_template_extensions = false
+
+module Spec
+ module Rails
+ module Example
+ class RailsExampleGroup < Test::Unit::TestCase
+ # Rails >= r8570 uses setup/teardown_fixtures explicitly
+ before(:each) do
+ setup_fixtures if self.respond_to?(:setup_fixtures)
+ end
+ after(:each) do
+ teardown_fixtures if self.respond_to?(:teardown_fixtures)
+ end
+
+ include Spec::Rails::Matchers
+
+ @@model_id = 1000
+ # Creates a mock object instance for a +model_class+ with common
+ # methods stubbed out.
+ # Additional methods may be easily stubbed (via add_stubs) if +stubs+ is passed.
+ def mock_model(model_class, options_and_stubs = {})
+ # null = options_and_stubs.delete(:null_object)
+ # stubs = options_and_stubs
+ id = @@model_id
+ @@model_id += 1
+ options_and_stubs = {
+ :id => id,
+ :to_param => id.to_s,
+ :new_record? => false,
+ :errors => stub("errors", :count => 0)
+ }.merge(options_and_stubs)
+ m = mock("#{model_class.name}_#{id}", options_and_stubs)
+ m.send(:__mock_proxy).instance_eval <<-CODE
+ def @target.is_a?(other)
+ #{model_class}.ancestors.include?(other)
+ end
+ def @target.kind_of?(other)
+ #{model_class}.ancestors.include?(other)
+ end
+ def @target.instance_of?(other)
+ other == #{model_class}
+ end
+ def @target.class
+ #{model_class}
+ end
+ CODE
+ yield m if block_given?
+ m
+ end
+
+ #--
+ # TODO - Shouldn't this just be an extension of stub! ??
+ # - object.stub!(:method => return_value, :method2 => return_value2, :etc => etc)
+ #++
+ # Stubs methods on +object+ (if +object+ is a symbol or string a new mock
+ # with that name will be created). +stubs+ is a Hash of <tt>method=>value</tt>
+ def add_stubs(object, stubs = {}) #:nodoc:
+ m = [String, Symbol].index(object.class) ? mock(object.to_s) : object
+ stubs.each {|k,v| m.stub!(k).and_return(v)}
+ m
+ end
+ Spec::Example::ExampleGroupFactory.default(self)
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example/render_observer.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/render_observer.rb
new file mode 100644
index 0000000..285e8b6
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/render_observer.rb
@@ -0,0 +1,90 @@
+require 'spec/mocks'
+
+module Spec
+ module Rails
+ module Example
+ # Provides specialized mock-like behaviour for controller and view examples,
+ # allowing you to mock or stub calls to render with specific arguments while
+ # ignoring all other calls.
+ module RenderObserver
+
+ # Similar to mocking +render+ with the exception that calls to +render+ with
+ # any other options are passed on to the receiver (i.e. controller in
+ # controller examples, template in view examples).
+ #
+ # This is necessary because Rails uses the +render+ method on both
+ # controllers and templates as a dispatcher to render different kinds of
+ # things, sometimes resulting in many calls to the render method within one
+ # request. This approach makes it impossible to use a normal mock object, which
+ # is designed to observe all incoming messages with a given name.
+ #
+ # +expect_render+ is auto-verifying, so failures will be reported without
+ # requiring you to explicitly request verification.
+ #
+ # Also, +expect_render+ uses parts of RSpec's mock expectation framework. Because
+ # it wraps only a subset of the framework, using this will create no conflict with
+ # other mock frameworks if you choose to use them. Additionally, the object returned
+ # by expect_render is an RSpec mock object, which means that you can call any of the
+ # chained methods available in RSpec's mocks.
+ #
+ # == Controller Examples
+ #
+ # controller.expect_render(:partial => 'thing', :object => thing)
+ # controller.expect_render(:partial => 'thing', :collection => things).once
+ #
+ # controller.stub_render(:partial => 'thing', :object => thing)
+ # controller.stub_render(:partial => 'thing', :collection => things).twice
+ #
+ # == View Examples
+ #
+ # template.expect_render(:partial => 'thing', :object => thing)
+ # template.expect_render(:partial => 'thing', :collection => things)
+ #
+ # template.stub_render(:partial => 'thing', :object => thing)
+ # template.stub_render(:partial => 'thing', :collection => things)
+ #
+ def expect_render(opts={})
+ register_verify_after_each
+ expect_render_mock_proxy.should_receive(:render, :expected_from => caller(1)[0]).with(opts)
+ end
+
+ # This is exactly like expect_render, with the exception that the call to render will not
+ # be verified. Use this if you are trying to isolate your example from a complicated render
+ # operation but don't care whether it is called or not.
+ def stub_render(opts={})
+ register_verify_after_each
+ expect_render_mock_proxy.stub!(:render, :expected_from => caller(1)[0]).with(opts)
+ end
+
+ def verify_rendered # :nodoc:
+ expect_render_mock_proxy.rspec_verify
+ end
+
+ def unregister_verify_after_each #:nodoc:
+ proc = verify_rendered_proc
+ Spec::Example::ExampleGroup.remove_after(:each, &proc)
+ end
+
+ protected
+
+ def verify_rendered_proc #:nodoc:
+ template = self
+ @verify_rendered_proc ||= Proc.new do
+ template.verify_rendered
+ template.unregister_verify_after_each
+ end
+ end
+
+ def register_verify_after_each #:nodoc:
+ proc = verify_rendered_proc
+ Spec::Example::ExampleGroup.after(:each, &proc)
+ end
+
+ def expect_render_mock_proxy #:nodoc:
+ @expect_render_mock_proxy ||= Spec::Mocks::Mock.new("expect_render_mock_proxy")
+ end
+
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/example/view_example_group.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/view_example_group.rb
new file mode 100644
index 0000000..bbbf052
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/example/view_example_group.rb
@@ -0,0 +1,171 @@
+module Spec
+ module Rails
+ module Example
+ # View Examples live in $RAILS_ROOT/spec/views/.
+ #
+ # View Specs use Spec::Rails::Example::ViewExampleGroup,
+ # which provides access to views without invoking any of your controllers.
+ # See Spec::Rails::Expectations::Matchers for information about specific
+ # expectations that you can set on views.
+ #
+ # == Example
+ #
+ # describe "login/login" do
+ # before do
+ # render 'login/login'
+ # end
+ #
+ # it "should display login form" do
+ # response.should have_tag("form[action=/login]") do
+ # with_tag("input[type=text][name=email]")
+ # with_tag("input[type=password][name=password]")
+ # with_tag("input[type=submit][value=Login]")
+ # end
+ # end
+ # end
+ class ViewExampleGroup < FunctionalExampleGroup
+ before(:each) do
+ ensure_that_flash_and_session_work_properly
+ end
+
+ after(:each) do
+ ensure_that_base_view_path_is_not_set_across_example_groups
+ end
+
+ def initialize(defined_description, &implementation) #:nodoc:
+ super
+ @controller_class_name = "Spec::Rails::Example::ViewExampleGroupController"
+ end
+
+ def ensure_that_flash_and_session_work_properly #:nodoc:
+ @controller.send :initialize_template_class, @response
+ @controller.send :assign_shortcuts, @request, @response
+ @session = @controller.session
+ @controller.class.send :public, :flash
+ end
+
+ def ensure_that_base_view_path_is_not_set_across_example_groups #:nodoc:
+ ActionView::Base.base_view_path = nil
+ end
+
+ def set_base_view_path(options) #:nodoc:
+ ActionView::Base.base_view_path = base_view_path(options)
+ end
+
+ def base_view_path(options) #:nodoc:
+ "/#{derived_controller_name(options)}/"
+ end
+
+ def derived_controller_name(options) #:nodoc:
+ parts = subject_of_render(options).split('/').reject { |part| part.empty? }
+ "#{parts[0..-2].join('/')}"
+ end
+
+ def derived_action_name(options) #:nodoc:
+ parts = subject_of_render(options).split('/').reject { |part| part.empty? }
+ "#{parts.last}"
+ end
+
+ def subject_of_render(options) #:nodoc:
+ [:template, :partial, :file].each do |render_type|
+ if options.has_key?(render_type)
+ return options[render_type]
+ end
+ end
+ raise Exception.new("Unhandled render type in view spec.")
+ end
+
+ def add_helpers(options) #:nodoc:
+ @controller.add_helper("application")
+ @controller.add_helper(derived_controller_name(options))
+ @controller.add_helper(options[:helper]) if options[:helper]
+ options[:helpers].each { |helper| @controller.add_helper(helper) } if options[:helpers]
+ end
+
+ # Renders a template for a View Spec, which then provides access to the result
+ # through the +response+.
+ #
+ # == Examples
+ #
+ # render('/people/list')
+ # render('/people/list', :helper => MyHelper)
+ # render('/people/list', :helpers => [MyHelper, MyOtherHelper])
+ # render(:partial => '/people/_address')
+ #
+ # See Spec::Rails::Example::ViewExampleGroup for more information.
+ def render(*args)
+ options = Hash === args.last ? args.pop : {}
+ options[:template] = args.first.to_s unless args.empty?
+
+ set_base_view_path(options)
+ add_helpers(options)
+
+ assigns[:action_name] = @action_name
+
+ @request.path_parameters = {
+ :controller => derived_controller_name(options),
+ :action => derived_action_name(options)
+ }
+
+ defaults = { :layout => false }
+ options = defaults.merge options
+
+ @controller.instance_variable_set :@params, @request.parameters
+
+ @controller.send :initialize_current_url
+
+ @controller.class.instance_eval %{
+ def controller_path
+ "#{derived_controller_name(options)}"
+ end
+
+ def controller_name
+ "#{derived_controller_name(options).split('/').last}"
+ end
+ }
+
+ @controller.send :forget_variables_added_to_assigns
+ @controller.send :render, options
+ @controller.send :process_cleanup
+ end
+
+ # This provides the template. Use this to set mock
+ # expectations for dealing with partials
+ #
+ # == Example
+ #
+ # describe "/person/new" do
+ # it "should use the form partial" do
+ # template.should_receive(:render).with(:partial => 'form')
+ # render "/person/new"
+ # end
+ # end
+ def template
+ @controller.template
+ end
+
+ Spec::Example::ExampleGroupFactory.register(:view, self)
+ end
+
+ class ViewExampleGroupController < ApplicationController #:nodoc:
+ include Spec::Rails::Example::RenderObserver
+ attr_reader :template
+
+ def add_helper_for(template_path)
+ add_helper(template_path.split('/')[0])
+ end
+
+ def add_helper(name)
+ begin
+ helper_module = "#{name}_helper".camelize.constantize
+ rescue
+ return
+ end
+ template.metaclass.class_eval do
+ include helper_module
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions.rb
new file mode 100644
index 0000000..2a4b9ec
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions.rb
@@ -0,0 +1,12 @@
+require 'spec'
+
+require 'spec/rails/extensions/object'
+
+require 'spec/rails/extensions/spec/example/configuration'
+require 'spec/rails/extensions/spec/matchers/have'
+
+require 'spec/rails/extensions/active_record/base'
+require 'spec/rails/extensions/action_controller/base'
+require 'spec/rails/extensions/action_controller/rescue'
+require 'spec/rails/extensions/action_controller/test_response'
+require 'spec/rails/extensions/action_view/base'
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_controller/base.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_controller/base.rb
new file mode 100644
index 0000000..1f7edf8
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_controller/base.rb
@@ -0,0 +1,14 @@
+module ActionController
+ class Base
+ class << self
+ def set_view_path(path)
+ [:append_view_path, :view_paths=, :template_root=].each do |method|
+ if respond_to?(method)
+ return send(method, path)
+ end
+ end
+ end
+ end
+ end
+end
+
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_controller/rescue.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_controller/rescue.rb
new file mode 100644
index 0000000..03dc572
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_controller/rescue.rb
@@ -0,0 +1,21 @@
+module ActionController
+ module Rescue
+ def use_rails_error_handling!
+ @use_rails_error_handling = true
+ end
+
+ def use_rails_error_handling?
+ @use_rails_error_handling ||= false
+ end
+
+ protected
+ def rescue_action_with_fast_errors(exception)
+ if use_rails_error_handling?
+ rescue_action_without_fast_errors exception
+ else
+ raise exception
+ end
+ end
+ alias_method_chain :rescue_action, :fast_errors
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_controller/test_response.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_controller/test_response.rb
new file mode 100644
index 0000000..85badf9
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_controller/test_response.rb
@@ -0,0 +1,11 @@
+module ActionController #:nodoc:
+ class TestResponse #:nodoc:
+ attr_writer :controller_path
+
+ def capture(name)
+ template.instance_variable_get "@content_for_#{name.to_s}"
+ end
+ alias [] capture
+
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_view/base.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_view/base.rb
new file mode 100644
index 0000000..47c717a
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/action_view/base.rb
@@ -0,0 +1,27 @@
+module ActionView #:nodoc:
+ class Base #:nodoc:
+ include Spec::Rails::Example::RenderObserver
+ cattr_accessor :base_view_path
+ def render_partial(partial_path, local_assigns = nil, deprecated_local_assigns = nil) #:nodoc:
+ if partial_path.is_a?(String)
+ unless partial_path.include?("/")
+ unless self.class.base_view_path.nil?
+ partial_path = "#{self.class.base_view_path}/#{partial_path}"
+ end
+ end
+ end
+ super(partial_path, local_assigns, deprecated_local_assigns)
+ end
+
+ alias_method :orig_render, :render
+ def render(options = {}, old_local_assigns = {}, &block)
+ if expect_render_mock_proxy.send(:__mock_proxy).send(:find_matching_expectation, :render, options)
+ expect_render_mock_proxy.render(options)
+ else
+ unless expect_render_mock_proxy.send(:__mock_proxy).send(:find_matching_method_stub, :render, options)
+ orig_render(options, old_local_assigns, &block)
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/active_record/base.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/active_record/base.rb
new file mode 100644
index 0000000..fd6d50f
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/active_record/base.rb
@@ -0,0 +1,30 @@
+if defined?(ActiveRecord::Base)
+ module ActiveRecord #:nodoc:
+ class Base
+
+ (class << self; self; end).class_eval do
+ # Extension for <tt>should have</tt> on AR Model classes
+ #
+ # ModelClass.should have(:no).records
+ # ModelClass.should have(1).record
+ # ModelClass.should have(n).records
+ def records
+ find(:all)
+ end
+ alias :record :records
+ end
+
+ # Extension for <tt>should have</tt> on AR Model instances
+ #
+ # model.should have(:no).errors_on(:attribute)
+ # model.should have(1).error_on(:attribute)
+ # model.should have(n).errors_on(:attribute)
+ def errors_on(attribute)
+ self.valid?
+ [self.errors.on(attribute)].flatten.compact
+ end
+ alias :error_on :errors_on
+
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/object.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/object.rb
new file mode 100644
index 0000000..68fce0b
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/object.rb
@@ -0,0 +1,5 @@
+class Object # :nodoc:
+ def self.path2class(klassname)
+ klassname.split('::').inject(Object) { |k,n| k.const_get n }
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/spec/example/configuration.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/spec/example/configuration.rb
new file mode 100644
index 0000000..06e3226
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/spec/example/configuration.rb
@@ -0,0 +1,66 @@
+require 'spec/example/configuration'
+
+module Spec
+ module Example
+ class Configuration
+ # Rails 1.2.3 does a copy of the @inheritable_attributes to the subclass when the subclass is
+ # created. This causes an ordering issue when setting state on Configuration because the data is
+ # already copied.
+ # Iterating over EXAMPLE_GROUP_CLASSES causes the base ExampleGroup classes to have their
+ # @inheritable_attributes updated.
+ # TODO: BT - When we no longer support Rails 1.2.3, we can remove this functionality
+ EXAMPLE_GROUP_CLASSES = [
+ ::Test::Unit::TestCase,
+ ::Spec::Rails::Example::RailsExampleGroup,
+ ::Spec::Rails::Example::FunctionalExampleGroup,
+ ::Spec::Rails::Example::ControllerExampleGroup,
+ ::Spec::Rails::Example::ViewExampleGroup,
+ ::Spec::Rails::Example::HelperExampleGroup,
+ ::Spec::Rails::Example::ModelExampleGroup
+ ]
+ # All of this is ActiveRecord related and makes no sense if it's not used by the app
+ if defined?(ActiveRecord::Base)
+ def initialize
+ super
+ self.fixture_path = RAILS_ROOT + '/spec/fixtures'
+ end
+
+ def use_transactional_fixtures
+ Test::Unit::TestCase.use_transactional_fixtures
+ end
+ def use_transactional_fixtures=(value)
+ EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.use_transactional_fixtures = value
+ end
+ end
+
+ def use_instantiated_fixtures
+ Test::Unit::TestCase.use_instantiated_fixtures
+ end
+ def use_instantiated_fixtures=(value)
+ EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.use_instantiated_fixtures = value
+ end
+ end
+
+ def fixture_path
+ Test::Unit::TestCase.fixture_path
+ end
+ def fixture_path=(path)
+ EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.fixture_path = path
+ end
+ end
+
+ def global_fixtures
+ ::Test::Unit::TestCase.fixture_table_names
+ end
+ def global_fixtures=(fixtures)
+ EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.fixtures(*fixtures)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/spec/matchers/have.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/spec/matchers/have.rb
new file mode 100644
index 0000000..dc01e40
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/extensions/spec/matchers/have.rb
@@ -0,0 +1,21 @@
+require 'spec/matchers/have'
+
+module Spec #:nodoc:
+ module Matchers #:nodoc:
+ class Have #:nodoc:
+ alias_method :__original_failure_message, :failure_message
+ def failure_message
+ return "expected #{relativities[@relativity]}#{@expected} errors on :#{@args[0]}, got #{@actual}" if @collection_name == :errors_on
+ return "expected #{relativities[@relativity]}#{@expected} error on :#{@args[0]}, got #{@actual}" if @collection_name == :error_on
+ return __original_failure_message
+ end
+
+ alias_method :__original_description, :description
+ def description
+ return "should have #{relativities[@relativity]}#{@expected} errors on :#{@args[0]}" if @collection_name == :errors_on
+ return "should have #{relativities[@relativity]}#{@expected} error on :#{@args[0]}" if @collection_name == :error_on
+ return __original_description
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers.rb
new file mode 100644
index 0000000..27ac2ba
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers.rb
@@ -0,0 +1,29 @@
+dir = File.dirname(__FILE__)
+require 'spec/rails/matchers/assert_select'
+require 'spec/rails/matchers/have_text'
+require 'spec/rails/matchers/redirect_to'
+require 'spec/rails/matchers/render_template'
+
+module Spec
+ module Rails
+ # Spec::Rails::Expectations::Matchers provides several expectation matchers
+ # intended to work with Rails components like models and responses. For example:
+ #
+ # response.should redirect_to("some/url") #redirect_to(url) is the matcher.
+ #
+ # In addition to those you see below, the arbitrary predicate feature of RSpec
+ # makes the following available as well:
+ #
+ # response.should be_success #passes if response.success?
+ # response.should be_redirect #passes if response.redirect?
+ #
+ # Note that many of these matchers are part of a wrapper of <tt>assert_select</tt>, so
+ # the documentation comes straight from that with some slight modifications.
+ # <tt>assert_select</tt> is a Test::Unit extension originally contributed to the
+ # Rails community as a plugin by Assaf Arkin and eventually shipped as part of Rails.
+ #
+ # For more info on <tt>assert_select</tt>, see the relevant Rails documentation.
+ module Matchers
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/assert_select.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/assert_select.rb
new file mode 100644
index 0000000..1af3511
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/assert_select.rb
@@ -0,0 +1,130 @@
+# This is a wrapper of assert_select for rspec.
+
+module Spec # :nodoc:
+ module Rails
+ module Matchers
+
+ class AssertSelect #:nodoc:
+
+ def initialize(assertion, spec_scope, *args, &block)
+ @assertion = assertion
+ @spec_scope = spec_scope
+ @args = args
+ @block = block
+ end
+
+ def matches?(response_or_text, &block)
+ if ActionController::TestResponse === response_or_text and
+ response_or_text.headers.key?('Content-Type') and
+ response_or_text.headers['Content-Type'].to_sym == :xml
+ @args.unshift(HTML::Document.new(response_or_text.body, false, true).root)
+ elsif String === response_or_text
+ @args.unshift(HTML::Document.new(response_or_text).root)
+ end
+ @block = block if block
+ begin
+ @spec_scope.send(@assertion, *@args, &@block)
+ rescue ::Test::Unit::AssertionFailedError => @error
+ end
+
+ @error.nil?
+ end
+
+ def failure_message; @error.message; end
+ def negative_failure_message; "should not #{description}, but did"; end
+
+ def description
+ {
+ :assert_select => "have tag#{format_args(*@args)}",
+ :assert_select_email => "send email#{format_args(*@args)}",
+ }[@assertion]
+ end
+
+ private
+
+ def format_args(*args)
+ return "" if args.empty?
+ return "(#{arg_list(*args)})"
+ end
+
+ def arg_list(*args)
+ args.collect do |arg|
+ arg.respond_to?(:description) ? arg.description : arg.inspect
+ end.join(", ")
+ end
+
+ end
+
+ # :call-seq:
+ # response.should have_tag(*args, &block)
+ # string.should have_tag(*args, &block)
+ #
+ # wrapper for assert_select with additional support for using
+ # css selectors to set expectation on Strings. Use this in
+ # helper specs, for example, to set expectations on the results
+ # of helper methods.
+ #
+ # == Examples
+ #
+ # # in a controller spec
+ # response.should have_tag("div", "some text")
+ #
+ # # in a helper spec (person_address_tag is a method in the helper)
+ # person_address_tag.should have_tag("input#person_address")
+ #
+ # see documentation for assert_select at http://api.rubyonrails.org/
+ def have_tag(*args, &block)
+ AssertSelect.new(:assert_select, self, *args, &block)
+ end
+
+ # wrapper for a nested assert_select
+ #
+ # response.should have_tag("div#form") do
+ # with_tag("input#person_name[name=?]", "person[name]")
+ # end
+ #
+ # see documentation for assert_select at http://api.rubyonrails.org/
+ def with_tag(*args, &block)
+ should have_tag(*args, &block)
+ end
+
+ # wrapper for a nested assert_select with false
+ #
+ # response.should have_tag("div#1") do
+ # without_tag("span", "some text that shouldn't be there")
+ # end
+ #
+ # see documentation for assert_select at http://api.rubyonrails.org/
+ def without_tag(*args, &block)
+ should_not have_tag(*args, &block)
+ end
+
+ # :call-seq:
+ # response.should have_rjs(*args, &block)
+ #
+ # wrapper for assert_select_rjs
+ #
+ # see documentation for assert_select_rjs at http://api.rubyonrails.org/
+ def have_rjs(*args, &block)
+ AssertSelect.new(:assert_select_rjs, self, *args, &block)
+ end
+
+ # :call-seq:
+ # response.should send_email(*args, &block)
+ #
+ # wrapper for assert_select_email
+ #
+ # see documentation for assert_select_email at http://api.rubyonrails.org/
+ def send_email(*args, &block)
+ AssertSelect.new(:assert_select_email, self, *args, &block)
+ end
+
+ # wrapper for assert_select_encoded
+ #
+ # see documentation for assert_select_encoded at http://api.rubyonrails.org/
+ def with_encoded(*args, &block)
+ should AssertSelect.new(:assert_select_encoded, self, *args, &block)
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/have_text.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/have_text.rb
new file mode 100644
index 0000000..12c71ea
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/have_text.rb
@@ -0,0 +1,55 @@
+module Spec
+ module Rails
+ module Matchers
+
+ class HaveText #:nodoc:
+
+ def initialize(expected)
+ @expected = expected
+ end
+
+ def matches?(response_or_text)
+ @actual = response_or_text.respond_to?(:body) ? response_or_text.body : response_or_text
+ return actual =~ expected if Regexp === expected
+ return actual == expected unless Regexp === expected
+ end
+
+ def failure_message
+ "expected #{expected.inspect}, got #{actual.inspect}"
+ end
+
+ def negative_failure_message
+ "expected not to have text #{expected.inspect}"
+ end
+
+ def to_s
+ "have text #{expected.inspect}"
+ end
+
+ private
+ attr_reader :expected
+ attr_reader :actual
+
+ end
+
+ # :call-seq:
+ # response.should have_text(expected)
+ # response.should_not have_text(expected)
+ #
+ # Accepts a String or a Regexp, matching a String using ==
+ # and a Regexp using =~.
+ #
+ # Use this instead of <tt>response.should have_tag()</tt>
+ # when you either don't know or don't care where on the page
+ # this text appears.
+ #
+ # == Examples
+ #
+ # response.should have_text("This is the expected text")
+ def have_text(text)
+ HaveText.new(text)
+ end
+
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/redirect_to.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/redirect_to.rb
new file mode 100644
index 0000000..7c61c81
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/redirect_to.rb
@@ -0,0 +1,113 @@
+module Spec
+ module Rails
+ module Matchers
+
+ class RedirectTo #:nodoc:
+
+ def initialize(request, expected)
+ @expected = expected
+ @request = request
+ end
+
+ def matches?(response)
+ @redirected = response.redirect?
+ @actual = response.redirect_url
+ return false unless @redirected
+ if @expected.instance_of? Hash
+ return false unless @actual =~ %r{^\w+://#{@request.host}}
+ return false unless actual_redirect_to_valid_route
+ return actual_hash == expected_hash
+ else
+ return @actual == expected_url
+ end
+ end
+
+ def actual_hash
+ hash_from_url @actual
+ end
+
+ def expected_hash
+ hash_from_url expected_url
+ end
+
+ def actual_redirect_to_valid_route
+ actual_hash
+ end
+
+ def hash_from_url(url)
+ query_hash(url).merge(path_hash(url)).with_indifferent_access
+ end
+
+ def path_hash(url)
+ path = url.sub(%r{^\w+://#{@request.host}}, "").split("?", 2)[0]
+ ActionController::Routing::Routes.recognize_path path
+ end
+
+ def query_hash(url)
+ query = url.split("?", 2)[1] || ""
+ QueryParameterParser.parse_query_parameters(query, @request)
+ end
+
+ def expected_url
+ case @expected
+ when Hash
+ return ActionController::UrlRewriter.new(@request, {}).rewrite(@expected)
+ when :back
+ return @request.env['HTTP_REFERER']
+ when %r{^\w+://.*}
+ return @expected
+ else
+ return "http://#{@request.host}" + (@expected.split('')[0] == '/' ? '' : '/') + @expected
+ end
+ end
+
+ def failure_message
+ if @redirected
+ return %Q{expected redirect to #{@expected.inspect}, got redirect to #{@actual.inspect}}
+ else
+ return %Q{expected redirect to #{@expected.inspect}, got no redirect}
+ end
+ end
+
+ def negative_failure_message
+ return %Q{expected not to be redirected to #{@expected.inspect}, but was} if @redirected
+ end
+
+ def description
+ "redirect to #{@actual.inspect}"
+ end
+
+ class QueryParameterParser
+ def self.parse_query_parameters(query, request)
+ if defined?(CGIMethods)
+ CGIMethods.parse_query_parameters(query)
+ else
+ request.class.parse_query_parameters(query)
+ end
+ end
+ end
+ end
+
+ # :call-seq:
+ # response.should redirect_to(url)
+ # response.should redirect_to(:action => action_name)
+ # response.should redirect_to(:controller => controller_name, :action => action_name)
+ # response.should_not redirect_to(url)
+ # response.should_not redirect_to(:action => action_name)
+ # response.should_not redirect_to(:controller => controller_name, :action => action_name)
+ #
+ # Passes if the response is a redirect to the url, action or controller/action.
+ # Useful in controller specs (integration or isolation mode).
+ #
+ # == Examples
+ #
+ # response.should redirect_to("path/to/action")
+ # response.should redirect_to("http://test.host/path/to/action")
+ # response.should redirect_to(:action => 'list')
+ def redirect_to(opts)
+ RedirectTo.new(request, opts)
+ end
+ end
+
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/render_template.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/render_template.rb
new file mode 100644
index 0000000..e36c8bc
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/matchers/render_template.rb
@@ -0,0 +1,70 @@
+module Spec
+ module Rails
+ module Matchers
+
+ class RenderTemplate #:nodoc:
+
+ def initialize(expected, controller)
+ @controller = controller
+ @expected = expected
+ end
+
+ def matches?(response)
+ @actual = response.rendered_file
+ full_path(@actual) == full_path(@expected)
+ end
+
+ def failure_message
+ "expected #{@expected.inspect}, got #{@actual.inspect}"
+ end
+
+ def negative_failure_message
+ "expected not to render #{@expected.inspect}, but did"
+ end
+
+ def description
+ "render template #{@expected.inspect}"
+ end
+
+ private
+ def full_path(path)
+ return nil if path.nil?
+ path.include?('/') ? path : "#{@controller.class.to_s.underscore.gsub('_controller','')}/#{path}"
+ end
+
+ end
+
+ # :call-seq:
+ # response.should render_template(path)
+ # response.should_not render_template(path)
+ #
+ # Passes if the specified template is rendered by the response.
+ # Useful in controller specs (integration or isolation mode).
+ #
+ # <code>path</code> can include the controller path or not. It
+ # can also include an optional extension (no extension assumes .rhtml).
+ #
+ # Note that partials must be spelled with the preceding underscore.
+ #
+ # == Examples
+ #
+ # response.should render_template('list')
+ # response.should render_template('same_controller/list')
+ # response.should render_template('other_controller/list')
+ #
+ # #rjs
+ # response.should render_template('list.rjs')
+ # response.should render_template('same_controller/list.rjs')
+ # response.should render_template('other_controller/list.rjs')
+ #
+ # #partials
+ # response.should render_template('_a_partial')
+ # response.should render_template('same_controller/_a_partial')
+ # response.should render_template('other_controller/_a_partial')
+ def render_template(path)
+ RenderTemplate.new(path.to_s, @controller)
+ end
+
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/story_adapter.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/story_adapter.rb
new file mode 100644
index 0000000..66124af
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/story_adapter.rb
@@ -0,0 +1,71 @@
+# WARNING - THIS IS PURELY EXPERIMENTAL AT THIS POINT
+# Courtesy of Brian Takita and Yurii Rashkovskii
+
+$:.unshift File.join(File.dirname(__FILE__), *%w[.. .. .. .. rspec lib])
+if defined?(ActiveRecord::Base)
+ require 'test_help'
+else
+ require 'action_controller/test_process'
+ require 'action_controller/integration'
+end
+require 'test/unit/testresult'
+require 'spec'
+require 'spec/rails'
+
+Test::Unit.run = true
+
+ActionController::Integration::Session.send(:include, Spec::Matchers)
+ActionController::Integration::Session.send(:include, Spec::Rails::Matchers)
+
+class RailsStory < ActionController::IntegrationTest
+ if defined?(ActiveRecord::Base)
+ self.use_transactional_fixtures = true
+ else
+ def self.fixture_table_names; []; end # Workaround for projects that don't use ActiveRecord
+ end
+
+ def initialize #:nodoc:
+ # TODO - eliminate this hack, which is here to stop
+ # Rails Stories from dumping the example summary.
+ Spec::Runner::Options.class_eval do
+ def examples_should_be_run?
+ false
+ end
+ end
+ @_result = Test::Unit::TestResult.new
+ end
+end
+
+class ActiveRecordSafetyListener
+ include Singleton
+ def scenario_started(*args)
+ if defined?(ActiveRecord::Base)
+ ActiveRecord::Base.send :increment_open_transactions unless Rails::VERSION::STRING == "1.1.6"
+ ActiveRecord::Base.connection.begin_db_transaction
+ end
+ end
+
+ def scenario_succeeded(*args)
+ if defined?(ActiveRecord::Base)
+ ActiveRecord::Base.connection.rollback_db_transaction
+ ActiveRecord::Base.send :decrement_open_transactions unless Rails::VERSION::STRING == "1.1.6"
+ end
+ end
+ alias :scenario_pending :scenario_succeeded
+ alias :scenario_failed :scenario_succeeded
+end
+
+class Spec::Story::Runner::ScenarioRunner
+ def initialize
+ @listeners = [ActiveRecordSafetyListener.instance]
+ end
+end
+
+class Spec::Story::GivenScenario
+ def perform(instance, name = nil)
+ scenario = Spec::Story::Runner::StoryRunner.scenario_from_current_story @name
+ runner = Spec::Story::Runner::ScenarioRunner.new
+ runner.instance_variable_set(:@listeners,[])
+ runner.run(scenario, instance)
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/lib/spec/rails/version.rb b/vendor/plugins/rspec_on_rails/lib/spec/rails/version.rb
new file mode 100644
index 0000000..0be4466
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/lib/spec/rails/version.rb
@@ -0,0 +1,23 @@
+module Spec
+ module Rails
+ module VERSION #:nodoc:
+ BUILD_TIME_UTC = 20080131122909
+ end
+ end
+end
+
+# Verify that the plugin has the same revision as RSpec
+if Spec::Rails::VERSION::BUILD_TIME_UTC != Spec::VERSION::BUILD_TIME_UTC
+ raise <<-EOF
+
+############################################################################
+Your RSpec on Rails plugin is incompatible with your installed RSpec.
+
+RSpec : #{Spec::VERSION::BUILD_TIME_UTC}
+RSpec on Rails : #{Spec::Rails::VERSION::BUILD_TIME_UTC}
+
+Make sure your RSpec on Rails plugin is compatible with your RSpec gem.
+See http://rspec.rubyforge.org/documentation/rails/install.html for details.
+############################################################################
+EOF
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/autotest/mappings_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/autotest/mappings_spec.rb
new file mode 100644
index 0000000..3ebf890
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/autotest/mappings_spec.rb
@@ -0,0 +1,36 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+require File.join(File.dirname(__FILE__), *%w[.. .. .. lib autotest rails_rspec])
+require File.join(File.dirname(__FILE__), *%w[.. .. .. .. rspec spec autotest_matchers])
+
+describe Autotest::RailsRspec, "file mapping" do
+ before(:each) do
+ @autotest = Autotest::RailsRspec.new
+ @autotest.hook :initialize
+ end
+
+ it "should map model example to model" do
+ @autotest.should map_specs(['spec/models/thing_spec.rb']).
+ to('app/models/thing.rb')
+ end
+
+ it "should map controller example to controller" do
+ @autotest.should map_specs(['spec/controllers/things_controller_spec.rb']).
+ to('app/controllers/things_controller.rb')
+ end
+
+ it "should map view.rhtml" do
+ @autotest.should map_specs(['spec/views/things/index.rhtml_spec.rb']).
+ to('app/views/things/index.rhtml')
+ end
+
+ it "should map view.rhtml with underscores in example filename" do
+ @autotest.should map_specs(['spec/views/things/index_rhtml_spec.rb']).
+ to('app/views/things/index.rhtml')
+ end
+
+ it "should map view.html.erb" do
+ @autotest.should map_specs(['spec/views/things/index.html.erb_spec.rb']).
+ to('app/views/things/index.html.erb')
+ end
+
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/autotest/rails_rspec_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/autotest/rails_rspec_spec.rb
new file mode 100644
index 0000000..148e005
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/autotest/rails_rspec_spec.rb
@@ -0,0 +1,8 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+require File.join(File.dirname(__FILE__), "..", "..", "..", "lib", "autotest", "rails_rspec")
+
+describe Autotest::RailsRspec do
+ it "should provide the correct spec_command" do
+ Autotest::RailsRspec.new.spec_command.should == "script/spec"
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/assigns_hash_proxy_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/assigns_hash_proxy_spec.rb
new file mode 100644
index 0000000..400fb82
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/assigns_hash_proxy_spec.rb
@@ -0,0 +1,55 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe "An AssignsHashProxy" do
+ before(:each) do
+ @object = Object.new
+ @assigns = Hash.new
+ @object.stub!(:assigns).and_return(@assigns)
+ @proxy = Spec::Rails::Example::AssignsHashProxy.new(@object)
+ end
+
+ it "has [] accessor" do
+ @proxy['foo'] = 'bar'
+ @assigns['foo'].should == 'bar'
+ @proxy['foo'].should == 'bar'
+ end
+
+ it "works for symbol key" do
+ @assigns[:foo] = 2
+ @proxy[:foo].should == 2
+ end
+
+ it "checks for string key before symbol key" do
+ @assigns['foo'] = false
+ @assigns[:foo] = 2
+ @proxy[:foo].should == false
+ end
+
+ it "each method iterates through each element like a Hash" do
+ values = {
+ 'foo' => 1,
+ 'bar' => 2,
+ 'baz' => 3
+ }
+ @proxy['foo'] = values['foo']
+ @proxy['bar'] = values['bar']
+ @proxy['baz'] = values['baz']
+
+ @proxy.each do |key, value|
+ key.should == key
+ value.should == values[key]
+ end
+ end
+
+ it "delete method deletes the element of passed in key" do
+ @proxy['foo'] = 'bar'
+ @proxy.delete('foo').should == 'bar'
+ @proxy['foo'].should be_nil
+ end
+
+ it "has_key? detects the presence of a key" do
+ @proxy['foo'] = 'bar'
+ @proxy.has_key?('foo').should == true
+ @proxy.has_key?('bar').should == false
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/configuration_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/configuration_spec.rb
new file mode 100644
index 0000000..91a1b26
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/configuration_spec.rb
@@ -0,0 +1,83 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+module Spec
+ module Example
+ describe Configuration, :shared => true do
+ before(:each) { @config = Configuration.new }
+ end
+
+ describe Configuration, "#use_transactional_fixtures" do
+ it_should_behave_like "Spec::Example::Configuration"
+
+ it "should return Test::Unit::TestCase.use_transactional_fixtures" do
+ @config.use_transactional_fixtures.should == Test::Unit::TestCase.use_transactional_fixtures
+ end
+
+ it "should set Test::Unit::TestCase.use_transactional_fixtures to false" do
+ Configuration::EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.should_receive(:use_transactional_fixtures=).with(false)
+ end
+ @config.use_transactional_fixtures = false
+ end
+
+ it "should set Test::Unit::TestCase.use_transactional_fixtures to true" do
+ Configuration::EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.should_receive(:use_transactional_fixtures=).with(true)
+ end
+ @config.use_transactional_fixtures = true
+ end
+ end
+
+ describe Configuration, "#use_instantiated_fixtures" do
+ it_should_behave_like "Spec::Example::Configuration"
+
+ it "should return Test::Unit::TestCase.use_transactional_fixtures" do
+ @config.use_instantiated_fixtures.should == Test::Unit::TestCase.use_instantiated_fixtures
+ end
+
+ it "should set Test::Unit::TestCase.use_instantiated_fixtures to false" do
+ Configuration::EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.should_receive(:use_instantiated_fixtures=).with(false)
+ end
+ @config.use_instantiated_fixtures = false
+ end
+
+ it "should set Test::Unit::TestCase.use_instantiated_fixtures to true" do
+ Configuration::EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.should_receive(:use_instantiated_fixtures=).with(true)
+ end
+ @config.use_instantiated_fixtures = true
+ end
+ end
+
+ describe Configuration, "#fixture_path" do
+ it_should_behave_like "Spec::Example::Configuration"
+
+ it "should default to RAILS_ROOT + '/spec/fixtures'" do
+ @config.fixture_path.should == RAILS_ROOT + '/spec/fixtures'
+ Configuration::EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.fixture_path.should == RAILS_ROOT + '/spec/fixtures'
+ end
+ end
+
+ it "should set fixture_path" do
+ @config.fixture_path = "/new/path"
+ @config.fixture_path.should == "/new/path"
+ Configuration::EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.fixture_path.should == "/new/path"
+ end
+ end
+ end
+
+ describe Configuration, "#global_fixtures" do
+ it_should_behave_like "Spec::Example::Configuration"
+
+ it "should set fixtures on TestCase" do
+ Configuration::EXAMPLE_GROUP_CLASSES.each do |example_group|
+ example_group.should_receive(:fixtures).with(:blah)
+ end
+ @config.global_fixtures = [:blah]
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/controller_isolation_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/controller_isolation_spec.rb
new file mode 100644
index 0000000..204db15
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/controller_isolation_spec.rb
@@ -0,0 +1,43 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+require 'controller_spec_controller'
+
+describe "a controller spec running in isolation mode", :type => :controller do
+ controller_name :controller_spec
+
+ it "should not care if the template doesn't exist" do
+ get 'some_action'
+ response.should be_success
+ response.should render_template("template/that/does/not/actually/exist")
+ end
+
+ it "should not care if the template has errors" do
+ get 'action_with_errors_in_template'
+ response.should be_success
+ response.should render_template("action_with_errors_in_template")
+ end
+end
+
+describe "a controller spec running in integration mode", :type => :controller do
+ controller_name :controller_spec
+ integrate_views
+
+ before(:each) do
+ controller.class.send(:define_method, :rescue_action) { |e| raise e }
+ end
+
+ it "should render a template" do
+ get 'action_with_template'
+ response.should be_success
+ response.should have_tag('div', 'This is action_with_template.rhtml')
+ end
+
+ it "should choke if the template doesn't exist" do
+ lambda { get 'some_action' }.should raise_error(ActionController::MissingTemplate)
+ response.should_not be_success
+ end
+
+ it "should choke if the template has errors" do
+ lambda { get 'action_with_errors_in_template' }.should raise_error(ActionView::TemplateError)
+ response.should_not be_success
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/controller_spec_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/controller_spec_spec.rb
new file mode 100644
index 0000000..230b608
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/controller_spec_spec.rb
@@ -0,0 +1,187 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+require 'controller_spec_controller'
+
+['integration', 'isolation'].each do |mode|
+ describe "A controller example running in #{mode} mode", :type => :controller do
+ controller_name :controller_spec
+ integrate_views if mode == 'integration'
+
+ it "should provide controller.session as session" do
+ get 'action_with_template'
+ session.should equal(controller.session)
+ end
+
+ it "should provide the same session object before and after the action" do
+ session_before = session
+ get 'action_with_template'
+ session.should equal(session_before)
+ end
+
+ it "should ensure controller.session is NOT nil before the action" do
+ controller.session.should_not be_nil
+ get 'action_with_template'
+ end
+
+ it "should ensure controller.session is NOT nil after the action" do
+ get 'action_with_template'
+ controller.session.should_not be_nil
+ end
+
+ it "should allow specifying a partial with partial name only" do
+ get 'action_with_partial'
+ response.should render_template("_partial")
+ end
+
+ it "should allow specifying a partial with expect_render" do
+ controller.expect_render(:partial => "controller_spec/partial")
+ get 'action_with_partial'
+ end
+
+ it "should allow specifying a partial with expect_render with object" do
+ controller.expect_render(:partial => "controller_spec/partial", :object => "something")
+ get 'action_with_partial_with_object', :thing => "something"
+ end
+
+ it "should allow specifying a partial with expect_render with locals" do
+ controller.expect_render(:partial => "controller_spec/partial", :locals => {:thing => "something"})
+ get 'action_with_partial_with_locals', :thing => "something"
+ end
+
+ it "should yield to render :update" do
+ template = stub("template")
+ controller.expect_render(:update).and_yield(template)
+ template.should_receive(:replace).with(:bottom, "replace_me", :partial => "non_existent_partial")
+ get 'action_with_render_update'
+ puts response.body
+ end
+
+ it "should allow a path relative to RAILS_ROOT/app/views/ when specifying a partial" do
+ get 'action_with_partial'
+ response.should render_template("controller_spec/_partial")
+ end
+
+ it "should provide access to flash" do
+ get 'action_with_template'
+ flash[:flash_key].should == "flash value"
+ end
+
+ it "should provide access to flash values set after a session reset" do
+ get 'action_setting_flash_after_session_reset'
+ flash[:after_reset].should == "available"
+ end
+
+ it "should not provide access to flash values set before a session reset" do
+ get 'action_setting_flash_before_session_reset'
+ flash[:before_reset].should_not == "available"
+ end
+
+ it "should provide access to session" do
+ get 'action_with_template'
+ session[:session_key].should == "session value"
+ end
+
+ it "should support custom routes" do
+ route_for(:controller => "custom_route_spec", :action => "custom_route").should == "/custom_route"
+ end
+
+ it "should support existing routes" do
+ route_for(:controller => "controller_spec", :action => "some_action").should == "/controller_spec/some_action"
+ end
+
+ it "should generate params for custom routes" do
+ params_from(:get, '/custom_route').should == {:controller => "custom_route_spec", :action => "custom_route"}
+ end
+
+ it "should generate params for existing routes" do
+ params_from(:get, '/controller_spec/some_action').should == {:controller => "controller_spec", :action => "some_action"}
+ end
+
+ it "should expose instance vars through the assigns hash" do
+ get 'action_setting_the_assigns_hash'
+ assigns[:indirect_assigns_key].should == :indirect_assigns_key_value
+ end
+
+ it "should expose the assigns hash directly" do
+ get 'action_setting_the_assigns_hash'
+ assigns[:direct_assigns_key].should == :direct_assigns_key_value
+ end
+
+ it "should complain when calling should_receive(:render) on the controller" do
+ lambda {
+ controller.should_receive(:render)
+ }.should raise_error(RuntimeError, /should_receive\(:render\) has been disabled/)
+ end
+
+ it "should complain when calling stub!(:render) on the controller" do
+ lambda {
+ controller.stub!(:render)
+ }.should raise_error(RuntimeError, /stub!\(:render\) has been disabled/)
+ end
+
+ it "should NOT complain when calling should_receive with arguments other than :render" do
+ controller.should_receive(:anything_besides_render)
+ lambda {
+ controller.rspec_verify
+ }.should raise_error(Exception, /expected :anything_besides_render/)
+ end
+ end
+
+ describe "Given a controller spec for RedirectSpecController running in #{mode} mode", :type => :controller do
+ controller_name :redirect_spec
+ integrate_views if mode == 'integration'
+
+ it "a redirect should ignore the absence of a template" do
+ get 'action_with_redirect_to_somewhere'
+ response.should be_redirect
+ response.redirect_url.should == "http://test.host/redirect_spec/somewhere"
+ response.should redirect_to("http://test.host/redirect_spec/somewhere")
+ end
+
+ it "a call to response.should redirect_to should fail if no redirect" do
+ get 'action_with_no_redirect'
+ lambda {
+ response.redirect?.should be_true
+ }.should fail
+ lambda {
+ response.should redirect_to("http://test.host/redirect_spec/somewhere")
+ }.should fail_with("expected redirect to \"http://test.host/redirect_spec/somewhere\", got no redirect")
+ end
+ end
+
+ describe "Given a controller spec running in #{mode} mode" do
+ example_group = describe "A controller spec"
+ # , :type => :controller do
+ # integrate_views if mode == 'integration'
+ it "a spec in a context without controller_name set should fail with a useful warning" do
+ pending("need a new way to deal with examples that should_raise")
+ # ,
+ # :should_raise => [
+ # Spec::Expectations::ExpectationNotMetError,
+ # /You have to declare the controller name in controller specs/
+ # ] do
+ end
+ end
+
+end
+
+describe ControllerSpecController, :type => :controller do
+ it "should not require naming the controller if describe is passed a type" do
+ end
+end
+
+module Spec
+ module Rails
+ module Example
+ describe ControllerExampleGroup do
+ it "should clear its name from the description" do
+ group = describe("foo", :type => :controller) do
+ $nested_group = describe("bar") do
+ end
+ end
+ group.description.to_s.should == "foo"
+ $nested_group.description.to_s.should == "foo bar"
+ end
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/example_group_factory_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/example_group_factory_spec.rb
new file mode 100644
index 0000000..0803c2f
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/example_group_factory_spec.rb
@@ -0,0 +1,112 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+module Spec
+ module Example
+ describe ExampleGroupFactory do
+ it "should return a ModelExampleGroup when given :type => :model" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :type => :model
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ModelExampleGroup
+ end
+
+ it "should return a ModelExampleGroup when given :spec_path => '/blah/spec/models/'" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '/blah/spec/models/blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ModelExampleGroup
+ end
+
+ it "should return a ModelExampleGroup when given :spec_path => '\\blah\\spec\\models\\' (windows format)" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '\\blah\\spec\\models\\blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ModelExampleGroup
+ end
+
+ it "should return a RailsExampleGroup when given :spec_path => '/blah/spec/foo/' (anything other than controllers, views and helpers)" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '/blah/spec/foo/blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::RailsExampleGroup
+ end
+
+ it "should return a RailsExampleGroup when given :spec_path => '\\blah\\spec\\foo\\' (windows format) (anything other than controllers, views and helpers)" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '\\blah\\spec\\foo\\blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::RailsExampleGroup
+ end
+
+ it "should return a ViewExampleGroup when given :type => :model" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :type => :view
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ViewExampleGroup
+ end
+
+ it "should return a ViewExampleGroup when given :spec_path => '/blah/spec/views/'" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '/blah/spec/views/blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ViewExampleGroup
+ end
+
+ it "should return a ModelExampleGroup when given :spec_path => '\\blah\\spec\\views\\' (windows format)" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '\\blah\\spec\\views\\blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ViewExampleGroup
+ end
+
+ it "should return a HelperExampleGroup when given :type => :helper" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :type => :helper
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::HelperExampleGroup
+ end
+
+ it "should return a HelperExampleGroup when given :spec_path => '/blah/spec/helpers/'" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '/blah/spec/helpers/blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::HelperExampleGroup
+ end
+
+ it "should return a ModelExampleGroup when given :spec_path => '\\blah\\spec\\helpers\\' (windows format)" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '\\blah\\spec\\helpers\\blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::HelperExampleGroup
+ end
+
+ it "should return a ControllerExampleGroup when given :type => :controller" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :type => :controller
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ControllerExampleGroup
+ end
+
+ it "should return a ControllerExampleGroup when given :spec_path => '/blah/spec/controllers/'" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '/blah/spec/controllers/blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ControllerExampleGroup
+ end
+
+ it "should return a ModelExampleGroup when given :spec_path => '\\blah\\spec\\controllers\\' (windows format)" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '\\blah\\spec\\controllers\\blah.rb'
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ControllerExampleGroup
+ end
+
+ it "should favor the :type over the :spec_path" do
+ example_group = Spec::Example::ExampleGroupFactory.create_example_group(
+ "name", :spec_path => '/blah/spec/models/blah.rb', :type => :controller
+ ) {}
+ example_group.superclass.should == Spec::Rails::Example::ControllerExampleGroup
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/helper_spec_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/helper_spec_spec.rb
new file mode 100644
index 0000000..33e3a19
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/helper_spec_spec.rb
@@ -0,0 +1,118 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+Spec::Runner.configuration.global_fixtures = :people
+
+describe ExplicitHelper, :type => :helper do
+ it "should not require naming the helper if describe is passed a type" do
+ method_in_explicit_helper.should match(/text from a method/)
+ end
+end
+
+module Spec
+ module Rails
+ module Example
+ describe HelperExampleGroup, :type => :helper do
+ helper_name :explicit
+
+ it "should have direct access to methods defined in helpers" do
+ method_in_explicit_helper.should =~ /text from a method/
+ end
+
+ it "should have access to named routes" do
+ rspec_on_rails_specs_url.should == "http://test.host/rspec_on_rails_specs"
+ rspec_on_rails_specs_path.should == "/rspec_on_rails_specs"
+ end
+
+ it "should fail if the helper method deson't exist" do
+ lambda { non_existant_helper_method }.should raise_error(NameError)
+ end
+ end
+
+
+ describe HelperExampleGroup, "#eval_erb", :type => :helper do
+ helper_name :explicit
+
+ it "should support methods that accept blocks" do
+ eval_erb("<% prepend 'foo' do %>bar<% end %>").should == "foobar"
+ end
+ end
+
+ describe HelperExampleGroup, ".fixtures", :type => :helper do
+ helper_name :explicit
+ fixtures :animals
+
+ it "should load fixtures" do
+ pig = animals(:pig)
+ pig.class.should == Animal
+ end
+
+ it "should load global fixtures" do
+ lachie = people(:lachie)
+ lachie.class.should == Person
+ end
+ end
+
+ describe HelperExampleGroup, "included modules", :type => :helper do
+ helpers = [
+ ActionView::Helpers::ActiveRecordHelper,
+ ActionView::Helpers::AssetTagHelper,
+ ActionView::Helpers::BenchmarkHelper,
+ ActionView::Helpers::CacheHelper,
+ ActionView::Helpers::CaptureHelper,
+ ActionView::Helpers::DateHelper,
+ ActionView::Helpers::DebugHelper,
+ ActionView::Helpers::FormHelper,
+ ActionView::Helpers::FormOptionsHelper,
+ ActionView::Helpers::FormTagHelper,
+ ActionView::Helpers::JavaScriptHelper,
+ ActionView::Helpers::NumberHelper,
+ ActionView::Helpers::PrototypeHelper,
+ ActionView::Helpers::ScriptaculousHelper,
+ ActionView::Helpers::TagHelper,
+ ActionView::Helpers::TextHelper,
+ ActionView::Helpers::UrlHelper
+ ]
+ helpers << ActionView::Helpers::PaginationHelper rescue nil #removed for 2.0
+ helpers << ActionView::Helpers::JavaScriptMacrosHelper rescue nil #removed for 2.0
+ helpers.each do |helper_module|
+ it "should include #{helper_module}" do
+ self.class.ancestors.should include(helper_module)
+ end
+ end
+ end
+
+ # TODO: BT - Helper Examples should proxy method_missing to a Rails View instance.
+ # When that is done, remove this method
+ describe HelperExampleGroup, "#protect_against_forgery?", :type => :helper do
+ it "should return false" do
+ protect_against_forgery?.should be_false
+ end
+ end
+ end
+ end
+end
+
+module Bug11223
+ # see http://rubyforge.org/tracker/index.php?func=detail&aid=11223&group_id=797&atid=3149
+ describe 'Accessing flash from helper spec', :type => :helper do
+ it 'should not raise an error' do
+ lambda { flash['test'] }.should_not raise_error
+ end
+ end
+end
+
+module Spec
+ module Rails
+ module Example
+ describe HelperExampleGroup do
+ it "should clear its name from the description" do
+ group = describe("foo", :type => :helper) do
+ $nested_group = describe("bar") do
+ end
+ end
+ group.description.to_s.should == "foo"
+ $nested_group.description.to_s.should == "foo bar"
+ end
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/ivar_proxy_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/ivar_proxy_spec.rb
new file mode 100644
index 0000000..af67293
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/ivar_proxy_spec.rb
@@ -0,0 +1,64 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe "IvarProxy setup", :shared => true do
+ before do
+ @object = Object.new
+ @proxy = Spec::Rails::Example::IvarProxy.new(@object)
+ end
+end
+
+describe "IvarProxy" do
+ it_should_behave_like "IvarProxy setup"
+
+ it "has [] accessor" do
+ @proxy['foo'] = 'bar'
+ @object.instance_variable_get(:@foo).should == 'bar'
+ @proxy['foo'].should == 'bar'
+ end
+
+ it "iterates through each element like a Hash" do
+ values = {
+ 'foo' => 1,
+ 'bar' => 2,
+ 'baz' => 3
+ }
+ @proxy['foo'] = values['foo']
+ @proxy['bar'] = values['bar']
+ @proxy['baz'] = values['baz']
+
+ @proxy.each do |key, value|
+ key.should == key
+ value.should == values[key]
+ end
+ end
+
+ it "detects the presence of a key" do
+ @proxy['foo'] = 'bar'
+ @proxy.has_key?('foo').should == true
+ @proxy.has_key?('bar').should == false
+ end
+end
+
+describe "IvarProxy", "#delete" do
+ it_should_behave_like "IvarProxy setup"
+
+ it "deletes the element with key" do
+ @proxy['foo'] = 'bar'
+ @proxy.delete('foo').should == 'bar'
+ @proxy['foo'].should be_nil
+ end
+
+ it "deletes nil instance variables" do
+ @proxy['foo'] = nil
+ @object.instance_variables.should include("@foo")
+ @proxy.delete('foo').should == nil
+ @proxy['foo'].should be_nil
+ @object.instance_variables.should_not include("@foo")
+ end
+
+ it "returns nil when key does not exist" do
+ @proxy['foo'].should be_nil
+ @proxy.delete('foo').should == nil
+ @proxy['foo'].should be_nil
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/model_spec_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/model_spec_spec.rb
new file mode 100644
index 0000000..938744d
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/model_spec_spec.rb
@@ -0,0 +1,18 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+module Spec
+ module Rails
+ module Example
+ describe ModelExampleGroup do
+ it "should clear its name from the description" do
+ group = describe("foo", :type => :model) do
+ $nested_group = describe("bar") do
+ end
+ end
+ group.description.to_s.should == "foo"
+ $nested_group.description.to_s.should == "foo bar"
+ end
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/shared_behaviour_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/shared_behaviour_spec.rb
new file mode 100644
index 0000000..ef19817
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/shared_behaviour_spec.rb
@@ -0,0 +1,16 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe "A shared view example_group", :shared => true do
+ it "should have some tag with some text" do
+ response.should have_tag('div', 'This is text from a method in the ViewSpecHelper')
+ end
+end
+
+describe "A view example_group", :type => :view do
+ it_should_behave_like "A shared view example_group"
+
+ before(:each) do
+ render "view_spec/implicit_helper"
+ end
+end
+
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/test_unit_assertion_accessibility_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/test_unit_assertion_accessibility_spec.rb
new file mode 100644
index 0000000..b7a8386
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/test_unit_assertion_accessibility_spec.rb
@@ -0,0 +1,33 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe "assert_equal", :shared => true do
+ it "like assert_equal" do
+ assert_equal 1, 1
+ lambda {
+ assert_equal 1, 2
+ }.should raise_error(Test::Unit::AssertionFailedError)
+ end
+end
+
+describe "A model spec should be able to access 'test/unit' assertions", :type => :model do
+ it_should_behave_like "assert_equal"
+end
+
+describe "A view spec should be able to access 'test/unit' assertions", :type => :view do
+ it_should_behave_like "assert_equal"
+end
+
+describe "A helper spec should be able to access 'test/unit' assertions", :type => :helper do
+ it_should_behave_like "assert_equal"
+end
+
+describe "A controller spec with integrated views should be able to access 'test/unit' assertions", :type => :controller do
+ controller_name :controller_spec
+ integrate_views
+ it_should_behave_like "assert_equal"
+end
+
+describe "A controller spec should be able to access 'test/unit' assertions", :type => :controller do
+ controller_name :controller_spec
+ it_should_behave_like "assert_equal"
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/example/view_spec_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/example/view_spec_spec.rb
new file mode 100644
index 0000000..b608550
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/example/view_spec_spec.rb
@@ -0,0 +1,263 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe "A template with an implicit helper", :type => :view do
+ before(:each) do
+ render "view_spec/implicit_helper"
+ end
+
+ it "should include the helper" do
+ response.should have_tag('div', :content => "This is text from a method in the ViewSpecHelper")
+ end
+
+ it "should include the application helper" do
+ response.should have_tag('div', :content => "This is text from a method in the ApplicationHelper")
+ end
+
+ it "should have access to named routes" do
+ rspec_on_rails_specs_url.should == "http://test.host/rspec_on_rails_specs"
+ rspec_on_rails_specs_path.should == "/rspec_on_rails_specs"
+ end
+end
+
+describe "A template requiring an explicit helper", :type => :view do
+ before(:each) do
+ render "view_spec/explicit_helper", :helper => 'explicit'
+ end
+
+ it "should include the helper if specified" do
+ response.should have_tag('div', :content => "This is text from a method in the ExplicitHelper")
+ end
+
+ it "should include the application helper" do
+ response.should have_tag('div', :content => "This is text from a method in the ApplicationHelper")
+ end
+end
+
+describe "A template requiring multiple explicit helpers", :type => :view do
+ before(:each) do
+ render "view_spec/multiple_helpers", :helpers => ['explicit', 'more_explicit']
+ end
+
+ it "should include all specified helpers" do
+ response.should have_tag('div', :content => "This is text from a method in the ExplicitHelper")
+ response.should have_tag('div', :content => "This is text from a method in the MoreExplicitHelper")
+ end
+
+ it "should include the application helper" do
+ response.should have_tag('div', :content => "This is text from a method in the ApplicationHelper")
+ end
+end
+
+describe "Message Expectations on helper methods", :type => :view do
+ it "should work" do
+ template.should_receive(:method_in_plugin_application_helper).and_return('alternate message 1')
+ render "view_spec/implicit_helper"
+ response.body.should =~ /alternate message 1/
+ end
+
+ it "should work twice" do
+ template.should_receive(:method_in_plugin_application_helper).and_return('alternate message 2')
+ render "view_spec/implicit_helper"
+ response.body.should =~ /alternate message 2/
+ end
+end
+
+describe "A template that includes a partial", :type => :view do
+ def render!
+ render "view_spec/template_with_partial"
+ end
+
+ it "should render the enclosing template" do
+ render!
+ response.should have_tag('div', "method_in_partial in ViewSpecHelper")
+ end
+
+ it "should render the partial" do
+ render!
+ response.should have_tag('div', "method_in_template_with_partial in ViewSpecHelper")
+ end
+
+ it "should include the application helper" do
+ render!
+ response.should have_tag('div', "This is text from a method in the ApplicationHelper")
+ end
+
+ it "should pass expect_render with the right partial" do
+ template.expect_render(:partial => 'partial')
+ render!
+ template.verify_rendered
+ end
+
+ it "should fail expect_render with the wrong partial" do
+ template.expect_render(:partial => 'non_existent')
+ render!
+ begin
+ template.verify_rendered
+ rescue Spec::Mocks::MockExpectationError => e
+ ensure
+ e.backtrace.find{|line| line =~ /view_spec_spec\.rb\:92/}.should_not be_nil
+ end
+ end
+
+ it "should pass expect_render when a partial is expected twice and happens twice" do
+ template.expect_render(:partial => 'partial_used_twice').twice
+ render!
+ template.verify_rendered
+ end
+
+ it "should pass expect_render when a partial is expected once and happens twice" do
+ template.expect_render(:partial => 'partial_used_twice')
+ render!
+ begin
+ template.verify_rendered
+ rescue Spec::Mocks::MockExpectationError => e
+ ensure
+ e.backtrace.find{|line| line =~ /view_spec_spec\.rb\:109/}.should_not be_nil
+ end
+ end
+
+ it "should fail expect_render with the right partial but wrong options" do
+ template.expect_render(:partial => 'partial', :locals => {:thing => Object.new})
+ render!
+ lambda {template.verify_rendered}.should raise_error(Spec::Mocks::MockExpectationError)
+ end
+end
+
+describe "A partial that includes a partial", :type => :view do
+ it "should support expect_render with nested partial" do
+ obj = Object.new
+ template.expect_render(:partial => 'partial', :object => obj)
+ render :partial => "view_spec/partial_with_sub_partial", :locals => { :partial => obj }
+ end
+end
+
+describe "A view that includes a partial using :collection and :spacer_template", :type => :view do
+ it "should render the partial w/ spacer_tamplate" do
+ render "view_spec/template_with_partial_using_collection"
+ response.should have_tag('div',/method_in_partial/)
+ response.should have_tag('div',/ApplicationHelper/)
+ response.should have_tag('div',/ViewSpecHelper/)
+ response.should have_tag('hr#spacer')
+ end
+
+ it "should render the partial" do
+ template.expect_render(:partial => 'partial',
+ :collection => ['Alice', 'Bob'],
+ :spacer_template => 'spacer')
+ render "view_spec/template_with_partial_using_collection"
+ end
+
+end
+
+describe "A view that includes a partial using an array as partial_path", :type => :view do
+ before(:each) do
+ module ActionView::Partials
+ def render_template_with_partial_with_array_support(partial_path, local_assigns = nil, deprecated_local_assigns = nil)
+ if partial_path.is_a?(Array)
+ "Array Partial"
+ else
+ render_partial_without_array_support(partial_path, local_assigns, deprecated_local_assigns)
+ end
+ end
+
+ alias :render_partial_without_array_support :render_partial
+ alias :render_partial :render_template_with_partial_with_array_support
+ end
+
+ @array = ['Alice', 'Bob']
+ assigns[:array] = @array
+ end
+
+ after(:each) do
+ module ActionView::Partials
+ alias :render_template_with_partial_with_array_support :render_partial
+ alias :render_partial :render_partial_without_array_support
+ undef render_template_with_partial_with_array_support
+ end
+ end
+
+ it "should render have the array passed through to render_partial without modification" do
+ render "view_spec/template_with_partial_with_array"
+ response.body.should match(/^Array Partial$/)
+ end
+end
+
+describe "Different types of renders (not :template)", :type => :view do
+ it "should render partial with local" do
+ render :partial => "view_spec/partial_with_local_variable", :locals => {:x => "Ender"}
+ response.should have_tag('div', :content => "Ender")
+ end
+end
+
+describe "A view", :type => :view do
+ before(:each) do
+ session[:key] = "session"
+ params[:key] = "params"
+ flash[:key] = "flash"
+ render "view_spec/accessor"
+ end
+
+ it "should have access to session data" do
+ response.should have_tag("div#session", "session")
+ end
+
+ specify "should have access to params data" do
+ response.should have_tag("div#params", "params")
+ end
+
+ it "should have access to flash data" do
+ response.should have_tag("div#flash", "flash")
+ end
+end
+
+describe "A view with a form_tag", :type => :view do
+ it "should render the right action" do
+ render "view_spec/entry_form"
+ response.should have_tag("form[action=?]","/view_spec/entry_form")
+ end
+end
+
+describe "An instantiated ViewExampleGroupController", :type => :view do
+ before do
+ render "view_spec/foo/show"
+ end
+
+ it "should return the name of the real controller that it replaces" do
+ @controller.controller_name.should == 'foo'
+ end
+
+ it "should return the path of the real controller that it replaces" do
+ @controller.controller_path.should == 'view_spec/foo'
+ end
+end
+
+module Spec
+ module Rails
+ module Example
+ describe ViewExampleGroup do
+ it "should clear its name from the description" do
+ group = describe("foo", :type => :view) do
+ $nested_group = describe("bar") do
+ end
+ end
+ group.description.to_s.should == "foo"
+ $nested_group.description.to_s.should == "foo bar"
+ end
+
+ it "should clear ActionView::Base.base_view_path on teardown" do
+ ViewExampleGroup.class_eval do
+ alias_method(:ensure_that_base_view_path_is_not_set_across_example_groups_orig,
+ :ensure_that_base_view_path_is_not_set_across_example_groups)
+ define_method(:ensure_that_base_view_path_is_not_set_across_example_groups){
+ $base_view_path_cleared = true
+ ensure_that_base_view_path_is_not_set_across_example_groups_orig
+ }
+ end
+ describe("base_view_path_cleared flag", :type => :view) do
+ it { $base_view_path_cleared.should be_true }
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/extensions/action_controller_rescue_action_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/extensions/action_controller_rescue_action_spec.rb
new file mode 100644
index 0000000..c257545
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/extensions/action_controller_rescue_action_spec.rb
@@ -0,0 +1,54 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+module ActionController
+ describe "Rescue", "#rescue_action in default mode" do
+ before(:each) do
+ @fixture = Object.new
+ @fixture.extend ActionController::Rescue
+ class << @fixture
+ public :rescue_action
+ end
+ end
+
+ it "should raise the passed in exception so examples fail fast" do
+ proc {@fixture.rescue_action(RuntimeError.new("Foobar"))}.should raise_error(RuntimeError, "Foobar")
+ end
+ end
+
+ class RescueOverriddenController < ActionController::Base
+ def rescue_action(error)
+ "successfully overridden"
+ end
+ end
+
+ describe "Rescue", "#rescue_action, when overridden" do
+ before(:each) do
+ @fixture = RescueOverriddenController.new
+ end
+
+ it "should do whatever the overridden method does" do
+ @fixture.rescue_action(RuntimeError.new("Foobar")).should == "successfully overridden"
+ end
+ end
+
+ class SearchController < ActionController::Base
+ end
+
+ describe "Rescue", "#rescue_action when told to use rails error handling" do
+ before(:each) do
+ @controller = SearchController.new
+ @controller.use_rails_error_handling!
+ class << @controller
+ public :rescue_action
+ end
+ end
+
+ it "should use Rails exception handling" do
+ exception = RuntimeError.new("The Error")
+ exception.stub!(:backtrace).and_return(caller)
+ @controller.should_receive(:rescue_action_locally).with(exception)
+
+ @controller.rescue_action(exception)
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/extensions/action_view_base_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/extensions/action_view_base_spec.rb
new file mode 100644
index 0000000..599249f
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/extensions/action_view_base_spec.rb
@@ -0,0 +1,48 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+require 'spec/mocks/errors'
+
+describe ActionView::Base, "with RSpec extensions:", :type => :view do
+
+ describe "expect_render" do
+ it "should not raise when render has been received" do
+ template.expect_render(:partial => "name")
+ template.render :partial => "name"
+ end
+
+ it "should raise when render has NOT been received" do
+ template.expect_render(:partial => "name")
+ lambda {
+ template.verify_rendered
+ }.should raise_error
+ end
+
+ it "should return something (like a normal mock)" do
+ template.expect_render(:partial => "name").and_return("Little Johnny")
+ result = template.render :partial => "name"
+ result.should == "Little Johnny"
+ end
+ end
+
+ describe "stub_render" do
+ it "should not raise when stubbing and render has been received" do
+ template.stub_render(:partial => "name")
+ template.render :partial => "name"
+ end
+
+ it "should not raise when stubbing and render has NOT been received" do
+ template.stub_render(:partial => "name")
+ end
+
+ it "should not raise when stubbing and render has been received with different options" do
+ template.stub_render(:partial => "name")
+ template.render :partial => "view_spec/spacer"
+ end
+
+ it "should not raise when stubbing and expecting and render has been received" do
+ template.stub_render(:partial => "name")
+ template.expect_render(:partial => "name")
+ template.render(:partial => "name")
+ end
+ end
+
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/extensions/active_record_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/extensions/active_record_spec.rb
new file mode 100644
index 0000000..95d43b2
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/extensions/active_record_spec.rb
@@ -0,0 +1,14 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe "A model" do
+ fixtures :things
+ it "should tell you its required fields" do
+ Thing.new.should have(1).error_on(:name)
+ end
+
+ it "should tell you how many records it has" do
+ Thing.should have(:no).records
+ Thing.create(:name => "THE THING")
+ Thing.should have(1).record
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/matchers/assert_select_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/matchers/assert_select_spec.rb
new file mode 100644
index 0000000..bdc8cf0
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/matchers/assert_select_spec.rb
@@ -0,0 +1,783 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+# assert_select plugins for Rails
+#
+# Copyright (c) 2006 Assaf Arkin, under Creative Commons Attribution and/or MIT License
+# Developed for http://co.mments.com
+# Code and documention: http://labnotes.org
+
+class AssertSelectController < ActionController::Base
+
+ def response=(content)
+ @content = content
+ end
+
+ #NOTE - this is commented because response is implemented in lib/spec/rails/context/controller
+ # def response(&block)
+ # @update = block
+ # end
+ #
+ def html()
+ render :text=>@content, :layout=>false, :content_type=>Mime::HTML
+ @content = nil
+ end
+
+ def rjs()
+ update = @update
+ render :update do |page|
+ update.call page
+ end
+ @update = nil
+ end
+
+ def xml()
+ render :text=>@content, :layout=>false, :content_type=>Mime::XML
+ @content = nil
+ end
+
+ def rescue_action(e)
+ raise e
+ end
+
+end
+
+class AssertSelectMailer < ActionMailer::Base
+
+ def test(html)
+ recipients "test <[email protected]>"
+ from "[email protected]"
+ subject "Test e-mail"
+ part :content_type=>"text/html", :body=>html
+ end
+
+end
+
+module AssertSelectSpecHelpers
+ def render_html(html)
+ @controller.response = html
+ get :html
+ end
+
+ def render_rjs(&block)
+ clear_response
+ @controller.response &block
+ get :rjs
+ end
+
+ def render_xml(xml)
+ @controller.response = xml
+ get :xml
+ end
+
+ def first_non_rspec_line_in_backtrace_of(error)
+ rspec_path = File.join('rspec', 'lib', 'spec')
+ error.backtrace.reject { |line|
+ line =~ /#{rspec_path}/
+ }.first
+ end
+
+ private
+ # necessary for 1.2.1
+ def clear_response
+ render_html("")
+ end
+end
+
+unless defined?(SpecFailed)
+ SpecFailed = Spec::Expectations::ExpectationNotMetError
+end
+
+describe "should have_tag", :type => :controller do
+ include AssertSelectSpecHelpers
+ controller_name :assert_select
+ integrate_views
+
+ it "should find specific numbers of elements" do
+ render_html %Q{<div id="1"></div><div id="2"></div>}
+ response.should have_tag( "div" )
+ response.should have_tag("div", 2)
+ lambda { response.should_not have_tag("div") }.should raise_error(SpecFailed, "should not have tag(\"div\"), but did")
+
+ lambda { response.should have_tag("div", 3) }.should raise_error(SpecFailed)
+ lambda { response.should have_tag("p") }.should raise_error(SpecFailed)
+ end
+
+ it "should expect to find elements when using true" do
+ render_html %Q{<div id="1"></div><div id="2"></div>}
+ response.should have_tag( "div", true )
+ lambda { response.should have_tag( "p", true )}.should raise_error(SpecFailed)
+ end
+
+ it "should expect to not find elements when using false" do
+ render_html %Q{<div id="1"></div><div id="2"></div>}
+ response.should have_tag( "p", false )
+ lambda { response.should have_tag( "div", false )}.should raise_error(SpecFailed)
+ end
+
+
+ it "should match submitted text using text or regexp" do
+ render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
+ response.should have_tag("div", "foo")
+ response.should have_tag("div", /(foo|bar)/)
+ response.should have_tag("div", :text=>"foo")
+ response.should have_tag("div", :text=>/(foo|bar)/)
+
+ lambda { response.should have_tag("div", "bar") }.should raise_error(SpecFailed)
+ lambda { response.should have_tag("div", :text=>"bar") }.should raise_error(SpecFailed)
+ lambda { response.should have_tag("p", :text=>"foo") }.should raise_error(SpecFailed)
+
+ lambda { response.should have_tag("div", /foobar/) }.should raise_error(SpecFailed)
+ lambda { response.should have_tag("div", :text=>/foobar/) }.should raise_error(SpecFailed)
+ lambda { response.should have_tag("p", :text=>/foo/) }.should raise_error(SpecFailed)
+ end
+
+ it "should use submitted message" do
+ render_html %Q{nothing here}
+ lambda {
+ response.should have_tag("div", {}, "custom message")
+ }.should raise_error(SpecFailed, /custom message/)
+ end
+
+ it "should match submitted html" do
+ render_html %Q{<p>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</p>}
+ text = "\"This is not a big problem,\" he said."
+ html = "<em>\"This is <strong>not</strong> a big problem,\"</em> he said."
+ response.should have_tag("p", text)
+ lambda { response.should have_tag("p", html) }.should raise_error(SpecFailed)
+ response.should have_tag("p", :html=>html)
+ lambda { response.should have_tag("p", :html=>text) }.should raise_error(SpecFailed)
+
+ # # No stripping for pre.
+ render_html %Q{<pre>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</pre>}
+ text = "\n\"This is not a big problem,\" he said.\n"
+ html = "\n<em>\"This is <strong>not</strong> a big problem,\"</em> he said.\n"
+ response.should have_tag("pre", text)
+ lambda { response.should have_tag("pre", html) }.should raise_error(SpecFailed)
+ response.should have_tag("pre", :html=>html)
+ lambda { response.should have_tag("pre", :html=>text) }.should raise_error(SpecFailed)
+ end
+
+ it "should match number of instances" do
+ render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
+ response.should have_tag("div", 2)
+ lambda { response.should have_tag("div", 3) }.should raise_error(SpecFailed)
+ response.should have_tag("div", 1..2)
+ lambda { response.should have_tag("div", 3..4) }.should raise_error(SpecFailed)
+ response.should have_tag("div", :count=>2)
+ lambda { response.should have_tag("div", :count=>3) }.should raise_error(SpecFailed)
+ response.should have_tag("div", :minimum=>1)
+ response.should have_tag("div", :minimum=>2)
+ lambda { response.should have_tag("div", :minimum=>3) }.should raise_error(SpecFailed)
+ response.should have_tag("div", :maximum=>2)
+ response.should have_tag("div", :maximum=>3)
+ lambda { response.should have_tag("div", :maximum=>1) }.should raise_error(SpecFailed)
+ response.should have_tag("div", :minimum=>1, :maximum=>2)
+ lambda { response.should have_tag("div", :minimum=>3, :maximum=>4) }.should raise_error(SpecFailed)
+ end
+
+ it "substitution values" do
+ render_html %Q{<div id="1">foo</div><div id="2">foo</div><span id="3"></span>}
+ response.should have_tag("div#?", /\d+/) do |elements| #using do/end
+ elements.size.should == 2
+ end
+ response.should have_tag("div#?", /\d+/) { |elements| #using {}
+ elements.size.should == 2
+ }
+ lambda {
+ response.should have_tag("div#?", /\d+/) do |elements|
+ elements.size.should == 3
+ end
+ }.should raise_error(SpecFailed, "expected: 3,\n got: 2 (using ==)")
+
+ lambda {
+ response.should have_tag("div#?", /\d+/) { |elements|
+ elements.size.should == 3
+ }
+ }.should raise_error(SpecFailed, "expected: 3,\n got: 2 (using ==)")
+
+ response.should have_tag("div#?", /\d+/) do |elements|
+ elements.size.should == 2
+ with_tag("#1")
+ with_tag("#2")
+ without_tag("#3")
+ end
+ end
+
+ #added for RSpec
+ it "nested tags in form" do
+ render_html %Q{
+ <form action="test">
+ <input type="text" name="email">
+ </form>
+ <form action="other">
+ <input type="text" name="other_input">
+ </form>
+ }
+ response.should have_tag("form[action=test]") { |form|
+ with_tag("input[type=text][name=email]")
+ }
+ response.should have_tag("form[action=test]") { |form|
+ with_tag("input[type=text][name=email]")
+ }
+
+ lambda {
+ response.should have_tag("form[action=test]") { |form|
+ with_tag("input[type=text][name=other_input]")
+ }
+ }.should raise_error(SpecFailed)
+
+ lambda {
+ response.should have_tag("form[action=test]") {
+ with_tag("input[type=text][name=other_input]")
+ }
+ }.should raise_error(SpecFailed)
+ end
+
+ it "should report the correct line number for a nested failed expectation" do
+ render_html %Q{
+ <form action="test">
+ <input type="text" name="email">
+ </form>
+ }
+ begin
+ response.should have_tag("form[action=test]") {
+ @expected_error_line = __LINE__; should have_tag("input[type=text][name=other_input]")
+ }
+ rescue => e
+ first_non_rspec_line_in_backtrace_of(e).should =~
+ /#{File.basename(__FILE__)}:#{@expected_error_line}/
+ else
+ fail
+ end
+ end
+
+ it "should report the correct line number for a nested raised exception" do
+ render_html %Q{
+ <form action="test">
+ <input type="text" name="email">
+ </form>
+ }
+ begin
+ response.should have_tag("form[action=test]") {
+ @expected_error_line = __LINE__; raise "Failed!"
+ }
+ rescue => e
+ first_non_rspec_line_in_backtrace_of(e).should =~
+ /#{File.basename(__FILE__)}:#{@expected_error_line}/
+ else
+ fail
+ end
+ end
+
+ it "should report the correct line number for a nested failed test/unit assertion" do
+ pending "Doesn't work at the moment. Do we want to support this?" do
+ render_html %Q{
+ <form action="test">
+ <input type="text" name="email">
+ </form>
+ }
+ begin
+ response.should have_tag("form[action=test]") {
+ @expected_error_line = __LINE__; assert false
+ }
+ rescue => e
+ first_non_rspec_line_in_backtrace_of(e).should =~
+ /#{File.basename(__FILE__)}:#{@expected_error_line}/
+ else
+ fail
+ end
+ end
+ end
+
+
+ it "beatles" do
+ unless defined?(BEATLES)
+ BEATLES = [
+ ["John", "Guitar"],
+ ["George", "Guitar"],
+ ["Paul", "Bass"],
+ ["Ringo", "Drums"]
+ ]
+ end
+
+ render_html %Q{
+ <div id="beatles">
+ <div class="beatle">
+ <h2>John</h2><p>Guitar</p>
+ </div>
+ <div class="beatle">
+ <h2>George</h2><p>Guitar</p>
+ </div>
+ <div class="beatle">
+ <h2>Paul</h2><p>Bass</p>
+ </div>
+ <div class="beatle">
+ <h2>Ringo</h2><p>Drums</p>
+ </div>
+ </div>
+ }
+ response.should have_tag("div#beatles>div[class=\"beatle\"]", 4)
+
+ response.should have_tag("div#beatles>div.beatle") {
+ BEATLES.each { |name, instrument|
+ with_tag("div.beatle>h2", name)
+ with_tag("div.beatle>p", instrument)
+ without_tag("div.beatle>span")
+ }
+ }
+ end
+
+ it "assert_select_text_match" do
+ render_html %Q{<div id="1"><span>foo</span></div><div id="2"><span>bar</span></div>}
+ response.should have_tag("div") do |divs|
+ with_tag("div", "foo")
+ with_tag("div", "bar")
+ with_tag("div", /\w*/)
+ with_tag("div", /\w*/, :count=>2)
+ without_tag("div", :text=>"foo", :count=>2)
+ with_tag("div", :html=>"<span>bar</span>")
+ with_tag("div", :html=>"<span>bar</span>")
+ with_tag("div", :html=>/\w*/)
+ with_tag("div", :html=>/\w*/, :count=>2)
+ without_tag("div", :html=>"<span>foo</span>", :count=>2)
+ end
+ end
+
+
+ it "assert_select_from_rjs with one item" do
+ render_rjs do |page|
+ page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>"
+ end
+ response.should have_tag("div") { |elements|
+ elements.size.should == 2
+ with_tag("#1")
+ with_tag("#2")
+ }
+
+ lambda {
+ response.should have_tag("div") { |elements|
+ elements.size.should == 2
+ with_tag("#1")
+ with_tag("#3")
+ }
+ }.should raise_error(SpecFailed)
+
+ lambda {
+ response.should have_tag("div") { |elements|
+ elements.size.should == 2
+ with_tag("#1")
+ without_tag("#2")
+ }
+ }.should raise_error(SpecFailed, "should not have tag(\"#2\"), but did")
+
+ lambda {
+ response.should have_tag("div") { |elements|
+ elements.size.should == 3
+ with_tag("#1")
+ with_tag("#2")
+ }
+ }.should raise_error(SpecFailed)
+
+
+ response.should have_tag("div#?", /\d+/) { |elements|
+ with_tag("#1")
+ with_tag("#2")
+ }
+ end
+
+ it "assert_select_from_rjs with multiple items" do
+ render_rjs do |page|
+ page.replace_html "test", "<div id=\"1\">foo</div>"
+ page.replace_html "test2", "<div id=\"2\">foo</div>"
+ end
+ response.should have_tag("div")
+ response.should have_tag("div") { |elements|
+ elements.size.should == 2
+ with_tag("#1")
+ with_tag("#2")
+ }
+
+ lambda {
+ response.should have_tag("div") { |elements|
+ with_tag("#3")
+ }
+ }.should raise_error(SpecFailed)
+ end
+end
+
+describe "css_select", :type => :controller do
+ include AssertSelectSpecHelpers
+ controller_name :assert_select
+ integrate_views
+
+ it "can select tags from html" do
+ render_html %Q{<div id="1"></div><div id="2"></div>}
+ css_select("div").size.should == 2
+ css_select("p").size.should == 0
+ end
+
+
+ it "can select nested tags from html" do
+ render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
+ response.should have_tag("div#?", /\d+/) { |elements|
+ css_select(elements[0], "div").should have(1).element
+ css_select(elements[1], "div").should have(1).element
+ }
+ response.should have_tag("div") {
+ css_select("div").should have(2).elements
+ css_select("div").each { |element|
+ # Testing as a group is one thing
+ css_select("#1,#2").should have(2).elements
+ # Testing individually is another
+ css_select("#1").should have(1).element
+ css_select("#2").should have(1).element
+ }
+ }
+ end
+
+ it "can select nested tags from rjs (one result)" do
+ render_rjs do |page|
+ page.replace_html "test", "<div id=\"1\">foo</div>\n<div id=\"2\">foo</div>"
+ end
+ css_select("div").should have(2).elements
+ css_select("#1").should have(1).element
+ css_select("#2").should have(1).element
+ end
+
+ it "can select nested tags from rjs (two results)" do
+ render_rjs do |page|
+ page.replace_html "test", "<div id=\"1\">foo</div>"
+ page.replace_html "test2", "<div id=\"2\">foo</div>"
+ end
+ css_select("div").should have(2).elements
+ css_select("#1").should have(1).element
+ css_select("#2").should have(1).element
+ end
+
+end
+
+describe "have_rjs behaviour_type", :type => :controller do
+ include AssertSelectSpecHelpers
+ controller_name :assert_select
+ integrate_views
+
+ before(:each) do
+ render_rjs do |page|
+ page.replace "test1", "<div id=\"1\">foo</div>"
+ page.replace_html "test2", "<div id=\"2\">bar</div><div id=\"3\">none</div>"
+ page.insert_html :top, "test3", "<div id=\"4\">loopy</div>"
+ page.hide "test4"
+ page["test5"].hide
+ end
+ end
+
+ it "should pass if any rjs exists" do
+ response.should have_rjs
+ end
+
+ it "should fail if no rjs exists" do
+ render_rjs do |page|
+ end
+ lambda do
+ response.should have_rjs
+ end.should raise_error(SpecFailed)
+ end
+
+ it "should find all rjs from multiple statements" do
+ response.should have_rjs do
+ with_tag("#1")
+ with_tag("#2")
+ with_tag("#3")
+ # with_tag("#4")
+ # with_tag("#5")
+ end
+ end
+
+ it "should find by id" do
+ response.should have_rjs("test1") { |rjs|
+ rjs.size.should == 1
+ with_tag("div", 1)
+ with_tag("div#1", "foo")
+ }
+
+ lambda do
+ response.should have_rjs("test1") { |rjs|
+ rjs.size.should == 1
+ without_tag("div#1", "foo")
+ }
+ end.should raise_error(SpecFailed, "should not have tag(\"div#1\", \"foo\"), but did")
+
+ response.should have_rjs("test2") { |rjs|
+ rjs.size.should == 2
+ with_tag("div", 2)
+ with_tag("div#2", "bar")
+ with_tag("div#3", "none")
+ }
+ # response.should have_rjs("test4")
+ # response.should have_rjs("test5")
+ end
+
+ # specify "should find rjs using :hide" do
+ # response.should have_rjs(:hide)
+ # response.should have_rjs(:hide, "test4")
+ # response.should have_rjs(:hide, "test5")
+ # lambda do
+ # response.should have_rjs(:hide, "test3")
+ # end.should raise_error(SpecFailed)
+ # end
+
+ it "should find rjs using :replace" do
+ response.should have_rjs(:replace) { |rjs|
+ with_tag("div", 1)
+ with_tag("div#1", "foo")
+ }
+ response.should have_rjs(:replace, "test1") { |rjs|
+ with_tag("div", 1)
+ with_tag("div#1", "foo")
+ }
+ lambda {
+ response.should have_rjs(:replace, "test2")
+ }.should raise_error(SpecFailed)
+
+ lambda {
+ response.should have_rjs(:replace, "test3")
+ }.should raise_error(SpecFailed)
+ end
+
+ it "should find rjs using :replace_html" do
+ response.should have_rjs(:replace_html) { |rjs|
+ with_tag("div", 2)
+ with_tag("div#2", "bar")
+ with_tag("div#3", "none")
+ }
+
+ response.should have_rjs(:replace_html, "test2") { |rjs|
+ with_tag("div", 2)
+ with_tag("div#2", "bar")
+ with_tag("div#3", "none")
+ }
+
+ lambda {
+ response.should have_rjs(:replace_html, "test1")
+ }.should raise_error(SpecFailed)
+
+ lambda {
+ response.should have_rjs(:replace_html, "test3")
+ }.should raise_error(SpecFailed)
+ end
+
+ it "should find rjs using :insert_html (non-positioned)" do
+ response.should have_rjs(:insert_html) { |rjs|
+ with_tag("div", 1)
+ with_tag("div#4", "loopy")
+ }
+
+ response.should have_rjs(:insert_html, "test3") { |rjs|
+ with_tag("div", 1)
+ with_tag("div#4", "loopy")
+ }
+
+ lambda {
+ response.should have_rjs(:insert_html, "test1")
+ }.should raise_error(SpecFailed)
+
+ lambda {
+ response.should have_rjs(:insert_html, "test2")
+ }.should raise_error(SpecFailed)
+ end
+
+ it "should find rjs using :insert (positioned)" do
+ render_rjs do |page|
+ page.insert_html :top, "test1", "<div id=\"1\">foo</div>"
+ page.insert_html :bottom, "test2", "<div id=\"2\">bar</div>"
+ page.insert_html :before, "test3", "<div id=\"3\">none</div>"
+ page.insert_html :after, "test4", "<div id=\"4\">loopy</div>"
+ end
+ response.should have_rjs(:insert, :top) do
+ with_tag("div", 1)
+ with_tag("#1")
+ end
+ response.should have_rjs(:insert, :top, "test1") do
+ with_tag("div", 1)
+ with_tag("#1")
+ end
+ lambda {
+ response.should have_rjs(:insert, :top, "test2")
+ }.should raise_error(SpecFailed)
+ response.should have_rjs(:insert, :bottom) {|rjs|
+ with_tag("div", 1)
+ with_tag("#2")
+ }
+ response.should have_rjs(:insert, :bottom, "test2") {|rjs|
+ with_tag("div", 1)
+ with_tag("#2")
+ }
+ response.should have_rjs(:insert, :before) {|rjs|
+ with_tag("div", 1)
+ with_tag("#3")
+ }
+ response.should have_rjs(:insert, :before, "test3") {|rjs|
+ with_tag("div", 1)
+ with_tag("#3")
+ }
+ response.should have_rjs(:insert, :after) {|rjs|
+ with_tag("div", 1)
+ with_tag("#4")
+ }
+ response.should have_rjs(:insert, :after, "test4") {|rjs|
+ with_tag("div", 1)
+ with_tag("#4")
+ }
+ end
+end
+
+describe "send_email behaviour_type", :type => :controller do
+ include AssertSelectSpecHelpers
+ controller_name :assert_select
+ integrate_views
+
+ before(:each) do
+ ActionMailer::Base.delivery_method = :test
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.deliveries = []
+ end
+
+ after(:each) do
+ ActionMailer::Base.deliveries.clear
+ end
+
+ it "should fail with nothing sent" do
+ response.should_not send_email
+ lambda {
+ response.should send_email{}
+ }.should raise_error(SpecFailed, /No e-mail in delivery list./)
+ end
+
+ it "should pass otherwise" do
+ AssertSelectMailer.deliver_test "<div><p>foo</p><p>bar</p></div>"
+ response.should send_email
+ lambda {
+ response.should_not send_email
+ }.should raise_error(SpecFailed)
+ response.should send_email{}
+ response.should send_email {
+ with_tag("div:root") {
+ with_tag("p:first-child", "foo")
+ with_tag("p:last-child", "bar")
+ }
+ }
+
+ lambda {
+ response.should_not send_email
+ }.should raise_error(SpecFailed, "should not send email, but did")
+ end
+
+end
+
+# describe "An rjs call to :visual_effect, a 'should have_rjs' spec with",
+# :type => :view do
+#
+# before do
+# render 'rjs_spec/visual_effect'
+# end
+#
+# it "should pass with the correct element name" do
+# response.should have_rjs(:effect, :fade, 'mydiv')
+# end
+#
+# it "should fail the wrong element name" do
+# lambda {
+# response.should have_rjs(:effect, :fade, 'wrongname')
+# }.should raise_error(SpecFailed)
+# end
+#
+# it "should fail with the correct element but the wrong command" do
+# lambda {
+# response.should have_rjs(:effect, :puff, 'mydiv')
+# }.should raise_error(SpecFailed)
+# end
+#
+# end
+#
+# describe "An rjs call to :visual_effect for a toggle, a 'should have_rjs' spec with",
+# :type => :view do
+#
+# before do
+# render 'rjs_spec/visual_toggle_effect'
+# end
+#
+# it "should pass with the correct element name" do
+# response.should have_rjs(:effect, :toggle_blind, 'mydiv')
+# end
+#
+# it "should fail with the wrong element name" do
+# lambda {
+# response.should have_rjs(:effect, :toggle_blind, 'wrongname')
+# }.should raise_error(SpecFailed)
+# end
+#
+# it "should fail the correct element but the wrong command" do
+# lambda {
+# response.should have_rjs(:effect, :puff, 'mydiv')
+# }.should raise_error(SpecFailed)
+# end
+#
+# end
+
+describe "string.should have_tag", :type => :helper do
+ include AssertSelectSpecHelpers
+
+ it "should find root element" do
+ "<p>a paragraph</p>".should have_tag("p", "a paragraph")
+ end
+
+ it "should not find non-existent element" do
+ lambda do
+ "<p>a paragraph</p>".should have_tag("p", "wrong text")
+ end.should raise_error(SpecFailed)
+ end
+
+ it "should find child element" do
+ "<div><p>a paragraph</p></div>".should have_tag("p", "a paragraph")
+ end
+
+ it "should find nested element" do
+ "<div><p>a paragraph</p></div>".should have_tag("div") do
+ with_tag("p", "a paragraph")
+ end
+ end
+
+ it "should not find wrong nested element" do
+ lambda do
+ "<div><p>a paragraph</p></div>".should have_tag("div") do
+ with_tag("p", "wrong text")
+ end
+ end.should raise_error(SpecFailed)
+ end
+end
+
+describe "have_tag", :type => :controller do
+ include AssertSelectSpecHelpers
+ controller_name :assert_select
+ integrate_views
+
+ it "should work exactly the same as assert_select" do
+ render_html %Q{
+ <div id="wrapper">foo
+ <div class="piece">
+ <h3>Text</h3>
+ </div>
+ <div class="piece">
+ <h3>Another</h3>
+ </div>
+ </div>
+ }
+
+ assert_select "#wrapper .piece h3", :text => "Text"
+ assert_select "#wrapper .piece h3", :text => "Another"
+
+ response.should have_tag("#wrapper .piece h3", :text => "Text")
+ response.should have_tag("#wrapper .piece h3", :text => "Another")
+ end
+end
+
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/matchers/description_generation_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/matchers/description_generation_spec.rb
new file mode 100644
index 0000000..4fd2bcd
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/matchers/description_generation_spec.rb
@@ -0,0 +1,37 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+class DescriptionGenerationSpecController < ActionController::Base
+ def render_action
+ end
+
+ def redirect_action
+ redirect_to :action => :render_action
+ end
+end
+
+describe "Description generation", :type => :controller do
+ controller_name :description_generation_spec
+
+ after(:each) do
+ Spec::Matchers.clear_generated_description
+ end
+
+ it "should generate description for render_template" do
+ get 'render_action'
+ response.should render_template("render_action")
+ Spec::Matchers.generated_description.should == "should render template \"render_action\""
+ end
+
+ it "should generate description for render_template with full path" do
+ get 'render_action'
+ response.should render_template("description_generation_spec/render_action")
+ Spec::Matchers.generated_description.should == "should render template \"description_generation_spec/render_action\""
+ end
+
+ it "should generate description for redirect_to" do
+ get 'redirect_action'
+ response.should redirect_to("http://test.host/description_generation_spec/render_action")
+ Spec::Matchers.generated_description.should == "should redirect to \"http://test.host/description_generation_spec/render_action\""
+ end
+
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/matchers/errors_on_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/matchers/errors_on_spec.rb
new file mode 100644
index 0000000..f0b9743
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/matchers/errors_on_spec.rb
@@ -0,0 +1,13 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe "error_on" do
+ it "should provide a message including the name of what the error is on" do
+ have(1).error_on(:whatever).description.should == "should have 1 error on :whatever"
+ end
+end
+
+describe "errors_on" do
+ it "should provide a message including the name of what the error is on" do
+ have(2).errors_on(:whatever).description.should == "should have 2 errors on :whatever"
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/matchers/have_text_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/matchers/have_text_spec.rb
new file mode 100644
index 0000000..93a1ef0
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/matchers/have_text_spec.rb
@@ -0,0 +1,62 @@
+require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
+
+describe "have_text" do
+
+ describe "where target is a Regexp" do
+ it 'should should match submitted text using a regexp' do
+ string = 'foo'
+ string.should have_text(/fo*/)
+ end
+ end
+
+ describe "where target is a String" do
+ it 'should match submitted text using a string' do
+ string = 'foo'
+ string.should have_text('foo')
+ end
+ end
+
+end
+
+describe "have_text",
+ :type => :controller do
+ ['isolation','integration'].each do |mode|
+ if mode == 'integration'
+ integrate_views
+ end
+
+ describe "where target is a response (in #{mode} mode)" do
+ controller_name :render_spec
+
+ it "should pass with exactly matching text" do
+ post 'text_action'
+ response.should have_text("this is the text for this action")
+ end
+
+ it "should pass with matching text (using Regexp)" do
+ post 'text_action'
+ response.should have_text(/is the text/)
+ end
+
+ it "should fail with matching text" do
+ post 'text_action'
+ lambda {
+ response.should have_text("this is NOT the text for this action")
+ }.should fail_with("expected \"this is NOT the text for this action\", got \"this is the text for this action\"")
+ end
+
+ it "should fail when a template is rendered" do
+ post 'some_action'
+ lambda {
+ response.should have_text("this is the text for this action")
+ }.should fail_with(/expected \"this is the text for this action\", got .*/)
+ end
+
+ it "should pass using should_not with incorrect text" do
+ post 'text_action'
+ response.should_not have_text("the accordian guy")
+ end
+ end
+ end
+end
+
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/matchers/redirect_to_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/matchers/redirect_to_spec.rb
new file mode 100644
index 0000000..b3c7d7a
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/matchers/redirect_to_spec.rb
@@ -0,0 +1,203 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+['isolation','integration'].each do |mode|
+ describe "redirect_to behaviour", :type => :controller do
+ if mode == 'integration'
+ integrate_views
+ end
+ controller_name :redirect_spec
+
+ it "redirected to another action" do
+ get 'action_with_redirect_to_somewhere'
+ response.should redirect_to(:action => 'somewhere')
+ end
+
+ it "redirected to another controller and action" do
+ get 'action_with_redirect_to_other_somewhere'
+ response.should redirect_to(:controller => 'render_spec', :action => 'text_action')
+ end
+
+ it "redirected to another action (with 'and return')" do
+ get 'action_with_redirect_to_somewhere_and_return'
+ response.should redirect_to(:action => 'somewhere')
+ end
+
+ it "redirected to correct path with leading /" do
+ get 'action_with_redirect_to_somewhere'
+ response.should redirect_to('/redirect_spec/somewhere')
+ end
+
+ it "redirected to correct path without leading /" do
+ get 'action_with_redirect_to_somewhere'
+ response.should redirect_to('redirect_spec/somewhere')
+ end
+
+ it "redirected to correct internal URL" do
+ get 'action_with_redirect_to_somewhere'
+ response.should redirect_to("http://test.host/redirect_spec/somewhere")
+ end
+
+ it "redirected to correct external URL" do
+ get 'action_with_redirect_to_rspec_site'
+ response.should redirect_to("http://rspec.rubyforge.org")
+ end
+
+ it "redirected :back" do
+ request.env['HTTP_REFERER'] = "http://test.host/previous/page"
+ get 'action_with_redirect_back'
+ response.should redirect_to(:back)
+ end
+
+ it "redirected :back and should redirect_to URL matches" do
+ request.env['HTTP_REFERER'] = "http://test.host/previous/page"
+ get 'action_with_redirect_back'
+ response.should redirect_to("http://test.host/previous/page")
+ end
+
+ it "redirected from within a respond_to block" do
+ get 'action_with_redirect_in_respond_to'
+ response.should redirect_to('redirect_spec/somewhere')
+ end
+
+ params_as_hash = {:action => "somewhere", :id => 1111, :param1 => "value1", :param2 => "value2"}
+
+ it "redirected to an internal URL containing a query string" do
+ get "action_with_redirect_which_creates_query_string"
+ response.should redirect_to(params_as_hash)
+ end
+
+ it "redirected to an internal URL containing a query string, one way it might be generated" do
+ get "action_with_redirect_with_query_string_order1"
+ response.should redirect_to(params_as_hash)
+ end
+
+ it "redirected to an internal URL containing a query string, another way it might be generated" do
+ get "action_with_redirect_with_query_string_order2"
+ response.should redirect_to(params_as_hash)
+ end
+
+ it "redirected to an internal URL which is unroutable but matched via a string" do
+ get "action_with_redirect_to_unroutable_url_inside_app"
+ response.should redirect_to("http://test.host/nonexistant/none")
+ end
+
+ end
+
+
+ describe "redirect_to with a controller spec in #{mode} mode and a custom request.host", :type => :controller do
+ if mode == 'integration'
+ integrate_views
+ end
+ controller_name :redirect_spec
+ before do
+ request.host = "some.custom.host"
+ end
+
+ it "should pass when redirected to another action" do
+ get 'action_with_redirect_to_somewhere'
+ response.should redirect_to(:action => 'somewhere')
+ end
+ end
+
+ describe "Given a controller spec in #{mode} mode", :type => :controller do
+ if mode == 'integration'
+ integrate_views
+ end
+ controller_name :redirect_spec
+
+ it "an action that redirects should not result in an error if no should redirect_to expectation is called" do
+ get 'action_with_redirect_to_somewhere'
+ end
+
+ it "an action that redirects should not result in an error if should_not redirect_to expectation was called, but not to that action" do
+ get 'action_with_redirect_to_somewhere'
+ response.should_not redirect_to(:action => 'another_destination')
+ end
+
+ it "an action that redirects should result in an error if should_not redirect_to expectation was called to that action" do
+ get 'action_with_redirect_to_somewhere'
+ lambda {
+ response.should_not redirect_to(:action => 'somewhere')
+ }.should fail_with("expected not to be redirected to {:action=>\"somewhere\"}, but was")
+ end
+
+ it "an action that does not redirects should not result in an error if should_not redirect_to expectation was called" do
+ get 'action_with_no_redirect'
+ response.should_not redirect_to(:action => 'any_destination')
+ end
+
+
+ end
+
+ describe "Given a controller spec in #{mode} mode, should redirect_to should fail when", :type => :controller do
+ if mode == 'integration'
+ integrate_views
+ end
+ controller_name :redirect_spec
+
+ it "redirected to wrong action" do
+ get 'action_with_redirect_to_somewhere'
+ lambda {
+ response.should redirect_to(:action => 'somewhere_else')
+ }.should fail_with("expected redirect to {:action=>\"somewhere_else\"}, got redirect to \"http://test.host/redirect_spec/somewhere\"")
+ end
+
+ it "redirected to incorrect path with leading /" do
+ get 'action_with_redirect_to_somewhere'
+ lambda {
+ response.should redirect_to('/redirect_spec/somewhere_else')
+ }.should fail_with('expected redirect to "/redirect_spec/somewhere_else", got redirect to "http://test.host/redirect_spec/somewhere"')
+ end
+
+ it "redirected to incorrect path without leading /" do
+ get 'action_with_redirect_to_somewhere'
+ lambda {
+ response.should redirect_to('redirect_spec/somewhere_else')
+ }.should fail_with('expected redirect to "redirect_spec/somewhere_else", got redirect to "http://test.host/redirect_spec/somewhere"')
+ end
+
+ it "redirected to incorrect internal URL (based on the action)" do
+ get 'action_with_redirect_to_somewhere'
+ lambda {
+ response.should redirect_to("http://test.host/redirect_spec/somewhere_else")
+ }.should fail_with('expected redirect to "http://test.host/redirect_spec/somewhere_else", got redirect to "http://test.host/redirect_spec/somewhere"')
+ end
+
+ it "redirected to wrong external URL" do
+ get 'action_with_redirect_to_rspec_site'
+ lambda {
+ response.should redirect_to("http://test.unit.rubyforge.org")
+ }.should fail_with('expected redirect to "http://test.unit.rubyforge.org", got redirect to "http://rspec.rubyforge.org"')
+ end
+
+ it "redirected to incorrect internal URL (based on the directory path)" do
+ get 'action_with_redirect_to_somewhere'
+ lambda {
+ response.should redirect_to("http://test.host/non_existent_controller/somewhere")
+ }.should fail_with('expected redirect to "http://test.host/non_existent_controller/somewhere", got redirect to "http://test.host/redirect_spec/somewhere"')
+ end
+
+ it "expected redirect :back, but redirected to a new URL" do
+ get 'action_with_no_redirect'
+ lambda {
+ response.should redirect_to(:back)
+ }.should fail_with('expected redirect to :back, got no redirect')
+ end
+
+ it "no redirect at all" do
+ get 'action_with_no_redirect'
+ lambda {
+ response.should redirect_to(:action => 'nowhere')
+ }.should fail_with("expected redirect to {:action=>\"nowhere\"}, got no redirect")
+ end
+
+ it "redirected to an internal URL which is unroutable and matched via a hash" do
+ get "action_with_redirect_to_unroutable_url_inside_app"
+ route = {:controller => "nonexistant", :action => "none"}
+ lambda {
+ response.should redirect_to(route)
+ }.should raise_error(ActionController::RoutingError, /(no route found to match|No route matches) \"\/nonexistant\/none\" with \{\}/)
+ end
+
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/matchers/render_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/matchers/render_spec.rb
new file mode 100644
index 0000000..93cca86
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/matchers/render_spec.rb
@@ -0,0 +1,169 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+['isolation','integration'].each do |mode|
+ describe "response.should render_template (in #{mode} mode)",
+ :type => :controller do
+ controller_name :render_spec
+ if mode == 'integration'
+ integrate_views
+ end
+
+ it "should match a simple path" do
+ post 'some_action'
+ response.should render_template('some_action')
+ end
+
+ it "should match a less simple path" do
+ post 'some_action'
+ response.should render_template('render_spec/some_action')
+ end
+
+ it "should match a less simple path to another controller" do
+ post 'action_which_renders_template_from_other_controller'
+ response.should render_template('controller_spec/action_with_template')
+ end
+
+ it "should match a symbol" do
+ post 'some_action'
+ response.should render_template(:some_action)
+ end
+
+ it "should match an rjs template" do
+ xhr :post, 'some_action'
+ if Rails::VERSION::STRING < "2.0.0"
+ response.should render_template('render_spec/some_action.rjs')
+ else
+ response.should render_template('render_spec/some_action')
+ end
+ end
+
+ it "should match a partial template (simple path)" do
+ get 'action_with_partial'
+ response.should render_template("_a_partial")
+ end
+
+ it "should match a partial template (complex path)" do
+ get 'action_with_partial'
+ response.should render_template("render_spec/_a_partial")
+ end
+
+ it "should fail when the wrong template is rendered" do
+ post 'some_action'
+ lambda do
+ response.should render_template('non_existent_template')
+ end.should fail_with("expected \"non_existent_template\", got \"render_spec/some_action\"")
+ end
+
+ it "should fail without full path when template is associated with a different controller" do
+ post 'action_which_renders_template_from_other_controller'
+ lambda do
+ response.should render_template('action_with_template')
+ end.should fail_with(%Q|expected "action_with_template", got "controller_spec/action_with_template"|)
+ end
+
+ it "should fail with incorrect full path when template is associated with a different controller" do
+ post 'action_which_renders_template_from_other_controller'
+ lambda do
+ response.should render_template('render_spec/action_with_template')
+ end.should fail_with(%Q|expected "render_spec/action_with_template", got "controller_spec/action_with_template"|)
+ end
+
+ it "should fail on the wrong extension (given rhtml)" do
+ get 'some_action'
+ lambda {
+ response.should render_template('render_spec/some_action.rjs')
+ }.should fail_with("expected \"render_spec/some_action.rjs\", got \"render_spec/some_action\"")
+ end
+
+ it "should fail when TEXT is rendered" do
+ post 'text_action'
+ lambda do
+ response.should render_template('some_action')
+ end.should fail_with("expected \"some_action\", got nil")
+ end
+ end
+
+ describe "response.should_not render_template (in #{mode} mode)",
+ :type => :controller do
+ controller_name :render_spec
+ if mode == 'integration'
+ integrate_views
+ end
+
+ it "should pass when the action renders nothing" do
+ post 'action_that_renders_nothing'
+ response.should_not render_template('action_that_renders_nothing')
+ end
+
+ it "should pass when the action renders nothing (symbol)" do
+ post 'action_that_renders_nothing'
+ response.should_not render_template(:action_that_renders_nothing)
+ end
+
+ it "should pass when the action does not render the template" do
+ post 'some_action'
+ response.should_not render_template('some_other_template')
+ end
+
+ it "should pass when the action does not render the template (symbol)" do
+ post 'some_action'
+ response.should_not render_template(:some_other_template)
+ end
+
+ it "should pass when the action does not render the template (named with controller)" do
+ post 'some_action'
+ response.should_not render_template('render_spec/some_other_template')
+ end
+
+ it "should pass when the action renders the template with a different controller" do
+ post 'action_which_renders_template_from_other_controller'
+ response.should_not render_template('action_with_template')
+ end
+
+ it "should pass when the action renders the template (named with controller) with a different controller" do
+ post 'action_which_renders_template_from_other_controller'
+ response.should_not render_template('render_spec/action_with_template')
+ end
+
+ it "should pass when TEXT is rendered" do
+ post 'text_action'
+ response.should_not render_template('some_action')
+ end
+
+ it "should fail when the action renders the template" do
+ post 'some_action'
+ lambda do
+ response.should_not render_template('some_action')
+ end.should fail_with("expected not to render \"some_action\", but did")
+ end
+
+ it "should fail when the action renders the template (symbol)" do
+ post 'some_action'
+ lambda do
+ response.should_not render_template(:some_action)
+ end.should fail_with("expected not to render \"some_action\", but did")
+ end
+
+ it "should fail when the action renders the template (named with controller)" do
+ post 'some_action'
+ lambda do
+ response.should_not render_template('render_spec/some_action')
+ end.should fail_with("expected not to render \"render_spec/some_action\", but did")
+ end
+
+ it "should fail when the action renders the partial" do
+ post 'action_with_partial'
+ lambda do
+ response.should_not render_template('_a_partial')
+ end.should fail_with("expected not to render \"_a_partial\", but did")
+ end
+
+ it "should fail when the action renders the partial (named with controller)" do
+ post 'action_with_partial'
+ lambda do
+ response.should_not render_template('render_spec/_a_partial')
+ end.should fail_with("expected not to render \"render_spec/_a_partial\", but did")
+ end
+
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/mocks/mock_model_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/mocks/mock_model_spec.rb
new file mode 100644
index 0000000..76793f0
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/mocks/mock_model_spec.rb
@@ -0,0 +1,65 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+class MockableModel < ActiveRecord::Base
+ has_one :associated_model
+end
+
+class SubMockableModel < MockableModel
+end
+
+class AssociatedModel < ActiveRecord::Base
+ belongs_to :mockable_model
+end
+
+describe "mock_model", :type => :view do
+ before(:each) do
+ @model = mock_model(SubMockableModel)
+ end
+ it "should say it is_a? if it is" do
+ @model.is_a?(SubMockableModel).should be(true)
+ end
+ it "should say it is_a? if it's ancestor is" do
+ @model.is_a?(MockableModel).should be(true)
+ end
+ it "should say it is kind_of? if it is" do
+ @model.kind_of?(SubMockableModel).should be(true)
+ end
+ it "should say it is kind_of? if it's ancestor is" do
+ @model.kind_of?(MockableModel).should be(true)
+ end
+ it "should say it is instance_of? if it is" do
+ @model.instance_of?(SubMockableModel).should be(true)
+ end
+ it "should not say it instance_of? if it isn't, even if it's ancestor is" do
+ @model.instance_of?(MockableModel).should be(false)
+ end
+end
+
+describe "mock_model with null_object", :type => :view do
+ before(:each) do
+ @model = mock_model(MockableModel, :null_object => true, :mocked_method => "mocked")
+ end
+
+ it "should be able to mock methods" do
+ @model.mocked_method.should == "mocked"
+ end
+ it "should return itself to unmocked methods" do
+ @model.unmocked_method.should equal(@model)
+ end
+end
+
+describe "mock_model as association", :type => :view do
+ before(:each) do
+ @real = AssociatedModel.create!
+ @mock_model = mock_model(MockableModel)
+ @real.mockable_model = @mock_model
+ end
+
+ it "should pass associated_model == mock" do
+ @mock_model.should == @real.mockable_model
+ end
+
+ it "should pass mock == associated_model" do
+ @real.mockable_model.should == @mock_model
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/sample_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/sample_spec.rb
new file mode 100644
index 0000000..7cd1d4e
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/sample_spec.rb
@@ -0,0 +1,7 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe "A sample spec" do
+ it "should pass" do
+ true.should === true
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/spec_server_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/spec_server_spec.rb
new file mode 100644
index 0000000..957bd10
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/spec_server_spec.rb
@@ -0,0 +1,89 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe "script/spec_server file", :shared => true do
+ attr_accessor :tmbundle_install_directory
+
+ after do
+ system "kill -9 #{@pid}"
+ end
+
+ it "runs a spec" do
+ dir = File.dirname(__FILE__)
+ output = ""
+ Timeout.timeout(10) do
+ loop do
+ output = `#{RAILS_ROOT}/script/spec #{dir}/sample_spec.rb --drb 2>&1`
+ break unless output.include?("No server is running")
+ end
+ end
+
+ unless $?.exitstatus == 0
+ flunk "command 'script/spec spec/sample_spec' failed\n#{output}"
+ end
+ end
+
+ def start_spec_server
+ create_spec_server_pid_file
+ start_spec_server_process
+ end
+
+ def create_spec_server_pid_file
+ current_dir = File.dirname(__FILE__)
+ pid_dir = "#{Dir.tmpdir}/#{Time.now.to_i}"
+ @spec_server_pid_file = "#{pid_dir}/spec_server.pid"
+ FileUtils.mkdir_p pid_dir
+ system "touch #{@spec_server_pid_file}"
+ @rspec_path = File.expand_path("#{current_dir}/../../../rspec/lib")
+ end
+
+ def start_spec_server_process
+ dir = File.dirname(__FILE__)
+ spec_server_cmd = %Q|export HOME=#{Dir.tmpdir}; |
+ spec_server_cmd << %Q|ruby -e 'system("echo " + Process.pid.to_s + " > #{@spec_server_pid_file}"); |
+ spec_server_cmd << %Q|$LOAD_PATH.unshift("#{@rspec_path}"); require "spec"; |
+ spec_server_cmd << %Q|load "#{RAILS_ROOT}/script/spec_server"' &|
+ system spec_server_cmd
+
+ file_content = ""
+ Timeout.timeout(5) do
+ loop do
+ file_content = File.read(@spec_server_pid_file)
+ break unless file_content.blank?
+ end
+ end
+ @pid = Integer(File.read(@spec_server_pid_file))
+ end
+end
+
+describe "script/spec_server file without TextMate bundle" do
+ it_should_behave_like "script/spec_server file"
+ before do
+ start_spec_server
+ end
+end
+
+describe "script/spec_server file with TextMate bundle" do
+ it_should_behave_like "script/spec_server file"
+ before do
+ dir = File.dirname(__FILE__)
+ @tmbundle_install_directory = File.expand_path("#{Dir.tmpdir}/Library/Application Support/TextMate/Bundles")
+ @bundle_name = "RSpec.tmbundle"
+ FileUtils.mkdir_p(tmbundle_install_directory)
+ bundle_dir = File.expand_path("#{dir}/../../../../../../#{@bundle_name}")
+ File.directory?(bundle_dir).should be_true
+ unless system(%Q|ln -s #{bundle_dir} "#{tmbundle_install_directory}"|)
+ raise "Creating link to Textmate Bundle"
+ end
+ start_spec_server
+ end
+
+ after do
+ bundle_file_to_remove = "#{tmbundle_install_directory}/#{@bundle_name}"
+ if bundle_file_to_remove == "/"
+ raise "bundle file path resolved to '/' - could not call rm"
+ end
+ unless system(%Q|rm "#{bundle_file_to_remove}"|)
+ raise "Removing Textmate bundle link failed"
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/rails/spec_spec.rb b/vendor/plugins/rspec_on_rails/spec/rails/spec_spec.rb
new file mode 100644
index 0000000..ea258c7
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails/spec_spec.rb
@@ -0,0 +1,11 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe "script/spec file" do
+ it "should run a spec" do
+ dir = File.dirname(__FILE__)
+ output = `#{RAILS_ROOT}/script/spec #{dir}/sample_spec.rb`
+ unless $?.exitstatus == 0
+ flunk "command 'script/spec spec/sample_spec' failed\n#{output}"
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec/rails_suite.rb b/vendor/plugins/rspec_on_rails/spec/rails_suite.rb
new file mode 100644
index 0000000..15effae
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/rails_suite.rb
@@ -0,0 +1,7 @@
+dir = File.dirname(__FILE__)
+Dir["#{dir}/**/*_example.rb"].each do |file|
+ require file
+end
+Dir["#{dir}/**/*_spec.rb"].each do |file|
+ require file
+end
diff --git a/vendor/plugins/rspec_on_rails/spec/spec_helper.rb b/vendor/plugins/rspec_on_rails/spec/spec_helper.rb
new file mode 100644
index 0000000..2d2c727
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec/spec_helper.rb
@@ -0,0 +1,46 @@
+dir = File.dirname(__FILE__)
+$LOAD_PATH.unshift(File.expand_path("#{dir}/../rspec/lib"))
+$LOAD_PATH.unshift(File.expand_path("#{dir}/../spec_resources/controllers"))
+$LOAD_PATH.unshift(File.expand_path("#{dir}/../spec_resources/helpers"))
+require File.expand_path("#{dir}/../../../../spec/spec_helper")
+require File.expand_path("#{dir}/../spec_resources/controllers/render_spec_controller")
+require File.expand_path("#{dir}/../spec_resources/controllers/rjs_spec_controller")
+require File.expand_path("#{dir}/../spec_resources/controllers/redirect_spec_controller")
+require File.expand_path("#{dir}/../spec_resources/controllers/action_view_base_spec_controller")
+require File.expand_path("#{dir}/../spec_resources/helpers/explicit_helper")
+require File.expand_path("#{dir}/../spec_resources/helpers/more_explicit_helper")
+require File.expand_path("#{dir}/../spec_resources/helpers/view_spec_helper")
+require File.expand_path("#{dir}/../spec_resources/helpers/plugin_application_helper")
+
+ActionController::Routing.controller_paths << "#{dir}/../spec_resources/controllers"
+
+module Spec
+ module Rails
+ module Example
+ class ViewExampleGroupController
+ set_view_path File.join(File.dirname(__FILE__), "..", "spec_resources", "views")
+ end
+ end
+ end
+end
+
+def fail()
+ raise_error(Spec::Expectations::ExpectationNotMetError)
+end
+
+def fail_with(message)
+ raise_error(Spec::Expectations::ExpectationNotMetError,message)
+end
+
+class Proc
+ def should_pass
+ lambda { self.call }.should_not raise_error
+ end
+end
+
+ActionController::Routing::Routes.draw do |map|
+ map.resources :rspec_on_rails_specs
+ map.connect 'custom_route', :controller => 'custom_route_spec', :action => 'custom_route'
+ map.connect ":controller/:action/:id"
+end
+
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/controllers/action_view_base_spec_controller.rb b/vendor/plugins/rspec_on_rails/spec_resources/controllers/action_view_base_spec_controller.rb
new file mode 100644
index 0000000..9240221
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/controllers/action_view_base_spec_controller.rb
@@ -0,0 +1,2 @@
+class ActionViewBaseSpecController < ActionController::Base
+end
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/controllers/controller_spec_controller.rb b/vendor/plugins/rspec_on_rails/spec_resources/controllers/controller_spec_controller.rb
new file mode 100644
index 0000000..d606773
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/controllers/controller_spec_controller.rb
@@ -0,0 +1,56 @@
+class ControllerSpecController < ActionController::Base
+ if ['edge','2.0.0'].include?(ENV['RSPEC_RAILS_VERSION'])
+ set_view_path [File.join(File.dirname(__FILE__), "..", "views")]
+ else
+ set_view_path File.join(File.dirname(__FILE__), "..", "views")
+ end
+
+ def some_action
+ render :template => "template/that/does/not/actually/exist"
+ end
+
+ def action_with_template
+ session[:session_key] = "session value"
+ flash[:flash_key] = "flash value"
+ render :template => "controller_spec/action_with_template"
+ end
+
+ def action_with_partial
+ render :partial => "controller_spec/partial"
+ end
+
+ def action_with_partial_with_object
+ render :partial => "controller_spec/partial", :object => params[:thing]
+ end
+
+ def action_with_partial_with_locals
+ render :partial => "controller_spec/partial", :locals => {:thing => params[:thing]}
+ end
+
+ def action_with_errors_in_template
+ render :template => "controller_spec/action_with_errors_in_template"
+ end
+
+ def action_setting_the_assigns_hash
+ assigns['direct_assigns_key'] = :direct_assigns_key_value
+ @indirect_assigns_key = :indirect_assigns_key_value
+ end
+
+ def action_setting_flash_after_session_reset
+ reset_session
+ flash[:after_reset] = "available"
+ end
+
+ def action_setting_flash_before_session_reset
+ flash[:before_reset] = 'available'
+ reset_session
+ end
+
+ def action_with_render_update
+ render :update do |page|
+ page.replace :bottom, 'replace_me',
+ :partial => 'non_existent_partial'
+ end
+ end
+end
+
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/controllers/redirect_spec_controller.rb b/vendor/plugins/rspec_on_rails/spec_resources/controllers/redirect_spec_controller.rb
new file mode 100644
index 0000000..aa3b24a
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/controllers/redirect_spec_controller.rb
@@ -0,0 +1,59 @@
+class RedirectSpecController < ApplicationController
+
+ def action_with_no_redirect
+ render :text => "this is just here to keep this from causing a MissingTemplate error"
+ end
+
+ def action_with_redirect_to_somewhere
+ redirect_to :action => 'somewhere'
+ end
+
+ def action_with_redirect_to_other_somewhere
+ redirect_to :controller => 'render_spec', :action => 'text_action'
+ end
+
+ def action_with_redirect_to_somewhere_and_return
+ redirect_to :action => 'somewhere' and return
+ render :text => "this is after the return"
+ end
+
+ def somewhere
+ render :text => "this is just here to keep this from causing a MissingTemplate error"
+ end
+
+ def action_with_redirect_to_rspec_site
+ redirect_to "http://rspec.rubyforge.org"
+ end
+
+ def action_with_redirect_back
+ redirect_to :back
+ end
+
+ def action_with_redirect_in_respond_to
+ respond_to do |wants|
+ wants.html { redirect_to :action => 'somewhere' }
+ end
+ end
+
+ def action_with_redirect_which_creates_query_string
+ redirect_to :action => "somewhere", :id => 1111, :param1 => "value1", :param2 => "value2"
+ end
+
+ # note: sometimes this is the URL which rails will generate from the hash in
+ # action_with_redirect_which_creates_query_string
+ def action_with_redirect_with_query_string_order1
+ redirect_to "http://test.host/redirect_spec/somewhere/1111?param1=value1¶m2=value2"
+ end
+
+ # note: sometimes this is the URL which rails will generate from the hash in
+ # action_with_redirect_which_creates_query_string
+ def action_with_redirect_with_query_string_order2
+ redirect_to "http://test.host/redirect_spec/somewhere/1111?param2=value2¶m1=value1"
+ end
+
+ def action_with_redirect_to_unroutable_url_inside_app
+ redirect_to :controller => "nonexistant", :action => "none"
+ end
+
+end
+
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/controllers/render_spec_controller.rb b/vendor/plugins/rspec_on_rails/spec_resources/controllers/render_spec_controller.rb
new file mode 100644
index 0000000..b546abe
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/controllers/render_spec_controller.rb
@@ -0,0 +1,26 @@
+class RenderSpecController < ApplicationController
+ set_view_path File.join(File.dirname(__FILE__), "..", "views")
+
+ def some_action
+ respond_to do |format|
+ format.html
+ format.js
+ end
+ end
+
+ def action_which_renders_template_from_other_controller
+ render :template => 'controller_spec/action_with_template'
+ end
+
+ def text_action
+ render :text => "this is the text for this action"
+ end
+
+ def action_with_partial
+ render :partial => "a_partial"
+ end
+
+ def action_that_renders_nothing
+ render :nothing => true
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/controllers/rjs_spec_controller.rb b/vendor/plugins/rspec_on_rails/spec_resources/controllers/rjs_spec_controller.rb
new file mode 100644
index 0000000..e7131bc
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/controllers/rjs_spec_controller.rb
@@ -0,0 +1,58 @@
+class RjsSpecController < ApplicationController
+ set_view_path File.join(File.dirname(__FILE__), "..", "views")
+
+ def replace_html
+ end
+
+ def insert_html
+ end
+
+ def replace
+ end
+
+ def hide_div
+ end
+
+ def hide_page_element
+ end
+
+ def replace_html_with_partial
+ end
+
+ def render_replace_html
+ render :update do |page|
+ page.replace_html 'mydiv', 'replacement text'
+ page.replace_html 'myotherdiv', 'other replacement text'
+ end
+ end
+
+ def render_replace_html_with_partial
+ render :update do |page|
+ page.replace_html 'mydiv', :partial => 'rjs_spec/replacement_partial'
+ end
+ end
+
+ def render_insert_html
+ render :update do |page|
+ page.insert_html 'mydiv', 'replacement text'
+ end
+ end
+
+ def render_replace
+ render :update do |page|
+ page.replace 'mydiv', 'replacement text'
+ end
+ end
+
+ def render_hide_div
+ render :update do |page|
+ page.hide 'mydiv'
+ end
+ end
+
+ def render_hide_page_element
+ render :update do |page|
+ page['mydiv'].hide
+ end
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/helpers/explicit_helper.rb b/vendor/plugins/rspec_on_rails/spec_resources/helpers/explicit_helper.rb
new file mode 100644
index 0000000..f39f0cc
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/helpers/explicit_helper.rb
@@ -0,0 +1,10 @@
+module ExplicitHelper
+ def method_in_explicit_helper
+ "<div>This is text from a method in the ExplicitHelper</div>"
+ end
+
+ # this is an example of a method spec'able with eval_erb in helper specs
+ def prepend(arg, &block)
+ concat(arg, block.binding) + block.call
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/helpers/more_explicit_helper.rb b/vendor/plugins/rspec_on_rails/spec_resources/helpers/more_explicit_helper.rb
new file mode 100644
index 0000000..7468741
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/helpers/more_explicit_helper.rb
@@ -0,0 +1,5 @@
+module MoreExplicitHelper
+ def method_in_more_explicit_helper
+ "<div>This is text from a method in the MoreExplicitHelper</div>"
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/helpers/plugin_application_helper.rb b/vendor/plugins/rspec_on_rails/spec_resources/helpers/plugin_application_helper.rb
new file mode 100644
index 0000000..2107d22
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/helpers/plugin_application_helper.rb
@@ -0,0 +1,6 @@
+# Methods added to this helper will be available to all templates in the application.
+module ApplicationHelper
+ def method_in_plugin_application_helper
+ "<div>This is text from a method in the ApplicationHelper</div>"
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/helpers/view_spec_helper.rb b/vendor/plugins/rspec_on_rails/spec_resources/helpers/view_spec_helper.rb
new file mode 100644
index 0000000..b05fc53
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/helpers/view_spec_helper.rb
@@ -0,0 +1,13 @@
+module ViewSpecHelper
+ def method_in_helper
+ "<div>This is text from a method in the ViewSpecHelper</div>"
+ end
+
+ def method_in_template_with_partial
+ "<div>method_in_template_with_partial in ViewSpecHelper</div>"
+ end
+
+ def method_in_partial
+ "<div>method_in_partial in ViewSpecHelper</div>"
+ end
+end
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/_partial.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/_partial.rhtml
new file mode 100644
index 0000000..e69de29
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_setting_flash_after_session_reset.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_setting_flash_after_session_reset.rhtml
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_setting_flash_after_session_reset.rhtml
@@ -0,0 +1 @@
+
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_setting_flash_before_session_reset.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_setting_flash_before_session_reset.rhtml
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_setting_flash_before_session_reset.rhtml
@@ -0,0 +1 @@
+
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_setting_the_assigns_hash.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_setting_the_assigns_hash.rhtml
new file mode 100644
index 0000000..e69de29
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_with_errors_in_template.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_with_errors_in_template.rhtml
new file mode 100644
index 0000000..0f957b2
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_with_errors_in_template.rhtml
@@ -0,0 +1 @@
+<% raise %>
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_with_template.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_with_template.rhtml
new file mode 100644
index 0000000..6e1f058
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/controller_spec/action_with_template.rhtml
@@ -0,0 +1 @@
+<div>This is action_with_template.rhtml</div>
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/_a_partial.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/_a_partial.rhtml
new file mode 100644
index 0000000..e69de29
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/some_action.js.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/some_action.js.rjs
new file mode 100644
index 0000000..4472f4b
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/some_action.js.rjs
@@ -0,0 +1 @@
+# This is used for rails > 1.2.3
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/some_action.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/some_action.rhtml
new file mode 100644
index 0000000..e69de29
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/some_action.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/some_action.rjs
new file mode 100644
index 0000000..c67be9b
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/render_spec/some_action.rjs
@@ -0,0 +1 @@
+# This is used for rails <= 1.2.3
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/_replacement_partial.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/_replacement_partial.rhtml
new file mode 100644
index 0000000..d282065
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/_replacement_partial.rhtml
@@ -0,0 +1 @@
+This is the text in the replacement partial.
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/hide_div.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/hide_div.rjs
new file mode 100644
index 0000000..1fe2139
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/hide_div.rjs
@@ -0,0 +1 @@
+page.hide 'mydiv'
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/hide_page_element.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/hide_page_element.rjs
new file mode 100644
index 0000000..de1ebc9
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/hide_page_element.rjs
@@ -0,0 +1 @@
+page['mydiv'].hide
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/insert_html.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/insert_html.rjs
new file mode 100644
index 0000000..f8a59e0
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/insert_html.rjs
@@ -0,0 +1 @@
+page.insert_html 'mydiv', 'replacement text'
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/replace.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/replace.rjs
new file mode 100644
index 0000000..aca59a9
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/replace.rjs
@@ -0,0 +1 @@
+page.replace 'mydiv', 'replacement text'
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/replace_html.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/replace_html.rjs
new file mode 100644
index 0000000..717c598
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/replace_html.rjs
@@ -0,0 +1 @@
+page.replace_html 'mydiv', 'replacement text'
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/replace_html_with_partial.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/replace_html_with_partial.rjs
new file mode 100644
index 0000000..0531804
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/replace_html_with_partial.rjs
@@ -0,0 +1 @@
+page.replace_html 'mydiv', :partial => 'rjs_spec/replacement_partial'
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/visual_effect.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/visual_effect.rjs
new file mode 100644
index 0000000..1c37b32
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/visual_effect.rjs
@@ -0,0 +1 @@
+page.visual_effect :fade, 'mydiv'
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/visual_toggle_effect.rjs b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/visual_toggle_effect.rjs
new file mode 100644
index 0000000..97cf6bb
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/rjs_spec/visual_toggle_effect.rjs
@@ -0,0 +1 @@
+page.visual_effect :toggle_blind, 'mydiv'
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/tag_spec/no_tags.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/tag_spec/no_tags.rhtml
new file mode 100644
index 0000000..877b908
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/tag_spec/no_tags.rhtml
@@ -0,0 +1 @@
+<!-THIS FILE HAS NO TAGS->
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/tag_spec/single_div_with_no_attributes.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/tag_spec/single_div_with_no_attributes.rhtml
new file mode 100644
index 0000000..281c686
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/tag_spec/single_div_with_no_attributes.rhtml
@@ -0,0 +1 @@
+<div></div>
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/tag_spec/single_div_with_one_attribute.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/tag_spec/single_div_with_one_attribute.rhtml
new file mode 100644
index 0000000..c664e76
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/tag_spec/single_div_with_one_attribute.rhtml
@@ -0,0 +1 @@
+<div key="value"></div>
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial.rhtml
new file mode 100644
index 0000000..39505da
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial.rhtml
@@ -0,0 +1,2 @@
+<%= method_in_plugin_application_helper %>
+<%= method_in_partial %>
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial_used_twice.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial_used_twice.rhtml
new file mode 100644
index 0000000..e69de29
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial_with_local_variable.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial_with_local_variable.rhtml
new file mode 100644
index 0000000..4727448
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial_with_local_variable.rhtml
@@ -0,0 +1 @@
+<div><%= x %></div>
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial_with_sub_partial.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial_with_sub_partial.rhtml
new file mode 100644
index 0000000..90207a3
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_partial_with_sub_partial.rhtml
@@ -0,0 +1 @@
+<%= render :partial => 'partial', :object => partial %>
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_spacer.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_spacer.rhtml
new file mode 100644
index 0000000..c952f6e
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/_spacer.rhtml
@@ -0,0 +1 @@
+<hr id="spacer" />
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/accessor.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/accessor.rhtml
new file mode 100644
index 0000000..ef636f6
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/accessor.rhtml
@@ -0,0 +1,3 @@
+<div id="session"><%= session[:key] %></div>
+<div id="params"><%= params[:key] %></div>
+<div id="flash"><%= flash[:key] %></div>
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/entry_form.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/entry_form.rhtml
new file mode 100644
index 0000000..7b11d97
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/entry_form.rhtml
@@ -0,0 +1,2 @@
+<% form_tag do %>
+<% end %>
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/explicit_helper.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/explicit_helper.rhtml
new file mode 100644
index 0000000..49aa081
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/explicit_helper.rhtml
@@ -0,0 +1,2 @@
+<%= method_in_plugin_application_helper %>
+<%= method_in_explicit_helper %>
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/foo/show.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/foo/show.rhtml
new file mode 100644
index 0000000..2cc5fd9
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/foo/show.rhtml
@@ -0,0 +1 @@
+<%= method_in_plugin_application_helper %>
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/implicit_helper.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/implicit_helper.rhtml
new file mode 100644
index 0000000..816c667
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/implicit_helper.rhtml
@@ -0,0 +1,2 @@
+<%= method_in_plugin_application_helper %>
+<%= method_in_helper %>
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/multiple_helpers.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/multiple_helpers.rhtml
new file mode 100644
index 0000000..ae5a72b
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/multiple_helpers.rhtml
@@ -0,0 +1,3 @@
+<%= method_in_plugin_application_helper %>
+<%= method_in_explicit_helper %>
+<%= method_in_more_explicit_helper %>
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/template_with_partial.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/template_with_partial.rhtml
new file mode 100644
index 0000000..0e13ba3
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/template_with_partial.rhtml
@@ -0,0 +1,5 @@
+<%= method_in_template_with_partial %>
+<%= render :partial => 'partial' %>
+
+<%= render :partial => 'partial_used_twice' %>
+<%= render :partial => 'partial_used_twice' %>
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/template_with_partial_using_collection.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/template_with_partial_using_collection.rhtml
new file mode 100644
index 0000000..79d8215
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/template_with_partial_using_collection.rhtml
@@ -0,0 +1,3 @@
+<%= render :partial => 'partial',
+ :collection => ['Alice', 'Bob'],
+ :spacer_template => 'spacer' %>
diff --git a/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/template_with_partial_with_array.rhtml b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/template_with_partial_with_array.rhtml
new file mode 100644
index 0000000..7d53476
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/spec_resources/views/view_spec/template_with_partial_with_array.rhtml
@@ -0,0 +1 @@
+<%= render :partial => @array %>
diff --git a/vendor/plugins/rspec_on_rails/stories/all.rb b/vendor/plugins/rspec_on_rails/stories/all.rb
new file mode 100644
index 0000000..7e55f8a
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/stories/all.rb
@@ -0,0 +1,10 @@
+require File.join(File.dirname(__FILE__), *%w[helper])
+require File.join(File.dirname(__FILE__), *%w[steps people])
+
+# Run transactions_should_rollback in Ruby
+require File.join(File.dirname(__FILE__), *%w[transactions_should_rollback])
+
+# Run transactions_should_rollback in Plain Text
+with_steps_for :people do
+ run File.join(File.dirname(__FILE__), *%w[transactions_should_rollback]), :type => RailsStory
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/stories/helper.rb b/vendor/plugins/rspec_on_rails/stories/helper.rb
new file mode 100644
index 0000000..50c6ee6
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/stories/helper.rb
@@ -0,0 +1,5 @@
+dir = File.dirname(__FILE__)
+$LOAD_PATH.unshift File.expand_path("#{dir}/../lib")
+require File.expand_path("#{dir}/../../../../spec/spec_helper")
+
+require 'spec/rails/story_adapter'
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/stories/steps/people.rb b/vendor/plugins/rspec_on_rails/stories/steps/people.rb
new file mode 100644
index 0000000..a3bf25e
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/stories/steps/people.rb
@@ -0,0 +1,8 @@
+steps_for :people do
+ When "I add a Person" do
+ Person.create!(:name => "Foo")
+ end
+ Then "there should be one person" do
+ Person.count.should == 1
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/stories/transactions_should_rollback b/vendor/plugins/rspec_on_rails/stories/transactions_should_rollback
new file mode 100644
index 0000000..9367676
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/stories/transactions_should_rollback
@@ -0,0 +1,15 @@
+Story: transactions should rollback in plain text
+ As an RSpec/Rails Story author
+ I want transactions to roll back between scenarios in plain text
+ So that I can have confidence in the state of the database
+
+ Scenario: add one Person
+ When I add a Person
+
+ Scenario: add another person
+ GivenScenario: add one Person
+ Then there should be one person
+
+ Scenario: add yet another person
+ GivenScenario: add one Person
+ Then there should be one person
diff --git a/vendor/plugins/rspec_on_rails/stories/transactions_should_rollback.rb b/vendor/plugins/rspec_on_rails/stories/transactions_should_rollback.rb
new file mode 100644
index 0000000..3e2bdda
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/stories/transactions_should_rollback.rb
@@ -0,0 +1,25 @@
+require File.join(File.dirname(__FILE__), *%w[helper])
+
+Story "transactions should rollback", %{
+ As an RSpec/Rails Story author
+ I want transactions to roll back between scenarios
+ So that I can have confidence in the state of the database
+}, :type => RailsStory do
+ Scenario "add one Person" do
+ When "I add a Person" do
+ Person.create!(:name => "Foo")
+ end
+ end
+
+ Scenario "add another person" do
+ GivenScenario "add one Person"
+ Then "there should be one person" do
+ Person.count.should == 1
+ end
+ end
+
+ Scenario "add yet another person" do
+ GivenScenario "add one Person"
+ Then "there should be one person"
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec_on_rails/tasks/rspec.rake b/vendor/plugins/rspec_on_rails/tasks/rspec.rake
new file mode 100644
index 0000000..7228547
--- /dev/null
+++ b/vendor/plugins/rspec_on_rails/tasks/rspec.rake
@@ -0,0 +1,137 @@
+# In rails 1.2, plugins aren't available in the path until they're loaded.
+# Check to see if the rspec plugin is installed first and require
+# it if it is. If not, use the gem version.
+rspec_base = File.expand_path(File.dirname(__FILE__) + '/../../rspec/lib')
+$LOAD_PATH.unshift(rspec_base) if File.exist?(rspec_base)
+require 'spec/rake/spectask'
+require 'spec/translator'
+
+spec_prereq = File.exist?(File.join(RAILS_ROOT, 'config', 'database.yml')) ? "db:test:prepare" : :noop
+task :noop do
+end
+
+task :default => :spec
+task :stats => "spec:statsetup"
+
+desc "Run all specs in spec directory (excluding plugin specs)"
+Spec::Rake::SpecTask.new(:spec => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+end
+
+namespace :spec do
+ desc "Run all specs in spec directory with RCov (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:rcov) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+ t.rcov = true
+ t.rcov_opts = lambda do
+ IO.readlines("#{RAILS_ROOT}/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten
+ end
+ end
+
+ desc "Print Specdoc for all specs (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+ end
+
+ desc "Print Specdoc for all plugin specs"
+ Spec::Rake::SpecTask.new(:plugin_doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*')
+ end
+
+ [:models, :controllers, :views, :helpers, :lib].each do |sub|
+ desc "Run the specs under spec/#{sub}"
+ Spec::Rake::SpecTask.new(sub => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList["spec/#{sub}/**/*_spec.rb"]
+ end
+ end
+
+ desc "Run the specs under vendor/plugins (except RSpec's own)"
+ Spec::Rake::SpecTask.new(:plugins => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*').exclude("vendor/plugins/rspec_on_rails/*")
+ end
+
+ namespace :plugins do
+ desc "Runs the examples for rspec_on_rails"
+ Spec::Rake::SpecTask.new(:rspec_on_rails) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/rspec_on_rails/spec/**/*_spec.rb']
+ end
+ end
+
+ desc "Translate/upgrade specs using the built-in translator"
+ task :translate do
+ translator = ::Spec::Translator.new
+ dir = RAILS_ROOT + '/spec'
+ translator.translate(dir, dir)
+ end
+
+ # Setup specs for stats
+ task :statsetup do
+ require 'code_statistics'
+ ::STATS_DIRECTORIES << %w(Model\ specs spec/models) if File.exist?('spec/models')
+ ::STATS_DIRECTORIES << %w(View\ specs spec/views) if File.exist?('spec/views')
+ ::STATS_DIRECTORIES << %w(Controller\ specs spec/controllers) if File.exist?('spec/controllers')
+ ::STATS_DIRECTORIES << %w(Helper\ specs spec/helpers) if File.exist?('spec/helpers')
+ ::STATS_DIRECTORIES << %w(Library\ specs spec/lib) if File.exist?('spec/lib')
+ ::CodeStatistics::TEST_TYPES << "Model specs" if File.exist?('spec/models')
+ ::CodeStatistics::TEST_TYPES << "View specs" if File.exist?('spec/views')
+ ::CodeStatistics::TEST_TYPES << "Controller specs" if File.exist?('spec/controllers')
+ ::CodeStatistics::TEST_TYPES << "Helper specs" if File.exist?('spec/helpers')
+ ::CodeStatistics::TEST_TYPES << "Library specs" if File.exist?('spec/lib')
+ ::STATS_DIRECTORIES.delete_if {|a| a[0] =~ /test/}
+ end
+
+ namespace :db do
+ namespace :fixtures do
+ desc "Load fixtures (from spec/fixtures) into the current environment's database. Load specific fixtures using FIXTURES=x,y"
+ task :load => :environment do
+ require 'active_record/fixtures'
+ ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir.glob(File.join(RAILS_ROOT, 'spec', 'fixtures', '*.{yml,csv}'))).each do |fixture_file|
+ Fixtures.create_fixtures('spec/fixtures', File.basename(fixture_file, '.*'))
+ end
+ end
+ end
+ end
+
+ namespace :server do
+ daemonized_server_pid = File.expand_path("spec_server.pid", RAILS_ROOT + "/tmp")
+
+ desc "start spec_server."
+ task :start do
+ if File.exist?(daemonized_server_pid)
+ $stderr.puts "spec_server is already running."
+ else
+ $stderr.puts "Starting up spec server."
+ system("ruby", "script/spec_server", "--daemon", "--pid", daemonized_server_pid)
+ end
+ end
+
+ desc "stop spec_server."
+ task :stop do
+ unless File.exist?(daemonized_server_pid)
+ $stderr.puts "No server running."
+ else
+ $stderr.puts "Shutting down spec_server."
+ system("kill", "-s", "TERM", File.read(daemonized_server_pid).strip) &&
+ File.delete(daemonized_server_pid)
+ end
+ end
+
+ desc "reload spec_server."
+ task :restart do
+ unless File.exist?(daemonized_server_pid)
+ $stderr.puts "No server running."
+ else
+ $stderr.puts "Reloading down spec_server."
+ system("kill", "-s", "USR2", File.read(daemonized_server_pid).strip)
+ end
+ end
+ end
+end
|
hiddentao/patterns2
|
179e157c6f7cd1bba0783042a65ffea18f4ebd8d
|
Added validation for blocks. We now ensure that the block that is to be updated exists.
|
diff --git a/components/block.inc b/components/block.inc
index 1cd1736..f4f241c 100644
--- a/components/block.inc
+++ b/components/block.inc
@@ -1,163 +1,178 @@
<?php
require_once('_common.php');
function block_patterns($op, $id = null, &$data = null) {
switch($op) {
// Return the valid tags that this component can prepare and process
case 'tags':
return array('block');
break;
// Return a list of forms/actions this component can handle
case 'actions':
return array(
'block_admin_display_form' => t('Block: Change the region or order of a block'),
'block_admin_configure' => t('Block: Configure block'),
'block_add_block_form' => t('Block: Add block'),
'block_box_delete' => t('Block: Delete block')
);
break;
// Prepare data for processing
case 'prepare':
if (isset($data['id'])) {
$split = strpos($data['id'], '-');
$data['module'] = substr($data['id'], 0, $split);
$data['delta'] = substr($data['id'], $split + 1);
unset($data['id']);
}
// Block description for custom blocks is always unique so we can try to get delta by looking up info field
elseif (!empty($data['info'])) {
$delta = db_result(db_query('SELECT delta FROM {blocks} bl INNER JOIN {boxes} bo ON bl.delta = bo.bid AND bl.module = "block" WHERE info = "%s"', $data['info']));
if (!empty($delta)) {
$data['delta'] = $delta;
$data['module'] = 'block';
}
}
if (!empty($data['description'])) {
$data['info'] = $data['description'];
unset($data['description']);
}
if (!empty($data['delete']) && empty($data['info']) && $data['module'] == 'block') {
$data['info'] = db_result(db_query('SELECT info FROM {boxes} WHERE bid = "%d"', $data['delta']));
}
if (!empty($data['pages']) && is_array($data['pages'])) {
$pages = implode("\r\n", $data['pages']);
$data['pages'] = str_replace('[front]', '<front>', $pages);
}
// ##! Patch to allow for modules other than 'block'
// use isset() rather than empty() for $data['delta']
// since $data['delta'] can be 0.
if ( empty($data['module']) || !isset($data['delta']) ) {
$data['module'] = 'block';
}
break;
// Pre validate actions
case 'pre-validate':
if (!(isset($data['module']) && isset($data['delta'])) && !$data['info']) {
return t('Missing required <module>, <delta> tags. Possibly malformed <id> tag could be the problem too. If creating a new block, tag <info> is required.');
}
else if (!empty($data['delete']) && $data['module'] != 'block') {
return t('Unable to delete non-block module blocks');
}
break;
// Return the form_id('s) for each action
case 'form_id':
$diff = array_diff($data, _block_patterns_display_keys());
if (!($data['module'] && $data['delta']) && $data['info']) {
return array(
'block_add_block_form',
'block_admin_display_form'
);
}
else if ($data['delete']) {
return 'block_box_delete';
}
else if (empty($diff)) {
return 'block_admin_display_form';
}
else {
return array(
'block_admin_configure',
'block_admin_display_form'
);
}
break;
// Prepare for valid processing of this type of component
case 'build':
_pattern_component_replace_format_name_with_id($data);
module_load_include('inc', 'block', 'block.admin');
// Fetch and sort blocks
$blocks = _block_rehash();
usort($blocks, '_block_compare');
if ($id == 'block_box_delete') {
$data['op'] = t('Delete');
$data['confirm'] = 1;
}
else if ($id == 'block_admin_display_form') {
if (isset($data['status']) && $data['status'] == 0) {
$data['region'] = -1;
}
// make sure delta is defined even for blocks that have just been created within the same action
if ($data['module'] == 'block' && empty($data['delta'])) {
// we can do this because block descriptions are always unique
$data['delta'] = db_result(db_query("SELECT bid FROM {boxes} WHERE info = '%s'", $data['info']));
}
$data = array($data['module'] .'_'. $data['delta'] => $data);
}
return $data;
break;
// Validate the values for an action before running the pattern
case 'validate':
-
+
+ // only want to check for cases where we are updating a block
+ if (empty($data['info']) && !empty($data['module']) && !empty($data['delta'])) {
+ $blocks = _block_rehash();
+ $found = FALSE;
+ foreach ($blocks as $b) {
+ if ($b['module'] == $data['module'] && $b['delta'] == $data['delta']) {
+ $found = TRUE;
+ break;
+ }
+ }
+ if (!$found) {
+ return t('Invalid block definition: %module - %delta', array('%module' => $data['module'], '%delta' => $data['delta']));
+ }
+ }
+
if (TRUE !== ($ret = _pattern_component_validate_format($data))) {
return $ret;
}
break;
// Build a patterns actions and parameters
case 'params':
if ($id == 'block_admin_configure') {
return array($data['module'], $data['delta']);
}
else if ($id == 'block_admin_display_form') {
$blocks = _block_rehash();
$check = current($data);
// Only return the block we are dealing with now
foreach($blocks as $key => &$block) {
if ($block['module'] == $check['module'] && $block['delta'] == $check['delta']) {
$blocks = array(&$block);
break;
}
}
return array($blocks, $check['theme']);
}
else if ($id == 'block_box_delete') {
return $data['delta'];
}
break;
}
}
function _block_patterns_display_keys() {
return array('module', 'delta', 'theme', 'weight', 'region', 'status');
}
|
hiddentao/patterns2
|
9732bb4eb66ae2ed0c2f82f2443d377481d2d0fa
|
Added a 'translate' attribute for the Menu Trails pattern. If you have deployed multiple sites in different languages but with each having the same basic menu structure (albeit translated menu items) you don't want to have to repeat Menu Trail patterns for each language.
|
diff --git a/components/menutrails.inc b/components/menutrails.inc
index 640eedc..e91416f 100644
--- a/components/menutrails.inc
+++ b/components/menutrails.inc
@@ -1,155 +1,172 @@
<?php
/**
* Component for updating menutrails configuration.
* @author Ramesh Nair (hiddentao)
*/
function menutrails_patterns($op, $id = null, &$data = null) {
switch($op) {
// Return the valid tags that this component can prepare and process
case 'tags':
return array('menu_trail');
break;
// Return a list of forms/actions this component can handle
case 'actions':
return array(
'menutrails_settings_form' => t('Menu Trails: Add/configure trails'),
);
break;
// Return a summary of an action
case 'summary':
if ('menutrails_settings_form' == $id && isset($data['type'])) {
return t('Configuring trail for node type: %name', array('%name' => $data['type']));
}
break;
// Prepare data for processing
case 'prepare':
break;
// Pre validate actions
case 'pre-validate':
if (!module_exists('menutrails')) {
return t('Menu Trails module must be enabled.');
}
if (!isset($data['menu']) || !isset($data['menu']['parent']) || !isset($data['menu']['item'])) {
return t('Valid "menu" (with "parent" and "item") required.');
}
if (!isset($data['type'])) {
return t('You must specify a "type" to associate with the menu.');
}
break;
// Return the form_id('s) for each action
case 'form_id':
return 'menutrails_settings_form';
break;
// Prepare for valid processing of this type of component
case 'build':
if ('menutrails_settings_form' == $id) {
// node type
$types = node_get_types('types');
$type_internal_name = '';
foreach ($types as $type => $info) {
if ($info->name == $data['type']) {
$type_internal_name = $type;
break;
} else if ($type == $data['type']) {
$type_internal_name = $type;
break;
}
}
// menu item
$menus = menu_get_menus(TRUE);
$menu_internal_name = '';
foreach ($menus as $name => $title) {
if ($title == $data['menu']['parent']) {
$menu_internal_name = $name;
break;
} else if ($name == $data['menu']['parent']) {
$menu_internal_name = $name;
break;
}
}
$tree = menu_tree_all_data($menu_internal_name);
- $menu_item = _menutrails_patterns_get_menu_item($tree, $data['menu']['item']);
+
+ if (is_array($data['menu']['item'])) {
+ $menu_item_name = $data['menu']['item']['value'];
+ if ('true' == $data['menu']['item']['translate']) {
+ $menu_item_name = t($menu_item_name, array(), language_default('language'));
+ }
+ } else {
+ $menu_item_name = $data['menu']['item'];
+ }
+ $menu_item = _menutrails_patterns_get_menu_item($tree, $menu_item_name);
// update params
$data['menutrails_node_types'][$type_internal_name] = $menu_item['link']['href'];
}
return $data;
break;
// Validate the values for an action before running the pattern
//
// Check here rather than in pre-validate in case we're adding
// roles or filters in the same pattern.
//
case 'validate':
// check node type
$types = node_get_types('types');
$found = FALSE;
foreach ($types as $type => $info) {
if ($type == $data['type'] || $info->name == $data['type']) {
$found = TRUE;
break;
}
}
if (!$found) {
return t('Invalid content type: %type', array('%type' => $data['type']));
}
// check menu
$menus = menu_get_menus(TRUE);
$found = FALSE;
$name = '';
foreach ($menus as $name => $title) {
if ($title == $data['menu']['parent'] || $name == $data['menu']['parent']) {
$found = TRUE;
break;
}
}
if (!$found)
return t('Invalid menu name: %menu', array('%menu' => $data['menu']['parent']));
// check menu item
$tree = menu_tree_all_data($name);
- $menu_item = _menutrails_patterns_get_menu_item($tree, $data['menu']['item']);
+ if (is_array($data['menu']['item'])) {
+ $menu_item_name = $data['menu']['item']['value'];
+ if ('true' == $data['menu']['item']['translate']) {
+ $menu_item_name = t($menu_item_name, array(), language_default('language'));
+ }
+ } else {
+ $menu_item_name = $data['menu']['item'];
+ }
+ $menu_item = _menutrails_patterns_get_menu_item($tree, $menu_item_name);
if (!$menu_item)
- return t('Invalid menu item: %item', array('%item' => $data['menu']['item']));
+ return t('Invalid menu item: %item', array('%item' => $menu_item_name));
break;
// Build a patterns actions and parameters
case 'params':
return array();
break;
}
}
function _menutrails_patterns_get_menu_item(&$tree, $menu_item_name) {
foreach ($tree as $item) {
// only want content nodes that are hidden
if ($menu_item_name == $item['link']['title']) {
return $item;
}
if (isset($item['below']) && is_array($item['below']) && !empty($item['below'])) {
$ret = _menutrails_patterns_get_menu_item($item['below'], $menu_item_name);
if ($ret) {
return $ret;
}
}
}
return FALSE;
}
|
hiddentao/patterns2
|
69e0a1de7933c7dccb33ec7b861b911f84e82fa4
|
The patterns custom error handler should ignore errors which have been deliberately suppressed (e.g. from within variable_set()).
|
diff --git a/patterns.module b/patterns.module
index 415876a..93d0c15 100644
--- a/patterns.module
+++ b/patterns.module
@@ -2398,975 +2398,980 @@ function patterns_sync_form_values($args) {
// Set the default value unless it is a type of value that would originally
// not be set in $_POST during form submit, like empty selects
if (!$found) {
$check['#missing_in_pattern'] = true;
$match = $check['#default_value'];
}
}
if (!empty($check['#options'])) {
$scalar = false;
if ((!$check['#tree'] && !$check['#multiple']) || (isset($check['#multiple']) && !$check['#multiple']) || in_array($check['#type'], array('radio', 'radios'))) {
$scalar = true;
}
// Find possible corresponding data in form values
$match = &$form_values;
$found = true;
foreach($check['#parents'] as $path) {
if (isset($match[$path])) {
$match = &$match[$path];
}
else {
$found = false;
break;
}
}
if ($found && isset($match)) {
// Check if we are overwriting or not.
//
// First, if the pattern value is there, but empty, we obviously
// should be overwriting. Next is to check if overwrite was specified
// manually
if (!$check['#missing_in_pattern'] && (empty($match) || (is_array($match) && isset($match['_overwrite_'])))) {
$overwrite = true;
if (is_array($match) && isset($match['_overwrite_'])) {
$match = $match['_overwrite_'];
}
}
// If overwriting, start the values array with all the
// possible values but empty. We will possibly fill them
// in with default values on update actions. Select types
// do not work when empty, non-selected, values are set
if (!$scalar && $overwrite && $check['#type'] != 'select') {
$values = $check['#options'];
foreach($values as &$v) {
$v = '';
}
}
else {
$values = array();
}
if (!$overwrite && !empty($check['#default_value'])) {
foreach((array)$check['#default_value'] as $value) {
$values[$value] = $value;
}
// Make sure we are still restricted to values available in #options
$values = array_intersect_key($values, $check['#options']);
}
// Flatten out the options in case it is trying to use optgroups
$options = patterns_options_flatten($check['#options']);
foreach((array)$match as $value) {
$key = array_search($value, $options);
// If the supplied value is an actual options value (not the label) use that
if ( (is_numeric($value) || is_string($value)) && array_key_exists($value, $options)) {
$values[$value] = $value;
}
// Or if the supplied value matches an options label, use that option
else if ($key !== FALSE) {
$values[$key] = $key;
}
// If we are trying to set an invalid value, at least select
// the first value for select forms since it is impossible to
// not select a good value there
else if ($check['#type'] == 'select') {
reset($options);
$values[key($options)] = key($options);
}
}
// If we are not on a multiple/tree form, the value should be singular/not an array.
// We make sure to use the last value here because the last value will absolutely
// be the user/pattern supplied value as opposed to the default_value
if ($scalar) {
$match = end($values);
}
else {
$match = $values;
}
}
}
foreach(element_children($check) as $element) {
$queue[] = &$check[$element];
}
}
// Make sure the new form_values will be used in the real executions
$args[1]['values'] = $form_values;
}
/**
* Helper function to flatter options, but keep the title/names in
*/
function patterns_options_flatten($array, $reset = TRUE) {
static $return;
if ($reset) {
$return = array();
}
foreach ($array as $key => $value) {
if (is_object($value)) {
patterns_options_flatten($value->option, FALSE);
}
else if (is_array($value)) {
patterns_options_flatten($value, FALSE);
}
else {
$return[$key] = $value;
}
}
return $return;
}
/**
* Take a $data and $config object and adjust $data
* based on the supplied configuration
*
* TODO Look for ways to optimize and increase performance
*/
function patterns_config_data(&$data, $configs) {
foreach($configs as $path => $config) {
// An alias key requires multiple paths
// for each alias and then a #real set
// to change all of them to the same key
// TODO test #alias
if ($config['#alias'] && is_array($config['#alias'])) {
$tokens = array_slice(preg_split('/(?<!=)\/(?![a-z]*\])/', $path), 1);
$real = end($tokens);
// Check for the real key
$matches = patterns_array_fetch($path, $data);
// If the real key was not found, get the aliases
if (empty($matches)) {
if (!$config['#key']) {
$config['#key'] = $real;
}
foreach($config['#alias'] as $alias) {
$tokens[count($tokens)-1] = $alias;
$matches += patterns_array_fetch('/'. implode('/', $tokens), $data);
}
}
}
else {
$matches = patterns_array_fetch($path, $data);
}
// If no matches were found and it is a required element
// return an error
if (empty($matches) && $config['#required']) {
$error = true;
}
foreach($matches as &$match) {
// Collect form_ids here.
// TODO Think of a better way to migrate components form_id operations here
if ($config['#form_id']) {
patterns_config_form_ids($data['tag'], $config['#form_id'], $match);
}
// Make sure values that should be arrays are set as such
if ($config['#array'] && !array_key_exists(0, $match['item'])) {
if (is_null($match['item']) || (is_array($match['item'] && empty($match['item'])))) {
$match['item'] = array();
}
else {
$match['item'] = array($match['item']);
}
// Update the context object to reflect new changes
$match = _patterns_array_context($match['item'], $match);
}
// Change the key of this match. Can get the key value via xpath as well.
// Any duplicate keys will return an error
if ($config['#key']) {
// Check that a single match is found via this xpath and that the resulting value is scalar
if ($config['#key']{0} == '/' && ($sub_matches = patterns_array_fetch($config['#key'], $match['item'], $match)) && count($sub_matches) == 1 && is_scalar($sub_matches[0]['item'])) {
// an xpath from the matched item is used to get the key value
$new_key = $sub_matches[0]['item'];
}
else if ($config['#default key']) {
$new_key = $config['#default key'];
}
else if ($config['#key']{0} == '/') {
// Could not find the appropriate key value from the xpath
$error = true;
}
else {
// Set the key to a static value. Typically used for allowing more user readable keys
$new_key = $config['#key'];
}
if ($new_key && array_key_exists($new_key, $match['parent']['item'])) {
// The new key already exists.
$error = true;
}
else if ($new_key) {
$key = $match['key'];
$match['parent']['item'][$new_key] = $match['item'];
// TODO This is buggy. Skip for now.
if(is_int($key) && false) {
array_splice($match['parent']['item'], $key, 1);
}
else {
unset($match['parent']['item'][$key]);
}
// Update the parent context object to reflect new changes
$match['parent'] = _patterns_array_context($match['parent']['item'], $match['parent']);
// Update to the new current match
for($i=0;$i<count($match['parent']);$i++) {
if ($match['parent'][$i]['key'] == $new_key) {
$match = &$match['parent'][$i];
break;
}
}
}
}
// Create empty key elements if they don't exist but should (and are not required)
// This is useful when using 'move' to ensure that the destination exists
if ($config['#create'] && is_array($match['item']) && !array_key_exists($config['#create'], $match['item'])) {
$match['item'][$config['#create']] = $config['#create value'];
}
// Move(or copy) this match to somewhere else in the object. If more than one destination
// match is found, this value is copied to each one
// TODO Make move automatically create the destination if it doesn't exist
// TODO Support move in (put inside array) and move to (replace) actions
if (!empty($match['parent']) && ($config['#move']{0} == '/' && ($dest_path = $config['#move']) && ($op = 'move')) ||
($config['#copy']{0} == '/' && ($dest_path = $config['#copy']) && ($op = 'copy'))) {
$dests = patterns_array_fetch($dest_path, $match['item'], $match);
$parent = &$match['parent'];
$obj = $match['item'];
foreach($dests as $dest) {
// Can't move to items that are not an array
if (!is_array($dest['item'])) {
continue;
}
if (!is_int($match['key'])) {
$dest['item'][$match['key']] = $obj;
}
else {
$dest['item'][] = $obj;
}
// Update the dest object to reflect the change
$dest = _patterns_array_context($dest['item'], $dest);
}
if ($op == 'move') {
if (!is_int($match['key'])) {
unset($parent['item'][$match['key']]);
}
else {
array_splice($parent['item'], $match['key'], 1);
}
// Update the parent object to reflect the change (removal)
$parent = _patterns_array_context($parent['item'], $parent);
unset($match);
}
}
}
}
}
/**
* Find parts of an array based on
* a semi-compatible xpath syntax.
*
* Returns an array of constructs that includes the
* references 'item' and 'parent' from the matching values
* in the $data object along with extra keys 'key' for the key
* of the current match and 'trace' for a full list of keys
* till the root of the $data object
*
* Loosely based off of Cake function Set::extract
*
* @Note: Ensure this always only returns matches from a single level
* in the array. Changes made to matches in different levels can possibly
* mess up the above-level matches. To this end, you cannot change the keys
* of a current match because the other matches cannot change their keys as well
* to sync with the new parent array.
* @TODO: Think of a solution for the above note (BROKEN RIGHT NOW)
*/
function patterns_array_fetch($path, &$data, $context = null) {
if (!$context && (empty($data) || !is_array($data))) {
return array();
}
if ($path === '/') {
return $data;
}
// Construct our contexts object that allows us to traverse the array
if(!$context) {
$context = _patterns_array_context($data);
}
// Make our context actually a list of contexts
$context = array($context);
// Create a list of tokens based on the supplied path
$tokens = array_slice(preg_split('/(?<!=)\/(?![a-z]*\])/', $path), 1);
while(!empty($tokens)) {
$token = array_shift($tokens);
// TODO Implement better conditionals for each token
// Currently only supports element=value conditions
$conditions = array();
if (preg_match('/(=)(.*)/', $token, $m)) {
$conditions[$m[1]] = $m[2];
$token = substr($token, 0, strpos($token, $m[1]));
}
$matches = array();
foreach ($context as &$piece) {
if ($token === '..') {
$matches[] = &$piece['parent'];
continue;
}
$match = false;
if (is_array($piece['item']) && ($token == '*' || array_key_exists($token, $piece['item']))) {
$i=0;
while(isset($piece[$i])) {
if ($piece[$i]['key'] === $token) {
$matches[] = &$piece[$i];
break;
}
else if ($token === '*') {
$matches[] = &$piece[$i];
}
$i++;
}
}
else if ($token === '.') {
$matches[] = &$piece;
}
}
// Filter matches from the matches list based on our conditions
foreach($conditions as $operator => $value) {
_patterns_array_filter($matches, $operator, $value);
}
// Update the context area to the next set of matches to dig into
$context = $matches;
}
// Return the list of matches containing references to their respective data objects
return $matches;
}
/**
* Helper function to create a context array based on the supplied object
* Supplying a parent object will set the parent for this context
*/
function _patterns_array_context(&$obj, &$current = null) {
// If a current context is set, use it's parent and key values
if (!($trace = $current['trace'])) {
$trace = array();
}
if (!($key = $current['key'])) {
$key = null;
}
if (!($parent = &$current['parent'])) {
$parent = null;
}
$context = array('trace' => $trace, 'key' => $key, 'item' => &$obj, 'parent' => &$parent);
$refs = array(&$context);
while (!empty($refs)) {
$ref = &$refs[0];
$parent = &$ref['item'];
array_splice($refs, 0, 1);
if (is_array($parent) && !empty($parent)) {
$i = 0;
foreach($parent as $index => &$child) {
// TODO possible optimizations can be done here (with the parent trace)
$ref[$i] = array('trace' => _patterns_array_trace($ref), 'key' => $index, 'item' => &$child, 'parent' => &$ref);
array_unshift($refs, '');
$refs[0] = &$ref[$i++];
}
}
}
return $context;
}
/**
* Helper function to filter values of the list of matches
*/
function _patterns_array_filter(&$matches, $operator, $value = null) {
for($i=count($matches)-1;$i>=0;$i--) {
$match = &$matches[$i];
switch($operator) {
case '=':
if ($match['item'] != $value) {
array_splice($matches, $i, 1);
}
break;
}
}
}
/**
* Helper function to create a list of parent keys given a context item
*/
function _patterns_array_trace($obj) {
// Loop back up through the parents to fill in the trace value.
$up = &$obj;
$trace = array();
while(isset($up['parent'])) {
array_unshift($trace, $up['key']);
$up = &$up['parent'];
}
return $trace;
}
/**
* Check if all the module dependencies are available
*
* @param $modules
* array of module names
* @param $update_list
* if TRUE, add all the dependecies to pattern's module list
* @return
* empty array if all dependencies are available
* array of missing module's names if some dependencies are not available
*
*/
function patterns_check_module_dependencies(&$modules, $update_list = FALSE) {
if (empty($modules)) return array();
$modules_info = module_rebuild_cache();
$result = array();
$dependencies = array();
foreach($modules as $module) {
$module = is_array($module) ? $module['value'] : $module;
if (array_key_exists($module, $modules_info)) {
// check also for module's dependencies
foreach ($modules_info[$module]->info['dependencies'] as $dependency) {
if (array_key_exists($dependency, $modules_info)) {
$dependencies[] = $dependency;
}
else {
$result[] = $dependency;
}
}
}
else {
$result[] = $module;
}
}
if ($update_list && empty($result) && !empty($dependencies)) {
$modules = array_unique(array_merge($modules, $dependencies));
}
return $result;
}
function patterns_set_error_handler() {
// set custom error handler
set_error_handler('patterns_error_handler');
// trigger dummy error
// this will be used as a refrence to determine if any real error
// occured during the pattern execution
@trigger_error('patterns_error');
}
function patterns_restore_error_handler() {
restore_error_handler();
}
/**
* Custom error handler used only during patterns execution
* in order to catch and properly handle PHP errors.
* Based on drupal_error_handler().
*/
function patterns_error_handler($errno, $message, $filename, $line, $context) {
+ // ignore suppressed errors (http://www.php.net/manual/en/language.operators.errorcontrol.php#98895)
+ if (0 == error_reporting()) {
+ return TRUE;
+ }
+
if ($errno & (E_ALL ^ E_NOTICE)) {
$types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning', 4096 => 'recoverable fatal error');
// For database errors, we want the line number/file name of the place that
// the query was originally called, not _db_query().
if (isset($context[DB_ERROR])) {
$backtrace = array_reverse(debug_backtrace());
// List of functions where SQL queries can originate.
$query_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
// Determine where query function was called, and adjust line/file
// accordingly.
foreach ($backtrace as $index => $function) {
if (in_array($function['function'], $query_functions)) {
$line = $backtrace[$index]['line'];
$filename = $backtrace[$index]['file'];
break;
}
}
}
// 'patterns_error' is not a real error and should be skipped
if ($message != 'patterns_error') {
watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
patterns_error_set_last(array('message' => $message, 'type' => $errno, 'file' => $filename, 'line' => $line));
}
}
return TRUE;
}
function patterns_error_set_last($error = NULL) {
static $last_error = array();
if (isset($error)) {
$last_error = $error;
}
return $last_error;
}
/**
* Check and report PHP errors during patterns execution
*
* @param $op
* operation within hook_patterns() during which error occured
* @param $key
* number of the action currently proccessed
* @param $description
* description of the current action
* @param $pattern_title
* title of the pattern currently proccessed
* @param $pattern_file
* path to pattern file currently proccessed
* @return
* error message if new error encountered
* FALSE if there are no new errors
*
*/
function patterns_error_get_last($op, $key, $description, $pattern_title, $pattern_file) {
$error = patterns_error_set_last();
if (!empty($error) && $error['message'] != 'patterns_error') {
$types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning', 4096 => 'recoverable fatal error');
$php_error_message = $types[$error['type']] .': '. $error['message'] .' in '. $error['file'] .' on line '. $error['line'] .'.';
$message = t('Pattern %title (%pattern_file)<br>Action #%key: %description (op "%op")<br>PHP error occured:<br>%error', array('%key' => $key, '%title' => $pattern_title, '%op' => $op, '%description' => $description, '%error' => $php_error_message, '%pattern_file' => $pattern_file));
return $message;
}
return FALSE;
}
/**
* Custom implementation of drupal_process_form()
*
* Enables validation to be performed for each executed form
* by calling our custom _patterns_validate_form() function
* see issue: http://drupal.org/node/260934
*/
function _patterns_process_form($form_id, &$form, &$form_state) {
$form_state['values'] = array();
$form = form_builder($form_id, $form, $form_state);
// Only process the form if it is programmed or the form_id coming
// from the POST data is set and matches the current form_id.
if ((!empty($form['#programmed'])) || (!empty($form['#post']) && (isset($form['#post']['form_id']) && ($form['#post']['form_id'] == $form_id)))) {
_patterns_validate_form($form_id, $form, $form_state);
// form_clean_id() maintains a cache of element IDs it has seen,
// so it can prevent duplicates. We want to be sure we reset that
// cache when a form is processed, so scenerios that result in
// the form being built behind the scenes and again for the
// browser don't increment all the element IDs needlessly.
form_clean_id(NULL, TRUE);
if ((!empty($form_state['submitted'])) && !form_get_errors() && empty($form_state['rebuild'])) {
$form_state['redirect'] = NULL;
form_execute_handlers('submit', $form, $form_state);
// We'll clear out the cached copies of the form and its stored data
// here, as we've finished with them. The in-memory copies are still
// here, though.
if (variable_get('cache', CACHE_DISABLED) == CACHE_DISABLED && !empty($form_state['values']['form_build_id'])) {
cache_clear_all('form_'. $form_state['values']['form_build_id'], 'cache_form');
cache_clear_all('storage_'. $form_state['values']['form_build_id'], 'cache_form');
}
// If batches were set in the submit handlers, we process them now,
// possibly ending execution. We make sure we do not react to the batch
// that is already being processed (if a batch operation performs a
// drupal_execute).
if ($batch =& batch_get() && !isset($batch['current_set'])) {
// The batch uses its own copies of $form and $form_state for
// late execution of submit handers and post-batch redirection.
$batch['form'] = $form;
$batch['form_state'] = $form_state;
$batch['progressive'] = !$form['#programmed'];
batch_process();
// Execution continues only for programmatic forms.
// For 'regular' forms, we get redirected to the batch processing
// page. Form redirection will be handled in _batch_finished(),
// after the batch is processed.
}
// If no submit handlers have populated the $form_state['storage']
// bundle, and the $form_state['rebuild'] flag has not been set,
// we're finished and should redirect to a new destination page
// if one has been set (and a fresh, unpopulated copy of the form
// if one hasn't). If the form was called by drupal_execute(),
// however, we'll skip this and let the calling function examine
// the resulting $form_state bundle itself.
if (!$form['#programmed'] && empty($form_state['rebuild']) && empty($form_state['storage'])) {
drupal_redirect_form($form, $form_state['redirect']);
}
}
}
}
/**
* Custom implementation of drupal_validate_form()
*
* Removed static variable that prevented same form_id to be
* validated more then once during a single page request
*/
function _patterns_validate_form($form_id, $form, &$form_state) {
// If the session token was set by drupal_prepare_form(), ensure that it
// matches the current user's session.
if (isset($form['#token'])) {
if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
// Setting this error will cause the form to fail validation.
form_set_error('form_token', t('Validation error, please try again. If this error persists, please contact the site administrator.'));
}
}
_form_validate($form, $form_state, $form_id);
}
/**
* Custom implementation of Drupal's _taxonomy_term_select()
*
* Used to override static caching in taxonmy_get_tree()
* which is preventing terms added during patterns execution
* to be included in parents and relations dropdowns and
* causes validation errors.
* Hopefully, we can find better solution for this.
*/
function _patterns_taxonomy_term_select($title, $name, $value, $vocabulary_id, $description, $multiple, $blank, $exclude = array()) {
$tree = _patterns_taxonomy_get_tree($vocabulary_id);
$options = array();
if ($blank) {
$options[''] = $blank;
}
if ($tree) {
foreach ($tree as $term) {
if (!in_array($term->tid, $exclude)) {
$choice = new stdClass();
$choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
$options[] = $choice;
}
}
}
return array('#type' => 'select',
'#title' => $title,
'#default_value' => $value,
'#options' => $options,
'#description' => $description,
'#multiple' => $multiple,
'#size' => $multiple ? min(9, count($options)) : 0,
'#weight' => -15,
'#theme' => 'taxonomy_term_select',
);
}
/**
* Custom implementation of Drupal's taxonomy_get_tree()
*
* Removed static caching.
* New terms may be created during patterns execution and
* static caching prevents them from being returned in
* all subsequent calls to taxonomy_get_tree() during
* the current pattern execution (within current page request)
*/
function _patterns_taxonomy_get_tree($vid, $parent = 0, $depth = -1, $max_depth = NULL) {
$depth++;
$children[$vid] = array();
$result = db_query(db_rewrite_sql('SELECT t.tid, t.*, parent FROM {term_data} t INNER JOIN {term_hierarchy} h ON t.tid = h.tid WHERE t.vid = %d ORDER BY weight, name', 't', 'tid'), $vid);
while ($term = db_fetch_object($result)) {
$children[$vid][$term->parent][] = $term->tid;
$parents[$vid][$term->tid][] = $term->parent;
$terms[$vid][$term->tid] = $term;
}
$max_depth = (is_null($max_depth)) ? count($children[$vid]) : $max_depth;
$tree = array();
if (!empty($children[$vid][$parent])) {
foreach ($children[$vid][$parent] as $child) {
if ($max_depth > $depth) {
$term = drupal_clone($terms[$vid][$child]);
$term->depth = $depth;
// The "parent" attribute is not useful, as it would show one parent only.
unset($term->parent);
$term->parents = $parents[$vid][$child];
$tree[] = $term;
if (!empty($children[$vid][$child])) {
$tree = array_merge($tree, _patterns_taxonomy_get_tree($vid, $child, $depth, $max_depth));
}
}
}
}
return $tree;
}
/**
* Custom implementation of Drupal's taxonomy_form()
*
* Used to override static caching for taxonomy terms on node edit form.
*/
function _patterns_taxonomy_form($vid, $value = 0, $help = NULL, $name = 'taxonomy') {
$vocabulary = taxonomy_vocabulary_load($vid);
$help = ($help) ? $help : $vocabulary->help;
if (!$vocabulary->multiple) {
$blank = ($vocabulary->required) ? t('- Please choose -') : t('- None selected -');
}
else {
$blank = ($vocabulary->required) ? 0 : t('- None -');
}
return _patterns_taxonomy_term_select(check_plain($vocabulary->name), $name, $value, $vid, $help, intval($vocabulary->multiple), $blank);
}
/**
* Custom implementation of Drupal's menu_parent_options()
*
* Used to override static caching in menu_tree_all_data()
* which is preventing menu items created during patterns execution
* to be included in 'parent item' dropdown and causes validation errors.
* Hopefully, we can find better solution for this.
*/
function _patterns_menu_parent_options($menus, $item) {
// The menu_links table can be practically any size and we need a way to
// allow contrib modules to provide more scalable pattern choosers.
// hook_form_alter is too late in itself because all the possible parents are
// retrieved here, unless menu_override_parent_selector is set to TRUE.
if (variable_get('menu_override_parent_selector', FALSE)) {
return array();
}
// If the item has children, there is an added limit to the depth of valid parents.
if (isset($item['parent_depth_limit'])) {
$limit = $item['parent_depth_limit'];
}
else {
$limit = _menu_parent_depth_limit($item);
}
foreach ($menus as $menu_name => $title) {
$tree = _patterns_menu_tree_all_data($menu_name, NULL);
$options[$menu_name .':0'] = '<'. $title .'>';
_menu_parents_recurse($tree, $menu_name, '--', $options, $item['mlid'], $limit);
}
return $options;
}
/**
* Custom implementation of Drupal's menu_tree_all_data()
*
* Removed static caching.
* New menu items may be created during pattern execution and
* static caching prevents them from being returned in
* all subsequent calls to menu_tree_all_data() during
* the current pattern execution (within current page request)
*/
function _patterns_menu_tree_all_data($menu_name = 'navigation', $item = NULL) {
$tree = array();
// Use $mlid as a flag for whether the data being loaded is for the whole tree.
$mlid = isset($item['mlid']) ? $item['mlid'] : 0;
// Generate a cache ID (cid) specific for this $menu_name and $item.
$cid = 'links:'. $menu_name .':all-cid:'. $mlid;
// If the static variable doesn't have the data, check {cache_menu}.
$cache = cache_get($cid, 'cache_menu');
if ($cache && isset($cache->data)) {
// If the cache entry exists, it will just be the cid for the actual data.
// This avoids duplication of large amounts of data.
$cache = cache_get($cache->data, 'cache_menu');
if ($cache && isset($cache->data)) {
$data = $cache->data;
}
}
// If the tree data was not in the cache, $data will be NULL.
if (!isset($data)) {
// Build and run the query, and build the tree.
if ($mlid) {
// The tree is for a single item, so we need to match the values in its
// p columns and 0 (the top level) with the plid values of other links.
$args = array(0);
for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
$args[] = $item["p$i"];
}
$args = array_unique($args);
$placeholders = implode(', ', array_fill(0, count($args), '%d'));
$where = ' AND ml.plid IN ('. $placeholders .')';
$parents = $args;
$parents[] = $item['mlid'];
}
else {
// Get all links in this menu.
$where = '';
$args = array();
$parents = array();
}
array_unshift($args, $menu_name);
// Select the links from the table, and recursively build the tree. We
// LEFT JOIN since there is no match in {menu_router} for an external
// link.
$data['tree'] = menu_tree_data(db_query("
SELECT m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.title, m.title_callback, m.title_arguments, m.type, m.description, ml.*
FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path
WHERE ml.menu_name = '%s'". $where ."
ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC", $args), $parents);
$data['node_links'] = array();
menu_tree_collect_node_links($data['tree'], $data['node_links']);
// Cache the data, if it is not already in the cache.
$tree_cid = _menu_tree_cid($menu_name, $data);
if (!cache_get($tree_cid, 'cache_menu')) {
cache_set($tree_cid, $data, 'cache_menu');
}
// Cache the cid of the (shared) data using the menu and item-specific cid.
cache_set($cid, $tree_cid, 'cache_menu');
}
// Check access for the current user to each item in the tree.
menu_tree_check_access($data['tree'], $data['node_links']);
$tree[$cid] = $data['tree'];
return $tree[$cid];
}
function patterns_debug_batch($var = null) {
$var = print_r($var, true);
$var = str_replace(" ", ' ', $var);
$var = str_replace("\n", "<br />", $var);
print drupal_to_js(array('status' => 0, 'data' => $var));
exit;
}
// ----------------------------------------------------------------------- //
// Patterns config tags
// ----------------------------------------------------------------------- //
// Patterns configuration directives
define('PATTERNS_IGNORE_FAILED_ACTIONS','ignore-failed-actions');
function patterns_patterns($op, $id = null, &$data = null) {
switch($op) {
// Return the valid tags that this component can prepare and process
case 'tags':
return array('patterns-config');
break;
// Return a list of forms/actions this component can handle
case 'actions':
return array(
'patterns_processing_config_form' => t('Patterns config: Configure the patterns processor'),
);
break;
// Return a summary of an action
case 'summary':
return t('Setting processing flag "%name" to value "%value"', array('%name' => $data['name'], $data['value']));
break;
// Pre validate actions
case 'pre-validate':
if (!isset($data['name']) || !isset($data['value'])) {
return t('Both "name" and "value" are required attributes.');
}
if (!in_array($data['name'], array(PATTERNS_IGNORE_FAILED_ACTIONS))) {
return t('Unrecognized processing directive: %name', array('%name' => $data['name']));
}
break;
// Return the form_id('s) for each action
case 'form_id':
return 'patterns_processing_config_form';
break;
// Prepare for valid processing of this type of component
case 'build':
return $data;
break;
// Build a patterns actions and parameters
case 'params':
return array();
break;
}
}
function patterns_processing_config_form($form_state) {
$form = array();
$form['name'] = array( '#type' => 'textfield' );
$form['value'] = array( '#type' => 'textfield' );
return $form;
}
function patterns_processing_config_form_submit($form, &$form_state) {
switch ($form_state['values']['name']) {
case PATTERNS_IGNORE_FAILED_ACTIONS:
if (1 == $form_state['values']['value']) {
$_SESSION[PATTERNS_IGNORE_FAILED_ACTIONS] = TRUE;
patterns_processing_config_show_msg(t('%flag turned ON',array('%flag' => PATTERNS_IGNORE_FAILED_ACTIONS)));
} else {
unset($_SESSION[PATTERNS_IGNORE_FAILED_ACTIONS]);
patterns_processing_config_show_msg(t('%flag turned OFF',array('%flag' => PATTERNS_IGNORE_FAILED_ACTIONS)));
}
break;
}
}
function patterns_processing_config_show_msg($msg) {
drupal_set_message("PATTERNS CONFIG: $msg", 'warning');
}
/**
* Reset all processing configuration.
*/
function patterns_processing_config_reset() {
unset($_SESSION[PATTERNS_IGNORE_FAILED_ACTIONS]);
}
|
hiddentao/patterns2
|
716599bc0485381f9faeeff002217254433b62c4
|
Fixed minor bug in patterns_get_patterns() method.
|
diff --git a/patterns.module b/patterns.module
index 55907fe..415876a 100644
--- a/patterns.module
+++ b/patterns.module
@@ -438,1025 +438,1025 @@ function patterns_import_server_submit($form, &$form_state) {
// save file
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
$path .= '/'. $pattern_info['name'] .'.'. $pattern_info['file_type'];
if (!$saved = file_save_data($source, $path, FILE_EXISTS_ERROR)) {
$errors['save file'][] = $pattern_info;
continue;
}
// choose appropriate function based on the file extension
$func = 'patterns_load_'. $pattern_info['file_type'];
// Load pattern
if (!$pattern = $func($saved)) {
$errors['load pattern'][] = $pattern_info;
unlink($saved);
continue;
}
patterns_save_pattern($pattern, $saved, $pattern_info['name']);
}
if (!empty($errors)) {
$patterns = array();
foreach ($errors as $type => $files) {
foreach ($files as $file) {
$patterns[] = $file['title'] .' (cause: "'. $type .'" failed)';
}
$patterns = theme('item_list', $patterns);
}
drupal_set_message(t('Import failed for the following patterns: ') .'<br>'. $patterns, 'error');
return;
}
unset($form_state['storage']);
$form_state['redirect'] = 'admin/build/patterns';
}
function patterns_feed_rearrange_data($feed) {
unset($feed['tag']);
foreach ($feed as $key => $section) {
$tag = $section['tag'];
if ($tag == 'pattern') {
unset($section['tag']);
if (!isset($section['value'])) {
foreach ($section as $t) {
if ($t['tag'] == 'pid') {
$pid = $t['value'];
break;
}
}
$result[$pid] = patterns_feed_rearrange_data($section);
}
else {
$result[$tag] = $section['value'];
}
}
else {
unset($section['tag']);
if (!isset($section['value'])) {
$result[$tag] = patterns_feed_rearrange_data($section);
}
else {
$result[$tag] = $section['value'];
}
}
}
return $result;
}
function patterns_publish_pattern($pid) {
if (is_numeric($pid)) {
$result = db_query("UPDATE {patterns} SET public = 1 WHERE pid = %d", $pid);
}
drupal_set_message('Pattern published.');
drupal_goto('admin/build/patterns');
}
function patterns_unpublish_pattern($pid) {
if (is_numeric($pid)) {
$result = db_query("UPDATE {patterns} SET public = 0 WHERE pid = %d", $pid);
}
drupal_set_message('Pattern unpublished.');
drupal_goto('admin/build/patterns');
}
/**
* Display the import pattern file form
*/
function patterns_import_file(&$form_state) {
if (empty($form_state['post'])) {
drupal_set_message(t('Import feature currently supports only XML file format.'), 'warning');
}
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['xmlfile'] = array(
'#type' => 'file',
'#title' => t('Upload Pattern File'),
'#description' => t('Imported patterns are not executed until you run them manually.'),
'#size' => 48
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import')
);
$form['#validate'][] = 'patterns_import_validate';
$form['#submit'][] = 'patterns_import_submit';
return $form;
}
/**
* Display the import pattern url form
*/
function patterns_import_url(&$form_state) {
if (empty($form_state['post'])) {
drupal_set_message(t('Import feature currently supports only XML file format.'), 'warning');
}
$form['xmlurl'] = array(
'#type' => 'textfield',
'#title' => t('Specify an URL'),
'#description' => t('Import a pattern from a remote URL. Imported patterns are not executed until you run them manually.'),
'#size' => 48
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import')
);
$form['#validate'][] = 'patterns_import_validate';
$form['#submit'][] = 'patterns_import_submit';
return $form;
}
function patterns_import_validate($form, &$form_state) {
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (!file_check_directory($path, true)) {
$message = t("Destination folder doesn't exist: !path<br />", array('!path' => $path));
$link = l(t('status report'), 'admin/reports/status');
$message .= t('You might want to check the !link to ensure your files directory exists and is writable.', array('!link' => $link));
form_set_error('xmlfile', $message);
return;
}
$validators = array('file_validate_extensions' => array('xml'));
if (isset($form_state['values']['xmlfile']) && ($file = file_save_upload('xmlfile', $validators))) {
$form_state['values']['xmlsource'] = file_get_contents($file->filepath);
$form_state['pattern_file'] = $file;
$form_state['pattern_file']->destination = $path;
}
else if (isset($form_state['values']['xmlfile'])) {
form_set_error('files[xmlfile]', t('Error uploading XML file.'));
return;
}
else if ($form_state['values']['xmlurl']) {
if (!ini_get('allow_url_fopen')) {
form_set_error('xmlsource', t('allow_url_fopen must be enabled in your php configuration in order to use this feature.'));
return;
}
if (strtolower(substr($form_state['values']['xmlurl'], -4)) != '.xml') {
form_set_error('xmlsource', t('Invalid file extension. Only "XML" file extension is allowed.'));
return;
}
if (!($form_state['values']['xmlsource'] = file_get_contents($form_state['values']['xmlurl']))) {
form_set_error('xmlurl', t('Failed to retreive the pattern specified: '. $form_state['values']['xmlurl']) .'. Check your URL and try again.');
return;
}
$pattern = array('/\.[^\.]*$/', '/[^a-zA-Z0-9_]/');
$replacement = array('', '_');
$form_state['values']['xmlname'] = preg_replace($pattern, $replacement, basename($form_state['values']['xmlurl']));
}
if (strpos($form_state['values']['xmlsource'], '<?xml') !== 0) {
$form_state['values']['xmlsource'] = '<?xml version="1.0" encoding="ISO-8859-1"?>' . $form_state['values']['xmlsource'];
}
if ($form_state['values']['xmlname'] && preg_match('/[^a-zA-Z0-9_]/', $form_state['values']['xmlname'])) {
form_set_error('xmlname', t('You can only include letters, numbers, and underscores in the pattern identifier.'));
}
else if ($form_state['values']['xmlname'] && preg_match('/^_/', $form_state['values']['xmlname'])) {
form_set_error('xmlname', t('You cannot start the pattern identifier with an underscore.'));
}
// @TODO validate XML and don't allow import if validation fails
$parse = drupal_xml_parser_create($form_state['values']['xmlsource']);
$success = xml_parse_into_struct($parse, $form_state['values']['xmlsource'], $vals, $index);
// Check that the xml was properly parsed and also that the
// root <pattern> tag and also an <info> tag were used.
if (!$success || !$vals || $vals[0]['tag'] != 'PATTERN' || $vals[1]['tag'] != 'INFO') {
form_set_error('xmlsource', t('Error parsing the XML, please check your syntax and try again.'));
}
}
function patterns_import_submit($form, &$form_state) {
if (isset($form_state['pattern_file'])) {
$saved = file_copy($form_state['pattern_file']->filepath, $form_state['pattern_file']->destination);
}
else if ($form_state['values']['xmlsource']) {
$saved = file_save_data($form_state['values']['xmlsource'], variable_get('patterns_save_xml', 'patterns') .'/'. $form_state['values']['xmlname'] .'.xml', FILE_EXISTS_REPLACE);
}
if ($saved) {
// Reload patterns
patterns_get_patterns(true);
drupal_set_message('Pattern successfully imported.');
}
else {
drupal_set_message("File couldn't be saved on the server. Import failed.", 'error');
}
$form_state['redirect'] = 'admin/build/patterns';
}
function patterns_list() {
drupal_add_css(drupal_get_path('module', 'patterns') .'/patterns.css');
drupal_add_js(drupal_get_path('module', 'patterns') .'/patterns.js');
patterns_load_components();
$patterns = patterns_get_patterns();
if (empty($patterns)) return t('No patterns available.');
// $header = array(t('Title'), t('Status'), t('Version'), t('Public'), t('Actions'));
$header = array(t('Title'), t('Status'), t('Version'), t('Actions'));
// List all patterns
$rows = array();
foreach($patterns as $pid => $pattern) {
$subpattern_only = (isset($pattern->info['subpattern_only']) && 1==$pattern->info['subpattern_only']);
$hidden = (isset($pattern->info['hidden']) && 1 == $pattern->info['hidden']);
if ($hidden)
continue;
$actions = array();
// cannot run pattern on its own if it's 'subpattern_only'
if (!$subpattern_only) {
if (!$pattern->status) {
$actions[] = l(t('Run'), 'admin/build/patterns/enable/'. $pid);
}
else if ($pattern->enabled >= $pattern->updated) {
$actions[] = l(t('Re-Run'), 'admin/build/patterns/enable/'. $pid);
}
else {
$actions[] = l(t('Run Update'), 'admin/build/patterns/enable/'. $pid);
}
}
$actions[] = l(t('Edit'), 'admin/build/patterns/edit/'. $pid);
if (variable_get('patterns_allow_publish', FALSE)) {
$actions[] = $pattern->public ? l(t('Unpublish'), 'admin/build/patterns/unpublish/'. $pid) : l(t('Publish'), 'admin/build/patterns/publish/'. $pid);
}
$actions = implode(' ', $actions);
$cells = array();
// $title = l($pattern->title, 'admin/build/patterns/info/'. $pid, array('attributes' => array('class' => 'pattern-title', 'id' => 'pid-'. $pid)));
$title = '<span id="pid-'. $pid .'" class="pattern-title">'. $pattern->title . ($subpattern_only ? ' <em>(sub-pattern)</em>' : '') . '</span>';
// $view_more = '<div>'. t('Clik on pattern title to see more details.') .'</div>';
$info = array();
$info[] = t('Author: ') . $pattern->info['author'];
$info[] = t('Email: ') . $pattern->info['author_email'];
$info[] = t('Web: ') . $pattern->info['author_website'];
$author = theme('item_list', $info);
$title .= '<div id="pid-'. $pid .'-info" class="pattern-info">'. $author . $pattern->description . $view_more .'</div>';
$cells[] = array('data' => $title, 'class' => 'title');
$cells[] = array('data' => $pattern->status ? t('Enabled') : t('Disabled'), 'class' => 'status');
$cells[] = array('data' => $pattern->info['version'], 'class' => 'version');
// $cells[] = $pattern->public ? t('Yes') : t('No');
$cells[] = array('data' => $actions, 'class' => 'actions');
$category = $pattern->info['category'] ? $pattern->info['category'] : t('Other');
$rows[$category][] = $cells;
}
ksort($rows);
foreach ($rows as $title => $category) {
$fieldset = array(
'#title' => t($title),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#value' => theme('table', $header, $category, array('class' => 'patterns-list')),
);
$output .= theme('fieldset', $fieldset);
}
return $output;
}
/**
* Menu callback to undo a patterns update changes
*/
// function patterns_revert($pid) {
// if ($name = db_result(db_query('SELECT name FROM {patterns} WHERE pid = "%d"', $pid))) {
// $path = file_create_path(variable_get('patterns_save_xml', 'patterns') .'/enabled/'. $name .'.xml');
// $new = db_result(db_query('SELECT file FROM {patterns} WHERE pid = "%d"'));
// }
// else {
// drupal_set_message(t('The pattern you specified does not exist.'), 'error');
// drupal_goto('admin/build/patterns');
// }
//
// if (file_exists($path)) {
// if (file_move($path, $new, FILE_EXISTS_REPLACE)) {
// drupal_set_message(t('This pattern was reverted to the state it was at when it was enabled.'));
// drupal_goto();
// }
// }
// else {
// drupal_set_message(t('The patterns enabled-state was not saved properly, therefore it cannot be reverted.'), 'error');
// }
//
// drupal_goto('admin/build/patterns');
// }
/**
* Menu callback to display patterns details page
*/
// function patterns_info($pid = null) {
// if (!is_numeric($pid)) {
// drupal_set_message(t('You must specify a pattern.'));
// return;
// }
//
// $pattern = patterns_get_pattern($pid);
//
// $output = '';
// return $output;
// }
/**
* Menu callback to edit a patterns data
*/
function patterns_edit(&$form_state, $pid = null) {
if (!is_numeric($pid)) {
drupal_set_message(t('You must specify a pattern to edit.'));
return;
}
$pattern = patterns_get_pattern($pid);
// TODO: Turn php into xml here.
// For now just allow modifying the original xml, which
// means the modification cannot be further modified
if (!$pattern->file) {
drupal_set_message(t('This pattern does not seem to have an XML source file to base the modifications off of.'), 'error');
return;
}
$xml = file_get_contents($pattern->file);
$form['name'] = array(
'#type' => 'value',
'#value' => $pattern->name
);
$form['pid'] = array(
'#type' => 'value',
'#value' => $pattern->pid
);
// if ($pattern->enabled <= $pattern->updated) {
// $form['revert'] = array(
// '#type' => 'markup',
// '#value' => l(t('Undo update changes to the state when you enabled the pattern.'), 'admin/build/patterns/revert/'. $pid, array(), drupal_get_destination())
// );
// }
$form['format'] = array(
'#type' => 'select',
'#title' => t('Pattern syntax'),
'#options' => array_combine(patterns_file_types(), patterns_file_types()),
'#default_value' => 'xml'
);
$form['xml'] = array(
'#type' => 'textarea',
'#title' => t('Pattern\'s code'),
'#rows' => 25,
'#default_value' => $xml
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}
/**
* Validate pattern modifications (make sure proper XML)
*/
function patterns_edit_validate($form, &$form_state) {
// @TODO Do validations....
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (!file_check_directory($path, true)) {
form_set_error('form_token', t('Unable to create @path to save the new pattern to.', array('@path' => $path)));
}
}
/**
* Submit edits to the pattern
*/
function patterns_edit_submit($form, &$form_state) {
// If this is an enabled pattern, make sure the enabled pattern is saved in its current state
if ($file = db_result(db_query('SELECT file FROM {patterns} WHERE status = 1 AND name = "%s"', $form_state['values']['name']))) {
$dir = file_directory_path() .'/'. variable_get('patterns_save_xml', 'patterns') .'/enabled';
file_check_directory($dir, true);
$path = $dir .'/'. $form_state['values']['name'] .'.'. $form_state['values']['format'];
if (!file_exists($path)) {
file_copy($file, $path, FILE_EXISTS_ERROR);
}
}
// Save the new pattern into the pattern files dir.
$path = file_directory_path() .'/'. variable_get('patterns_save_xml', 'patterns') .'/'. $form_state['values']['name'] .'.'. $form_state['values']['format'];
file_save_data($form_state['values']['xml'], $path, FILE_EXISTS_REPLACE);
$old = db_result(db_query('SELECT file FROM {patterns} WHERE name = "%s"', $form_state['values']['name']));
// Load and save pattern
$load_func = 'patterns_load_' .$form_state['values']['format'];
if ($pattern = $load_func($path)) {
if ($old) {
db_query('UPDATE {patterns} SET file = "%s", updated = "%s" WHERE pid = "%d"', $path, time(), $form_state['values']['pid']);
}
patterns_save_pattern($pattern, $path, $form_state['values']['name']);
drupal_set_message(t('%name was saved.', array('%name' => $form_state['values']['name'])));
$form_state['redirect'] = 'admin/build/patterns';
}
else {
drupal_set_message(t("Pattern '%name' couldn't be saved. Make sure edited code is well-formed.", array('%name' => $form_state['values']['name'])), 'error');
}
}
/**
* List the modules used by a particular pattern
*/
function patterns_modules_page($pid) {
$pattern = patterns_get_pattern($pid);
drupal_set_title($pattern->title .' '. t('(Pattern Modules)'));
$modules = isset($pattern->pattern['modules']) ? $pattern->pattern['modules'] : array();
$modules_info = module_rebuild_cache();
$modules_list = module_list();
// Get module name, whether its to be disabled or enabled,
// whether the module is available or not, and whether it is
// currently enabled or not
foreach($modules as $module) {
$row = array();
$delete = is_array($module) ? $module['delete'] : false;
$module = is_array($module) ? $module['value'] : $module;
$available = array_key_exists($module, $modules_info);
$enabled = array_key_exists($module, $modules_list);
$row[] = $module;
$row[] = $available ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $enabled ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $delete ? t('Delete') : t('Enable');
$rows[] = $row;
if (!$available) {
$not_available = true;
}
}
if ($not_available) {
drupal_set_message(t('Some modules are not availalble, please download them before running this pattern.'), 'error');
}
else {
drupal_set_message(t('All modules required by this module are available. Click !here to run this pattern.', array('!here' => l(t('here'), 'admin/build/patterns/enable/'. $pid))));
}
return theme('table', array(t('Name'), t('Available'), t('Enabled'), t('Pattern Action')), $rows, t('Modules used for this pattern'));
}
function patterns_load_components() {
static $loaded = false;
if ($loaded) {
return;
}
require_once drupal_get_path('module', 'patterns') .'/patterns.inc';
// Get a list of directories to search
$paths = module_invoke_all('patterns_directory');
foreach($paths as $path) {
foreach(file_scan_directory($path .'/components', '.\.inc$') as $file) {
include_once $file->filename;
}
}
$loaded = true;
}
function patterns_get_patterns($reset = true) {
patterns_load_components();
if ($reset || !variable_get('patterns_loaded', false)) {
// Get a listing of enabled patterns
$enabled = array();
$result = db_query('SELECT file FROM {patterns} WHERE status = 1');
while ($pattern = db_fetch_object($result)) {
- $enabled[] = $result->file;
+ $enabled[] = $pattern->file;
}
$priority = array();
$errors = array();
// Get list of directories to scan for patterns
$patterns_paths = patterns_paths();
// get valid file extensions
$mask = '.\.('. implode('|', patterns_file_types()) .')$';
// prepare list of files/folders to be excluded
// 'enabled' - Don't save enabled pattern backups
$no_mask = array('.', '..', 'CVS', '.svn', 'enabled');
foreach ($patterns_paths as $path) {
foreach(file_scan_directory($path, $mask, $no_mask) as $file) {
// Can't update existing patterns that are enabled
if (in_array($file->filename, $enabled) || in_array($file->name, $priority)) {
continue;
}
$priority[] = $file->name;
// choose appropriate function based on the file extension
$func = 'patterns_load_'. substr($file->basename, strlen($file->name) + 1);
// Load and save pattern
if ($pattern = $func($file->filename)) {
patterns_save_pattern($pattern, $file->filename, $file->name);
}
else {
$errors[] = $file->filename;
}
}
}
variable_set('patterns_loaded', time());
}
$result = db_query('SELECT * FROM {patterns}');
$messages = array();
while ($pattern = db_fetch_object($result)) {
// skip pattern if its file is missing
if (!is_file($pattern->file)) continue;
// skip pattern if loading failed and report that to the user
if (in_array($pattern->file, $errors)) {
$messages[] = t("Pattern couldn't be loaded from the file '%file'", array('%file' => $pattern->file));
continue;
}
$patterns[$pattern->pid] = $pattern;
$data = unserialize($pattern->pattern);
$patterns[$pattern->pid]->pattern = $data;
$patterns[$pattern->pid]->info = $data['info'];
}
if (!empty($messages)) {
drupal_set_message(implode('<br>', $messages) .'<br>'. t('Make sure that above file(s) are readable and contain valid data.'), 'error');
}
return $patterns;
}
/**
* return a list of paths that will be scanned for patterns
*/
function patterns_paths() {
global $profile;
if (!isset($profile)) {
$profile = variable_get('install_profile', 'default');
}
// array of all the paths where we should look for patterns
$patterns_paths = array(
conf_path() .'/patterns',
'profiles/'. $profile .'/patterns',
'sites/all/patterns'
);
// allow any module to include patterns too
foreach(module_invoke_all('patterns_directory') as $path) {
if (is_dir($path)) {
$patterns_paths[] = $path .'/patterns';
}
}
// also prepend files folder if it's valid
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (file_check_directory($path)) {
array_unshift($patterns_paths, $path);
}
return $patterns_paths;
}
/**
* Implementation of hook_patterns_directory()
*
* Let us know about where the pattern files are at
*/
function patterns_patterns_directory() {
return drupal_get_path('module', 'patterns');
}
function patterns_save_pattern($pattern, $path = '', $name = '') {
$title = $pattern['info']['title'];
$description = $pattern['info']['description'];
$author = $pattern['info']['author'];
if ($pid = db_result(db_query('SELECT pid FROM {patterns} WHERE name = "%s"', $name))) {
$updated = db_result(db_query('SELECT updated FROM {patterns} WHERE pid = "%d"', $pid));
if (($new_updated = filemtime($path)) > $updated) {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", updated = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $new_updated, $description, $pid);
}
else {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $description, $pid);
}
}
else {
db_query('INSERT INTO {patterns} (name, status, file, updated, enabled, title, description, pattern) VALUES ( "%s", 0, "%s", "%s", 0, "%s", "%s", "%s")', $name, $path, time(), $title, $description, serialize($pattern));
}
}
function patterns_get_pattern($id) {
if (is_numeric($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE pid = "%d"', $id));
}
else if (is_string($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE name = "%s"', $id));
}
if (!$pattern) return FALSE;
// Get the actual data. Data is stored in serialized form in the db.
$pattern->pattern = unserialize($pattern->pattern);
return $pattern;
}
/**
* Check if pattern array contains only allowed keys
*
* @param $pattern
* pattern array obtained by parsing pattern file
* @return
* TRUE when only allowed array keys are found, FALSE otherwise
*
* @todo expand this function to include much more detailed validation
*/
function patterns_validate_pattern($pattern) {
if (empty($pattern)) {
return FALSE;
}
$allowed_keys = array('info', 'modules', 'actions');
$diff = array_diff(array_keys($pattern), $allowed_keys);
return empty($diff) ? TRUE : FALSE;
}
/**
* Return file extensions supported by patterns module
*
* @return array of supported file types
*
* @todo convert this into pluggable system
*/
function patterns_file_types() {
$result = array('xml', 'php');
if (file_exists(drupal_get_path('module', 'patterns') .'/spyc/spyc.php')) {
$result[] = 'yaml';
}
return $result;
}
function patterns_load_yaml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
include_once 'spyc/spyc.php';
$pattern = Spyc::YAMLLoad($path);
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
function patterns_load_string_yaml($source) {
// loading yaml from source doesn't preserve line breaks
// so we need to save it as a file first
$path = file_directory_temp() .'/import.yaml';
file_save_data($source, $path, FILE_EXISTS_REPLACE);
$pattern = patterns_load_yaml($path);
unlink($path);
return $pattern;
}
function patterns_load_xml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
if (!$xml = file_get_contents($path)) {
return FALSE;
}
return patterns_load_string_xml($xml);
}
function patterns_load_string_xml($source) {
$pattern = patterns_from_source($source);
if (empty($pattern) || $pattern['tag'] != 'pattern') {
return FALSE;
}
// Rearrange the data in a nice way for each component.
// Make sure actions are processed differently so order is preserved.
$pattern = patterns_rearrange_data($pattern);
foreach($pattern as $key => $values) {
$pattern[$values['tag']] = $values;
unset($pattern[$values['tag']]['tag']);
unset($pattern[$key]);
// ensure the 'modules' array is collapsed - this is necessary to do if,
// for example, we're including multiple sub-patterns which each include
// their own list of modules
if ('modules' == $values['tag']) {
if (isset($values['module'])) {
if (is_array($values['module'])) {
$pattern['modules'] = $values['module'];
} else {
$pattern['modules'] = array($values['module']);
}
}
}
}
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
/**
* Read and evaluate a php file to return a 'pattern'
*/
function patterns_load_php($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
$pattern = array();
@include($path);
// That should have declared a 'pattern' into current scope.
if (!patterns_validate_pattern($pattern)) {
trigger_error("Failed to evaluate a useful pattern from the input file $path. Pattern did not validate. May have been invalid syntax. ", E_USER_WARNING);
return FALSE;
}
return $pattern;
}
/**
* Create a pattern from an XML data source
*/
function patterns_from_source($xml) {
$parse = drupal_xml_parser_create($xml);
if (!xml_parse_into_struct($parse, $xml, $vals, $index)) {
return false;
}
// Create a multi-dimensional array representing the XML structure
$pattern = current(_patterns_parse_tag($vals));
return $pattern;
}
/**
* Recurse through the values of a parsed xml file to create a
* multi-dimensional representation of the data.
*/
function _patterns_parse_tag($data, &$index = 0) {
$pattern = array();
while (isset($data[$index]) && ($current = $data[$index])) {
$type = $current['type'];
if (isset($current['attributes'])) {
foreach((array)$current['attributes'] as $key => $value) {
$current[strtolower($key)] = $value;
}
}
$current['tag'] = strtolower($current['tag']);
unset($current['type'], $current['level'], $current['attributes']);
if (isset($current['value']) && !trim($current['value']) && $current['value'] != "0") {
unset($current['value']);
}
switch($type) {
case 'open':
$index++;
$current += _patterns_parse_tag($data, $index);
$pattern[] = $current;
break;
case 'close':
$index++;
return $pattern;
break;
case 'complete':
// In order to support more complex/non-standard features we can use serialized data
if (isset($current['attributes']) && $current['attributes']['serialized']) {
$value = unserialize($current['value']);
if (isset($value)) {
$current['value'] = $value;
}
}
// If no value was specified, make sure an empty value is there
if (!isset($current['value'])) {
$current['value'] = '';
}
$pattern[] = $current;
break;
}
$index++;
}
return $pattern;
}
// function patterns_disable_pattern($pid) {
// $form['pid'] = array(
// '#type' => 'value',
// '#value' => $pid
// );
//
// $pattern = patterns_get_pattern($pid);
//
// return confirm_form($form, t('Proceed with disabling pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', '');
// }
function patterns_enable_pattern(&$form_state, $pid) {
$form['pid'] = array(
'#type' => 'value',
'#value' => $pid
);
$options = array(
'first-update' => t('only if disabled or if updated since last run (recommended)'),
'always' => t('always'),
'update' => t('only if updated since last run'),
'first' => t('only if disabled'),
'never' => t("don't run sub-patterns at all"),
);
$form['run-subpatterns'] = array(
'#type' => 'radios',
'#title' => t('Run sub-patterns:'),
'#description' => t("Decide when to run sub-patterns that are called by the currently run pattern. If unsure, stick to recommended setting. Note that your choice won't have any effect if your pattern doesn't contain sub-patterns or if this setting has been defined within the pattern file itself."),
'#options' => $options,
'#default_value' => 'first-update',
);
$disclaimer = t('Please be sure to backup your site before running a pattern. Patterns are not guaranteed to be reversable in case they do not execute well or if unforseen side effects occur.');
$pattern = patterns_get_pattern($pid);
return confirm_form($form, t('Proceed with running pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', $disclaimer);
}
// function patterns_disable_pattern_submit($form_id, $form_values) {
// $pid = $form_values['pid'];
// $pattern = patterns_get_pattern($pid);
//
// if (patterns_execute_pattern($pattern, true, true)) {
// return 'admin/build/patterns';
// }
// }
function patterns_enable_pattern_submit($form, &$form_state) {
$pid = $form_state['values']['pid'];
patterns_load_components();
$pattern = patterns_get_pattern($pid);
patterns_execute_pattern($pattern, $form_state['values']);
$form_state['redirect'] = 'admin/build/patterns';
}
/**
* Execute default configuration for module during the module installation
*
* This function should be called by other modules from
* within their hook_enable() implementation.
* Module should also provide modulename.config file containing PHP array
* with the actions that need to be executed.
*
* @param $module
* name of the module calling the function
*/
function patterns_execute_config($module) {
// since this function is called from hook_enable(), we need to ensure that
// it's executed only at module installation (first time module is enabled)
if (drupal_get_installed_schema_version($module) == SCHEMA_INSTALLED) return;
$path = drupal_get_path('module', $module) .'/'. $module .'.config';
if (file_exists($path)) {
include_once($path);
if (empty($actions)) return;
$pattern = new stdClass();
$pattern->title = t('Default configuration for @module module', array('@module' => $module));
$pattern->status = false;
$pattern->pattern['actions'] = $actions;
patterns_execute_pattern($pattern);
}
}
function patterns_execute_pattern($pattern, $params = array(), $mode = 'batch') {
$args = array($pattern, $params);
$function = 'patterns_execute_pattern_'. $mode;
if (!function_exists($function) || !is_object($pattern)) return FALSE;
return call_user_func_array($function, $args);
}
function patterns_execute_pattern_batch($pattern, $params = array()) {
$ret = _patterns_execute_pattern_intermediate_steps($pattern, $params);
if (!$ret)
return FALSE;
list ($pattern_details, $actions, $actions_map) = $ret;
$batch = array(
'title' => t('Processing pattern %pattern', array('%pattern' => $info['title'])),
'progress_message' => t('Running action @current out of @total'),
'operations' => array(),
'finished' => 'patterns_batch_finish'
);
for($i=0;$i<count($actions);$i++) {
$batch['operations'][] = array('patterns_batch_actions', array($actions[$i], $i, $actions_map));
}
batch_set($batch);
return TRUE;
}
/**
* Execute a pattern immediately without using the batch API.
* @return TRUE if pattern succeeds; FALSE otherwise.
*/
function patterns_execute_pattern_immediate($pattern, $params = array()) {
$ret = _patterns_execute_pattern_intermediate_steps($pattern, $params);
if (!$ret)
return FALSE;
list ($pattern_details, $actions, $actions_map) = $ret;
$finished = 1;
$task_message = '';
$context = array(
'sandbox' => array(),
'results' => array('abort' => FALSE, 'error_message' => '', 'identifiers' => array()),
'finished' => &$finished,
'message' => &$task_message
);
// execute actions
for($i=0;$i<count($actions) && !$context['results']['abort'];$i++) {
patterns_batch_actions($actions[$i],$i,$actions_map,$context);
}
$success = !$context['results']['abort'];
patterns_batch_finish($success, $context['results'], $actions);
return $success;
}
/**
* Helper to patterns_execute_pattern_batch() and patterns_execute_pattern_immediate().
*/
function _patterns_execute_pattern_intermediate_steps(&$pattern, &$params = array()) {
set_time_limit(0);
|
hiddentao/patterns2
|
f5a92c45403ab6b8409cb914ed8b4c0eece832d4
|
Added a Nat-NG pattern component (http://drupal.org/project/nat_ng).
|
diff --git a/components/nat_ng.inc b/components/nat_ng.inc
new file mode 100644
index 0000000..a139e23
--- /dev/null
+++ b/components/nat_ng.inc
@@ -0,0 +1,150 @@
+<?php
+/**
+ * Component for updating Nat-NG configuration.
+ *
+ * Tested with Nat-NG 6.x-1.3
+ *
+ * @author Ramesh Nair (hiddentao)
+ */
+
+
+function nat_ng_patterns($op, $id = null, &$data = null) {
+ switch($op) {
+ // Return the valid tags that this component can prepare and process
+ case 'tags':
+ return array('nat_ng');
+ break;
+
+ // Return a list of forms/actions this component can handle
+ case 'actions':
+ return array(
+ 'nat_ng_settings_form' => t('Configure Nat-NG for a node type'),
+ );
+ break;
+
+ // Return a summary of an action
+ case 'summary':
+ if ('nat_ng_settings_form' == $id && isset($data['type'])) {
+ return t('Configuring NAT-ng for node type: %name', array('%name' => $data['type']));
+ }
+ break;
+
+ // Prepare data for processing
+ case 'prepare':
+
+ if (isset($data['vocabs']) && isset($data['vocabs']['vocab'])) {
+ $data['vocabs'] = array($data['vocabs']['vocab']);
+ }
+
+ break;
+
+ // Pre validate actions
+ case 'pre-validate':
+ if (!module_exists('nat_ng')) {
+ return t('Nat-NG module must be enabled.');
+ }
+ if (!isset($data['type'])) {
+ return t('You must specify a node "type" to configure.');
+ }
+ break;
+
+ // Return the form_id('s) for each action
+ case 'form_id':
+ return 'nat_ng_settings_form';
+
+ break;
+
+ // Prepare for valid processing of this type of component
+ case 'build':
+ if ('nat_ng_settings_form' == $id) {
+
+ module_load_include('inc','nat_ng','nat_ng.admin');
+
+ // node type
+ $types = node_get_types('types');
+ $type_internal_name = '';
+ foreach ($types as $type => $info) {
+ if ($info->name == $data['type']) {
+ $type_internal_name = $type;
+ break;
+ } else if ($type == $data['type']) {
+ $type_internal_name = $type;
+ break;
+ }
+ }
+ unset($data['type']);
+
+ // set vocab ids
+ if (isset($data['vocabs']) && !empty($data['vocabs'])) {
+ // construct vocabs array (name => vocab id)
+ $all_vocabs = taxonomy_get_vocabularies();
+ $fn = create_function('$info','return $info->name;');
+ $all_vocabs = array_flip(array_map($fn,$all_vocabs));
+
+ // save selected vocab ids to form data
+ $data['types'][$type_internal_name] = array_values(array_intersect_key($all_vocabs,array_flip($data['vocabs'])));
+ }
+ unset($data['vocabs']);
+
+ // additional config
+ $flags = array(
+ 'associate-node-body-with-term-description' => 'body',
+ 'delete-node-if-term-deleted' => 'delete',
+ 'delete-natng-node-if-natng-term-deleted' => 'delete_node',
+ 'allow-users-to-define-synonyms' => 'related',
+ 'natng-term-in-node-view-points-to-node' => 'node_links',
+ );
+ foreach ($flags as $f => $k) {
+ $data[$k][$type_internal_name] = isset($data[$f]) && 1 == $data[$f] ? 1 : 0;
+ unset($data[$f]);
+ }
+
+ }
+
+ return $data;
+ break;
+
+ // Validate the values for an action before running the pattern
+ //
+ // Check here rather than in pre-validate in case we're adding
+ // roles or filters in the same pattern.
+ //
+ case 'validate':
+
+ // check node type
+ $types = node_get_types('types');
+ $found = FALSE;
+ foreach ($types as $type => $info) {
+ if ($type == $data['type'] || $info->name == $data['type']) {
+ $found = TRUE;
+ break;
+ }
+ }
+ if (!$found) {
+ return t('Invalid node type: %type', array('%type' => $data['type']));
+ }
+
+ // check vocab names
+ if (isset($data['vocabs']) && !empty($data['vocabs'])) {
+ $all_vocabs = taxonomy_get_vocabularies();
+ $fn = create_function('$info','return $info->name;');
+ $all_vocab_names = array_flip(array_map($fn, $all_vocabs));
+ $found = array();
+ foreach ($data['vocabs'] as $vocab) {
+ if (!isset($all_vocab_names[$vocab]))
+ $found[] = $vocab;
+ }
+ if (!empty($found))
+ return t('Invalid vocab names: %names', array('%names' => implode(', ',$found)));
+ }
+
+ break;
+
+ // Build a patterns actions and parameters
+ case 'params':
+ return array();
+ break;
+
+ }
+}
+
|
hiddentao/patterns2
|
407c190e3f924c9c37ff5dd13e73b0a2c918c881
|
Added the ability to execute a pattern programmatically without using the batch API. This allow for patterns to be run from within hook_update() implementations, which themselves use the batch API.
|
diff --git a/patterns.module b/patterns.module
index 1025a3f..55907fe 100644
--- a/patterns.module
+++ b/patterns.module
@@ -880,1098 +880,1147 @@ function patterns_edit_submit($form, &$form_state) {
*/
function patterns_modules_page($pid) {
$pattern = patterns_get_pattern($pid);
drupal_set_title($pattern->title .' '. t('(Pattern Modules)'));
$modules = isset($pattern->pattern['modules']) ? $pattern->pattern['modules'] : array();
$modules_info = module_rebuild_cache();
$modules_list = module_list();
// Get module name, whether its to be disabled or enabled,
// whether the module is available or not, and whether it is
// currently enabled or not
foreach($modules as $module) {
$row = array();
$delete = is_array($module) ? $module['delete'] : false;
$module = is_array($module) ? $module['value'] : $module;
$available = array_key_exists($module, $modules_info);
$enabled = array_key_exists($module, $modules_list);
$row[] = $module;
$row[] = $available ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $enabled ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $delete ? t('Delete') : t('Enable');
$rows[] = $row;
if (!$available) {
$not_available = true;
}
}
if ($not_available) {
drupal_set_message(t('Some modules are not availalble, please download them before running this pattern.'), 'error');
}
else {
drupal_set_message(t('All modules required by this module are available. Click !here to run this pattern.', array('!here' => l(t('here'), 'admin/build/patterns/enable/'. $pid))));
}
return theme('table', array(t('Name'), t('Available'), t('Enabled'), t('Pattern Action')), $rows, t('Modules used for this pattern'));
}
function patterns_load_components() {
static $loaded = false;
if ($loaded) {
return;
}
require_once drupal_get_path('module', 'patterns') .'/patterns.inc';
// Get a list of directories to search
$paths = module_invoke_all('patterns_directory');
foreach($paths as $path) {
foreach(file_scan_directory($path .'/components', '.\.inc$') as $file) {
include_once $file->filename;
}
}
$loaded = true;
}
function patterns_get_patterns($reset = true) {
patterns_load_components();
if ($reset || !variable_get('patterns_loaded', false)) {
// Get a listing of enabled patterns
$enabled = array();
$result = db_query('SELECT file FROM {patterns} WHERE status = 1');
while ($pattern = db_fetch_object($result)) {
$enabled[] = $result->file;
}
$priority = array();
$errors = array();
// Get list of directories to scan for patterns
$patterns_paths = patterns_paths();
// get valid file extensions
$mask = '.\.('. implode('|', patterns_file_types()) .')$';
// prepare list of files/folders to be excluded
// 'enabled' - Don't save enabled pattern backups
$no_mask = array('.', '..', 'CVS', '.svn', 'enabled');
foreach ($patterns_paths as $path) {
foreach(file_scan_directory($path, $mask, $no_mask) as $file) {
// Can't update existing patterns that are enabled
if (in_array($file->filename, $enabled) || in_array($file->name, $priority)) {
continue;
}
$priority[] = $file->name;
// choose appropriate function based on the file extension
$func = 'patterns_load_'. substr($file->basename, strlen($file->name) + 1);
// Load and save pattern
if ($pattern = $func($file->filename)) {
patterns_save_pattern($pattern, $file->filename, $file->name);
}
else {
$errors[] = $file->filename;
}
}
}
variable_set('patterns_loaded', time());
}
$result = db_query('SELECT * FROM {patterns}');
$messages = array();
while ($pattern = db_fetch_object($result)) {
// skip pattern if its file is missing
if (!is_file($pattern->file)) continue;
// skip pattern if loading failed and report that to the user
if (in_array($pattern->file, $errors)) {
$messages[] = t("Pattern couldn't be loaded from the file '%file'", array('%file' => $pattern->file));
continue;
}
$patterns[$pattern->pid] = $pattern;
$data = unserialize($pattern->pattern);
$patterns[$pattern->pid]->pattern = $data;
$patterns[$pattern->pid]->info = $data['info'];
}
if (!empty($messages)) {
drupal_set_message(implode('<br>', $messages) .'<br>'. t('Make sure that above file(s) are readable and contain valid data.'), 'error');
}
return $patterns;
}
/**
* return a list of paths that will be scanned for patterns
*/
function patterns_paths() {
global $profile;
if (!isset($profile)) {
$profile = variable_get('install_profile', 'default');
}
// array of all the paths where we should look for patterns
$patterns_paths = array(
conf_path() .'/patterns',
'profiles/'. $profile .'/patterns',
'sites/all/patterns'
);
// allow any module to include patterns too
foreach(module_invoke_all('patterns_directory') as $path) {
if (is_dir($path)) {
$patterns_paths[] = $path .'/patterns';
}
}
// also prepend files folder if it's valid
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (file_check_directory($path)) {
array_unshift($patterns_paths, $path);
}
return $patterns_paths;
}
/**
* Implementation of hook_patterns_directory()
*
* Let us know about where the pattern files are at
*/
function patterns_patterns_directory() {
return drupal_get_path('module', 'patterns');
}
function patterns_save_pattern($pattern, $path = '', $name = '') {
$title = $pattern['info']['title'];
$description = $pattern['info']['description'];
$author = $pattern['info']['author'];
if ($pid = db_result(db_query('SELECT pid FROM {patterns} WHERE name = "%s"', $name))) {
$updated = db_result(db_query('SELECT updated FROM {patterns} WHERE pid = "%d"', $pid));
if (($new_updated = filemtime($path)) > $updated) {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", updated = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $new_updated, $description, $pid);
}
else {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $description, $pid);
}
}
else {
db_query('INSERT INTO {patterns} (name, status, file, updated, enabled, title, description, pattern) VALUES ( "%s", 0, "%s", "%s", 0, "%s", "%s", "%s")', $name, $path, time(), $title, $description, serialize($pattern));
}
}
function patterns_get_pattern($id) {
if (is_numeric($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE pid = "%d"', $id));
}
else if (is_string($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE name = "%s"', $id));
}
if (!$pattern) return FALSE;
// Get the actual data. Data is stored in serialized form in the db.
$pattern->pattern = unserialize($pattern->pattern);
return $pattern;
}
/**
* Check if pattern array contains only allowed keys
*
* @param $pattern
* pattern array obtained by parsing pattern file
* @return
* TRUE when only allowed array keys are found, FALSE otherwise
*
* @todo expand this function to include much more detailed validation
*/
function patterns_validate_pattern($pattern) {
if (empty($pattern)) {
return FALSE;
}
$allowed_keys = array('info', 'modules', 'actions');
$diff = array_diff(array_keys($pattern), $allowed_keys);
return empty($diff) ? TRUE : FALSE;
}
/**
* Return file extensions supported by patterns module
*
* @return array of supported file types
*
* @todo convert this into pluggable system
*/
function patterns_file_types() {
$result = array('xml', 'php');
if (file_exists(drupal_get_path('module', 'patterns') .'/spyc/spyc.php')) {
$result[] = 'yaml';
}
return $result;
}
function patterns_load_yaml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
include_once 'spyc/spyc.php';
$pattern = Spyc::YAMLLoad($path);
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
function patterns_load_string_yaml($source) {
// loading yaml from source doesn't preserve line breaks
// so we need to save it as a file first
$path = file_directory_temp() .'/import.yaml';
file_save_data($source, $path, FILE_EXISTS_REPLACE);
$pattern = patterns_load_yaml($path);
unlink($path);
return $pattern;
}
function patterns_load_xml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
if (!$xml = file_get_contents($path)) {
return FALSE;
}
return patterns_load_string_xml($xml);
}
function patterns_load_string_xml($source) {
$pattern = patterns_from_source($source);
if (empty($pattern) || $pattern['tag'] != 'pattern') {
return FALSE;
}
// Rearrange the data in a nice way for each component.
// Make sure actions are processed differently so order is preserved.
$pattern = patterns_rearrange_data($pattern);
foreach($pattern as $key => $values) {
$pattern[$values['tag']] = $values;
unset($pattern[$values['tag']]['tag']);
unset($pattern[$key]);
// ensure the 'modules' array is collapsed - this is necessary to do if,
// for example, we're including multiple sub-patterns which each include
// their own list of modules
if ('modules' == $values['tag']) {
if (isset($values['module'])) {
if (is_array($values['module'])) {
$pattern['modules'] = $values['module'];
} else {
$pattern['modules'] = array($values['module']);
}
}
}
}
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
/**
* Read and evaluate a php file to return a 'pattern'
*/
function patterns_load_php($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
$pattern = array();
@include($path);
// That should have declared a 'pattern' into current scope.
if (!patterns_validate_pattern($pattern)) {
trigger_error("Failed to evaluate a useful pattern from the input file $path. Pattern did not validate. May have been invalid syntax. ", E_USER_WARNING);
return FALSE;
}
return $pattern;
}
/**
* Create a pattern from an XML data source
*/
function patterns_from_source($xml) {
$parse = drupal_xml_parser_create($xml);
if (!xml_parse_into_struct($parse, $xml, $vals, $index)) {
return false;
}
// Create a multi-dimensional array representing the XML structure
$pattern = current(_patterns_parse_tag($vals));
return $pattern;
}
/**
* Recurse through the values of a parsed xml file to create a
* multi-dimensional representation of the data.
*/
function _patterns_parse_tag($data, &$index = 0) {
$pattern = array();
while (isset($data[$index]) && ($current = $data[$index])) {
$type = $current['type'];
if (isset($current['attributes'])) {
foreach((array)$current['attributes'] as $key => $value) {
$current[strtolower($key)] = $value;
}
}
$current['tag'] = strtolower($current['tag']);
unset($current['type'], $current['level'], $current['attributes']);
if (isset($current['value']) && !trim($current['value']) && $current['value'] != "0") {
unset($current['value']);
}
switch($type) {
case 'open':
$index++;
$current += _patterns_parse_tag($data, $index);
$pattern[] = $current;
break;
case 'close':
$index++;
return $pattern;
break;
case 'complete':
// In order to support more complex/non-standard features we can use serialized data
if (isset($current['attributes']) && $current['attributes']['serialized']) {
$value = unserialize($current['value']);
if (isset($value)) {
$current['value'] = $value;
}
}
// If no value was specified, make sure an empty value is there
if (!isset($current['value'])) {
$current['value'] = '';
}
$pattern[] = $current;
break;
}
$index++;
}
return $pattern;
}
// function patterns_disable_pattern($pid) {
// $form['pid'] = array(
// '#type' => 'value',
// '#value' => $pid
// );
//
// $pattern = patterns_get_pattern($pid);
//
// return confirm_form($form, t('Proceed with disabling pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', '');
// }
function patterns_enable_pattern(&$form_state, $pid) {
$form['pid'] = array(
'#type' => 'value',
'#value' => $pid
);
$options = array(
'first-update' => t('only if disabled or if updated since last run (recommended)'),
'always' => t('always'),
'update' => t('only if updated since last run'),
'first' => t('only if disabled'),
'never' => t("don't run sub-patterns at all"),
);
$form['run-subpatterns'] = array(
'#type' => 'radios',
'#title' => t('Run sub-patterns:'),
'#description' => t("Decide when to run sub-patterns that are called by the currently run pattern. If unsure, stick to recommended setting. Note that your choice won't have any effect if your pattern doesn't contain sub-patterns or if this setting has been defined within the pattern file itself."),
'#options' => $options,
'#default_value' => 'first-update',
);
$disclaimer = t('Please be sure to backup your site before running a pattern. Patterns are not guaranteed to be reversable in case they do not execute well or if unforseen side effects occur.');
$pattern = patterns_get_pattern($pid);
return confirm_form($form, t('Proceed with running pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', $disclaimer);
}
// function patterns_disable_pattern_submit($form_id, $form_values) {
// $pid = $form_values['pid'];
// $pattern = patterns_get_pattern($pid);
//
// if (patterns_execute_pattern($pattern, true, true)) {
// return 'admin/build/patterns';
// }
// }
function patterns_enable_pattern_submit($form, &$form_state) {
$pid = $form_state['values']['pid'];
patterns_load_components();
$pattern = patterns_get_pattern($pid);
patterns_execute_pattern($pattern, $form_state['values']);
$form_state['redirect'] = 'admin/build/patterns';
}
/**
* Execute default configuration for module during the module installation
*
* This function should be called by other modules from
* within their hook_enable() implementation.
* Module should also provide modulename.config file containing PHP array
* with the actions that need to be executed.
*
* @param $module
* name of the module calling the function
*/
function patterns_execute_config($module) {
// since this function is called from hook_enable(), we need to ensure that
// it's executed only at module installation (first time module is enabled)
if (drupal_get_installed_schema_version($module) == SCHEMA_INSTALLED) return;
$path = drupal_get_path('module', $module) .'/'. $module .'.config';
if (file_exists($path)) {
include_once($path);
if (empty($actions)) return;
$pattern = new stdClass();
$pattern->title = t('Default configuration for @module module', array('@module' => $module));
$pattern->status = false;
$pattern->pattern['actions'] = $actions;
patterns_execute_pattern($pattern);
}
}
function patterns_execute_pattern($pattern, $params = array(), $mode = 'batch') {
- patterns_processing_config_reset();
-
$args = array($pattern, $params);
$function = 'patterns_execute_pattern_'. $mode;
if (!function_exists($function) || !is_object($pattern)) return FALSE;
return call_user_func_array($function, $args);
}
function patterns_execute_pattern_batch($pattern, $params = array()) {
- set_time_limit(0);
+ $ret = _patterns_execute_pattern_intermediate_steps($pattern, $params);
+ if (!$ret)
+ return FALSE;
+ list ($pattern_details, $actions, $actions_map) = $ret;
+
+
+ $batch = array(
+ 'title' => t('Processing pattern %pattern', array('%pattern' => $info['title'])),
+ 'progress_message' => t('Running action @current out of @total'),
+ 'operations' => array(),
+ 'finished' => 'patterns_batch_finish'
+ );
+
+ for($i=0;$i<count($actions);$i++) {
+ $batch['operations'][] = array('patterns_batch_actions', array($actions[$i], $i, $actions_map));
+ }
+ batch_set($batch);
+ return TRUE;
+}
+
+
+/**
+ * Execute a pattern immediately without using the batch API.
+ * @return TRUE if pattern succeeds; FALSE otherwise.
+ */
+function patterns_execute_pattern_immediate($pattern, $params = array()) {
+
+ $ret = _patterns_execute_pattern_intermediate_steps($pattern, $params);
+ if (!$ret)
+ return FALSE;
+ list ($pattern_details, $actions, $actions_map) = $ret;
+
+ $finished = 1;
+ $task_message = '';
+ $context = array(
+ 'sandbox' => array(),
+ 'results' => array('abort' => FALSE, 'error_message' => '', 'identifiers' => array()),
+ 'finished' => &$finished,
+ 'message' => &$task_message
+ );
+
+ // execute actions
+ for($i=0;$i<count($actions) && !$context['results']['abort'];$i++) {
+ patterns_batch_actions($actions[$i],$i,$actions_map,$context);
+ }
+
+ $success = !$context['results']['abort'];
+
+ patterns_batch_finish($success, $context['results'], $actions);
+
+ return $success;
+}
+
+
+/**
+ * Helper to patterns_execute_pattern_batch() and patterns_execute_pattern_immediate().
+ */
+function _patterns_execute_pattern_intermediate_steps(&$pattern, &$params = array()) {
+
+ set_time_limit(0);
+
+ patterns_processing_config_reset();
+
+ unset($_SESSION['patterns_batch_info']);
+
if (!is_object($pattern)) {
$pattern = patterns_get_pattern($pattern);
if (!$pattern) {
return FALSE;
}
}
$pattern->subpatterns_run_mode = isset($params['run-subpatterns']) ? $params['run-subpatterns'] : FALSE;
$pattern_details = patterns_get_pattern_details($pattern, TRUE);
$modules = $pattern_details['modules'];
$actions = $pattern_details['actions'];
$actions_map = array('patterns' => $pattern_details['info'], 'map' => $pattern_details['actions_map']);
$info = reset($pattern_details['info']);
// If there are no actions or modules, most likely the pattern
// was not created correctly.
if (empty($actions) && empty($modules)) {
drupal_set_message(t('Could not recognize pattern %title, aborting.', array('%title' => $info['title'])), 'error');
return FALSE;
}
$result = patterns_install_modules($modules);
if (!$result['success']) {
drupal_set_message($result['error_message'], 'error');
return FALSE;
}
// lets clear the caches here to ensure that newly added modules
// and future pattern actions work as expected.
module_load_include('inc', 'system', 'system.admin');
$form = $form_state = array();
system_clear_cache_submit($form, $form_state);
-
$result = patterns_prepare_actions($actions, $actions_map);
if (!$result['success']) {
drupal_set_message($result['error_message'], 'error');
return FALSE;
}
-
- $batch = array(
- 'title' => t('Processing pattern %pattern', array('%pattern' => $info['title'])),
-// 'init_message' => t('Running action @current out of @total', array('@current' => 1, '@total' => count($actions))),
- 'progress_message' => t('Running action @current out of @total'),
- 'operations' => array(),
- 'finished' => 'patterns_batch_finish'
- );
-
- for($i=0;$i<count($actions);$i++) {
- $batch['operations'][] = array('patterns_batch_actions', array($actions[$i], $i, $actions_map));
- }
-
+
$_SESSION['patterns_batch_info'] = $pattern_details['info'];
-
- batch_set($batch);
- return TRUE;
+
+ return array($pattern_details, $actions, $actions_map);
}
+
function patterns_install_modules(&$modules) {
$result = array('success' => TRUE);
if (empty($modules)) return $result;
$missing = patterns_check_module_dependencies($modules, TRUE);
if (!empty($missing)) {
$result['success'] = FALSE;
$result['error_message'] = t('Following required modules are missing: %modules', array('%modules' => implode(', ', $missing)));
$result['missing_modules'] = $missing;
return $result;
}
require_once './includes/install.inc';
drupal_install_modules($modules);
module_rebuild_cache();
$result['installed_modules'] = $modules;
return $result;
}
function patterns_locate_action($key, $actions_map) {
$result['key'] = $actions_map['map'][$key]['index'];
$result['title'] = $actions_map['patterns'][$actions_map['map'][$key]['pid']]['title'];
$result['file'] = $actions_map['patterns'][$actions_map['map'][$key]['pid']]['file'];
return $result;
}
function patterns_prepare_actions(&$actions, $actions_map) {
$result = array('success' => TRUE);
if (empty($actions)) return $result;
patterns_load_components();
// Keep a list of what modules handle what tags
$tag_modules = patterns_invoke($empty, 'tag modules');
// TODO Finish basic setup and execution of the 'config' operation
// TODO Make a better streamlined config framework process. For instance collect form_ids
// from here and give the form_id and matching data to the 'build' process
foreach($actions as $key => &$data) {
if (($config = patterns_invoke($actions[$key], 'config')) && !empty($config)) {
patterns_config_data($data, $config);
}
}
// Prepare actions for validation/processing
foreach($actions as $key => &$data) {
patterns_invoke($actions[$key], 'prepare');
}
$errors = array();
// Pre validate tags with their appropriate components
foreach($actions as $key => &$data) {
$action_location = patterns_locate_action($key, $actions_map);
$index = $action_location['key'];
$pattern_title = $action_location['title'];
// $pattern_file = $action_location['file'];
if (!array_key_exists($data['tag'], $tag_modules)) {
$errors[] = t('Action #%num (%tag) in pattern %title: <%tag> is not a valid tag', array('%num' => $index+1, '%tag' => $data['tag'], '%title' => $pattern_title));
}
else {
$error = patterns_invoke($actions[$key], 'pre-validate');
if ($error) {
$errors[] = t('Action #%num (%tag) in pattern %title: !msg', array('!msg' => $error, '%num' => $index+1, '%tag' => $data['tag'], '%title' => $pattern_title));
}
}
}
if (count($errors)) {
$message = t('Errors encountered during pre-processing:') .'<br>'. implode('<br>', $errors);
$result['success'] = FALSE;
$result['error_message'] = $message;
}
return $result;
}
/**
* Execute a batch action
*/
function patterns_batch_actions($action, $place, $actions_map, &$context) {
patterns_load_components();
// Nothing to do if there is no action
if (empty($action)) {
$context['finished'] = 1;
return;
}
// Start a timer. Since we want each action to be its own http request, we need
// to ensure the batch api will decide to do it like that by making each action
// take at least a second to execute
timer_start('patterns_action');
// skip action execution if an error is encountered in some of the previous operations
if (!empty($context['results']['abort'])) return;
$result = patterns_implement_action($action, $context['results']['identifiers'], $place, $actions_map);
if (!$result['success']) {
if (!isset($_SESSION[PATTERNS_IGNORE_FAILED_ACTIONS])) {
// we use 'results' to keep track of errors and abort execution if required
$context['results']['error_message'] .= $result['error_message'];
$context['results']['abort'] = TRUE;
} else {
drupal_set_message('ERROR: ' . $result['error_message'], 'warning');
}
}
if (timer_read('patterns_action') < 1000) {
@usleep(1000 - timer_read('patterns_action'));
}
}
/**
* Finish a batch operation
*/
function patterns_batch_finish($success, $results, $operations) {
patterns_processing_config_reset();
$info = $_SESSION['patterns_batch_info'];
if (!isset($results['abort']) || !($results['abort'])) {
foreach ($info as $key => $i) {
drupal_set_message(t('Pattern "@pattern" ran successfully.', array('@pattern' => $i['title'])));
db_query('UPDATE {patterns} SET status = 1, enabled = "%s" WHERE pid = %d', time(), $key);
}
}
else {
$pattern = reset($info);
drupal_set_message(t('Pattern "@pattern" ran with the errors. Check the error messages to get more details.', array('@pattern' => $pattern['title'])));
drupal_set_message($results['error_message'], 'error');
}
unset($_SESSION['patterns_batch_info']);
drupal_flush_all_caches();
}
/**
* Setup and run an action
*/
function patterns_implement_action($action, &$identifiers, $place = 0, $actions_map = NULL) {
patterns_set_error_handler();
$result = array('success' => TRUE);
// Prepare actions for processing, ensure smooth pattern executions, and return form ids for execution
$return = patterns_invoke($action, 'form_id');
// If prepare removed the data, dont continue with this action
if (!$action || !$return) {
return $result;
}
if (is_string($return)) {
$form_ids = array($return);
}
else if ($return) {
$form_ids = $return;
}
$action_descriptions = patterns_invoke($action, 'actions');
$action_location = patterns_locate_action($place, $actions_map);
$index = $action_location['key'] + 1;
$pattern_title = $action_location['title'];
$pattern_file = $action_location['file'];
// Build the action
foreach($form_ids as $form_id) {
$clone = $action;
$action_description = isset($action_descriptions[$form_id]) ? $action_descriptions[$form_id] : t('System: Execute form');
$result['action_descriptions'][$place][] = $action_description;
// If tokens are enabled, apply tokens to the action values
// before processing
if (module_exists('token')) {
_patterns_recurse_tokens($clone, $identifiers);
//array_walk($clone, '_patterns_replace_tokens', $identifiers);
}
$error = patterns_invoke($clone, 'validate', $form_id);
if ($message = patterns_error_get_last('validate', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
if ($error) {
$message = t('An error occured while validating action #%num (%action) in %title pattern', array('%num' => $index, '%action' => $action_description, '%title' => $pattern_title));
$result['error_message'] = $message .'<br>'. $error;
$result['success'] = FALSE;
return $result;
}
// Get the form data for the action. This can either just be the form values,
// or it can be the full form_state object
$form_obj = patterns_invoke($clone, 'build', $form_id);
if ($message = patterns_error_get_last('build', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
// Dont execute the action if a string was returned, indicating the pattern component
// most likely handled the action on its own and this is the message to display.
if (is_string($form_obj)) {
drupal_set_message($form_obj);
}
else {
// We check for the 'storage' and 'submitted' values in the object to see
// if it is a form_state instead of form_values. There could be a better way
// to do this.
if (array_key_exists('submitted', (array)$form_obj) && array_key_exists('storage', (array)$form_obj)) {
$action_state = $form_obj;
}
else {
$action_state = array(
'storage' => null,
'submitted' => false,
'values' => $form_obj
);
}
// Get any extra parameters required for the action
$params = patterns_invoke($clone, 'params', $form_id, $action_state);
if ($message = patterns_error_get_last('params', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
// A single, simple value can be returned as a parameter, which is then
// put into an array here.
if (isset($params) && !is_array($params)) {
$params = array($params);
}
// Execute action
patterns_execute_action($form_id, $action_state, $params);
if ($message = patterns_error_get_last('execute', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
if ($errors = form_get_errors()) {
$result['error_message'] = t('Above error(s) occured while executing action #%num (%action) in %title pattern. Error location(s) are: %errors', array('%num' => $index, '%action' => $action_description, '%title' => $pattern_title, '%errors' => str_replace('][', '->', implode(', ', array_keys($errors)))));
$result['success'] = FALSE;
return $result;
}
// Let a component cleanup after each action
patterns_invoke($clone, 'cleanup', $form_id, $action_state);
if ($message = patterns_error_get_last('cleanup', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
}
// Clear the cache in case it causes problems
cache_clear_all();
// Rebuild the menu
// TODO Should this go at the end only when a pattern successfully runs?
variable_set('menu_rebuild_needed', true);
}
// Get any primary identifiers from the action for further actions to take advantage of
$id = null;
$id = patterns_invoke($clone, 'identifier', $form_id, $action_state);
if (isset($id)) {
$index = isset($clone['action_label']) ? $clone['action_label'] : $place+1;
$identifiers[$index] = $id;
}
patterns_restore_error_handler();
return $result;
}
/**
* Execute an action
*/
function patterns_execute_action($form_id, &$form_state, $params) {
// Make sure we always have a clear cache for everything
// Beware - this direct database access needs to be db-prefix-safe!
global $db_prefix;
$result = db_query('SHOW TABLES LIKE "{cache}_%"');
while ($table = db_fetch_array($result)) {
// Remove the db prefix if any. cache_clear_all() will put it back again.
$table = substr(current($table), strlen($db_prefix));
cache_clear_all(null, $table);
}
$args = array($form_id, &$form_state);
if (is_array($params)) {
$args = array_merge($args, $params);
}
patterns_executing(true);
// If we are in batch mode, trick the form api to think
// otherwise to avoid potential problems
$batch =& batch_get();
$batch_clone = $batch;
$batch = null;
//$form = call_user_func_array('drupal_retrieve_form', $args);
//$form['#post'] = $values;
//$return = drupal_process_form($form_id, $form);
//dpm($args);
// drupal_execute fails to keep $form_state in-sync through the
// whole FAPI process. Issue http://drupal.org/node/346244
//$return = call_user_func_array('drupal_execute', $args);
// Fix some parts of the #post values based on the original form
patterns_sync_form_values($args);
// Copy of drupal_execute until above issue is fixed
$form = call_user_func_array('drupal_retrieve_form', $args);
$form['#post'] = $form_state['values'];
drupal_prepare_form($form_id, $form, $form_state);
// If you call drupal_validate_form() on the same form more
// than once per page request, validation is not performed
// on any but the first call.
// see issue: http://drupal.org/node/260934
// drupal_process_form($form_id, $form, $form_state);
// Until above issue is fixed we use our own implementation
// of drupal_process_form() and drupal_validate_form().
_patterns_process_form($form_id, $form, $form_state);
patterns_executing(false);
$batch = $batch_clone;
return $return;
}
function patterns_executing($b = null) {
static $executing = false;
if (is_bool($b)) {
$executing = $b;
}
return $executing;
}
function patterns_rearrange_data($pattern) {
foreach($pattern as $key => $value) {
if (is_string($key)) {
unset($pattern[$key]);
}
else {
if ($value['tag'] == 'actions') {
$pattern[$key] = patterns_rearrange_data($value);
$pattern[$key]['tag'] = 'actions';
}
else {
$pattern[$key] = _patterns_rearrange_data($value);
}
}
}
return $pattern;
}
/**
* Return an array with detailed information about the pattern
*/
function patterns_get_pattern_details($pattern, $recursive = FALSE, &$pids = array()) {
// prevent infinite recursion
if (in_array($pattern->pid, $pids)) return array();
$pids[$pattern->pid] = $pattern->pid;
$actions = !empty($pattern->pattern['actions']) ? $pattern->pattern['actions'] : array();
$modules = !empty($pattern->pattern['modules']) ? $pattern->pattern['modules'] : array();
$patterns[$pattern->pid] = (array)$pattern;
$patterns[$pattern->pid] = array_merge($patterns[$pattern->pid], $patterns[$pattern->pid]['pattern']['info']);
unset($patterns[$pattern->pid]['pattern']);
if ($recursive) {
$result = array('modules' => $modules, 'info' => $patterns);
foreach($actions as $key => $action) {
if ($action['tag'] == 'pattern') {
// determine pattern name
if (!empty($action['value'])) {
$name = $action['value'];
}
elseif (!empty($action['name'])) {
$name = $action['name'];
}
if (!$p = patterns_get_pattern($name)) {
// just give a warning and try to continue
drupal_set_message(t('Action #%key in %file: Pattern %pattern not found.<br>Pattern execution will try to continue without it.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'warning');
continue;
}
// Decide if sub-pattern needs to be run based on the mode defined within the pattern or selected in UI at the time of form submission
// @TODO: UI setting should be able to override a setting defined within the pattern
$modes = array('first-update', 'always', 'update', 'first', 'never');
if (!empty($action['run']) && in_array($action['run'], $modes)) {
$mode = $action['run'];
}
else {
$mode = $pattern->subpatterns_run_mode;
}
switch ($mode) {
case 'never':
// don't run sub-pattern
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to be skipped.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
break;
case 'first':
// Only run on first run
if ($p->status) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on the first run.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'update':
// Only run on pattern update
if ($p->enabled >= $p->updated) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on pattern update.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'first-update':
// Only run on first run or pattern update
if ($p->status && $p->enabled >= $p->updated) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on first run or update.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'always':
default:
// Run always
break;
}
$a = patterns_get_pattern_details($p, TRUE, $pids);
if (is_array($a) && empty($a)) {
// An empty array is returned on infinite recursion detection
drupal_set_message(t('Action #%key in %file: Infinite recursion detected while attempting to run pattern %pattern.<br>Pattern execution will try to continue without it.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'warning');
continue;
}
// array_merge doesn't preserve numeric array keys
// so we handle 'info' separately
$info = $result['info'];
$result = array_merge_recursive($result, $a);
$result['info'] = $info + $a['info'];
}
else {
$result['actions'][] = $action;
$result['actions_map'][] = array(
'pid' => $pattern->pid,
'index' => $key,
);
}
}
$result['modules'] = array_merge(array_unique($result['modules']));
// Remove pid from recursion stack
//unset($pids[$pattern->pid]);
return $result;
}
// Remove pid from recursion stack
//unset($pids[$pattern->pid]);
return array('actions' => $actions, 'modules' => $modules, 'info' => $patterns);
}
//function patterns_process_modules($modules, $op = 'enable') {
// // Enable at the beginning of the pattern. Disable at the end.
// for($i=0;$module=$modules[$i];$i++) {
// if (($op == 'enable' && $module['delete']) || ($op == 'disable' && !$module['delete'])) {
// unset($modules[$i]);
// }
// }
//
// patterns_invoke($empty, 'tag modules');
// $error = patterns_invoke($modules, 'pre-validate');
//
// // Error validating modules
// if ($error) {
// return $error;
// }
//
// patterns_invoke($modules, 'prepare');
//}
function patterns_invoke(&$data, $op, $form_id = null, &$a = null) {
|
hiddentao/patterns2
|
c06af4bf64652b8c592f542a64c9fab93fc0f09c
|
Added two new tags (to be placed inside <info>) for controlling how a pattern appears in the list on the patterns admin page...
|
diff --git a/patterns.module b/patterns.module
index 76e7da4..1025a3f 100644
--- a/patterns.module
+++ b/patterns.module
@@ -157,1043 +157,1055 @@ function patterns_menu() {
$items['admin/build/patterns/import/url'] = array(
'title' => 'Import from URL',
'page callback' => 'drupal_get_form',
'page arguments' => array('patterns_import_url'),
'access arguments' => array('administer patterns'),
'type' => MENU_LOCAL_TASK
);
$items['admin/build/patterns/server'] = array(
'title' => 'Patterns Server',
'page callback' => 'drupal_get_form',
'page arguments' => array('patterns_import_server'),
'access arguments' => array('administer patterns'),
'type' => MENU_LOCAL_TASK,
'weight' => -5
);
return $items;
}
/**
* Implementation of hook_help().
*/
function patterns_help($section, $arg = NULL) {
$output = '';
switch ($section) {
case 'admin/build/patterns':
$output = t('Patterns will be looked for in files under the following locations: ') . theme('item_list', patterns_paths());
break;
}
return $output;
}
/**
* Display the pattern settings form
*/
function patterns_settings(&$form_state) {
$form['patterns_form_helper'] = array(
'#type' => 'checkbox',
'#title' => t('Enable Patterns Form Helper'),
'#description' => t('When enabled, patterns form helper will dump $form_id and $form_state variables at the bottom of each page. Dump will always contain values from the latest form submission. This may be very helpful while writing your own patterns.'),
'#default_value' => variable_get('patterns_form_helper', FALSE),
);
$form['patterns_allow_publish'] = array(
'#type' => 'checkbox',
'#title' => t('Share your patterns'),
'#description' => t('When enabled, you will be able to "publish" selected patterns and make them available to other patterns users on the following URL: %url.', array('%url' => url(NULL, array('absolute' => TRUE)) . (variable_get('clean_url', 0) ? '' : '?q=') .'patterns.xml')),
'#default_value' => variable_get('patterns_allow_publish', FALSE),
);
// Reload patterns while we are here and ensure the lists are up to date
patterns_get_patterns(TRUE);
return system_settings_form($form);
}
/**
* Display the import pattern form
*/
function patterns_import_source(&$form_state) {
if (empty($form_state['post'])) {
drupal_set_message(t('Import feature currently supports only XML file format.'), 'warning');
}
$form['xmlname'] = array(
'#type' => 'textfield',
'#title' => t('Pattern Identifier'),
'#description' => t('Machine readable name for the pattern. The actual title should be included in the pattern itself.'),
'#required' => true
);
$form['xmlsource'] = array(
'#type' => 'textarea',
'#rows' => 15,
'#title' => t('Enter Pattern Source Code'),
'#description' => t('Imported patterns are not executed until you run them manually.')
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import')
);
$form['#validate'][] = 'patterns_import_validate';
$form['#submit'][] = 'patterns_import_submit';
return $form;
}
/**
* Menu callback - returns source code of the requested pattern
* if the pattern is public
*
* @param $pid
* pattern id
* @return
* source code of the requested pattern
*/
function patterns_get_source($pid) {
if (!is_numeric($pid)) {
exit;
}
$pattern = patterns_get_pattern($pid);
// make sure pattern is public (published)
if (!$pattern->public) {
exit;
}
$content_type = 'text/plain';
if (substr($pattern->file,-4) == '.xml') {
$content_type = 'text/xml';
}
drupal_set_header('Content-Type: '. $content_type .'; charset=utf-8');
print file_get_contents($pattern->file);
exit;
}
/**
* Prints XML Feed of published (public) patterns
*
*/
function patterns_feed() {
global $base_url;
if (!variable_get('patterns_allow_publish', FALSE)) {
return drupal_not_found();
}
$patterns = variable_get('patterns_allow_publish', FALSE) ? patterns_get_patterns() : array();
foreach ($patterns as $pattern) {
if (!$pattern->public) {
continue;
}
preg_match('/[^\.]*$/', $pattern->file, $matches);
$extension = $matches[0];
$item = " <pattern>\n";
$item .= " <pid>". $pattern->pid ."</pid>\n";
$item .= " <name>". $pattern->name . "</name>\n";
$item .= " <title>". $pattern->title . "</title>\n";
$item .= " <description>". $pattern->description . "</description>\n";
$item .= " <category>". $pattern->pattern['info']['category'] . "</category>\n";
$item .= " <file_type>". $extension . "</file_type>\n";
$item .= " </pattern>\n";
$items .= $item;
}
$header = " <info>\n";
$header .= " <url>". $base_url ."</url>\n";
// $header .= " <description>". $description ."</description>\n";
$header .= " </info>\n";
$feed = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$feed .= "<patterns_feed>\n";
$feed .= $header;
$feed .= " <patterns>\n";
$feed .= $items;
$feed .= " </patterns>\n";
$feed .= "</patterns_feed>\n";
drupal_set_header('Content-Type: text/xml; charset=utf-8');
print $feed;
exit;
}
/**
* Display the import pattern from server form
*/
function patterns_import_server(&$form_state) {
if (empty($form_state['storage'])) {
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (!file_check_directory($path, true)) {
$message = t("In order to save imported patterns, directory %path must be writable.<br />", array('%path' => $path));
$link = l(t('status report'), 'admin/reports/status');
$message .= t('You might want to check the !link to ensure your files directory exists and is writable.', array('!link' => $link));
drupal_set_message($message, 'error');
return array();
}
$form['server_url'] = array(
'#type' => 'textfield',
'#title' => t('Specify Patterns Server URL'),
'#description' => t('URL of the web site you want to import patterns from. Example: http://patterns.graviteklabs.com'),
'#default_value' => variable_get('patterns_default_server', 'http://patterns.graviteklabs.com'),
'#size' => 48
);
}
else {
$feed = $form_state['storage']['feed'];
$form['patterns'] = array(
'#type' => 'fieldset',
'#tree' => TRUE,
'#title' => t('Patterns'),
);
foreach ($feed['patterns'] as $pattern) {
$form['patterns'][$pattern['pid']] = array(
'#type' => 'checkbox',
'#title' => $pattern['title'],
'#description' => $pattern['description'],
'#disabled' => in_array($pattern['file_type'], patterns_file_types()) ? FALSE : TRUE,
);
}
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => empty($form_state['storage']) ? t('Get Patterns List') : t('Import')
);
$form['#validate'][] = 'patterns_import_server_validate';
$form['#submit'][] = 'patterns_import_server_submit';
return $form;
}
function patterns_import_server_validate($form, &$form_state) {
if (empty($form_state['storage'])) {
if (!ini_get('allow_url_fopen')) {
form_set_error('fopen', t('allow_url_fopen must be enabled in your php configuration in order to use this feature.'));
return;
}
$feed_url = $form_state['values']['server_url'] .'/patterns.xml';
if (empty($feed_url)) {
form_set_error('server_url', t('Please enter Patterns Server URL.'));
return;
}
if (!$xml = file_get_contents($feed_url)) {
form_set_error('server_url', t('Failed to retreive the patterns feed from: %url. Please check your URL and try again.', array('%url' => $form_state['values']['server_url'])));
return;
}
// @todo: replace this with proper XML validation
if (strpos($xml, '<?xml') !== 0) {
form_set_error('', t('URL %url is not a valid XML file.', array('%url' => $form_state['values']['server_url'])));
return;
}
$feed = patterns_from_source($xml);
if (!$feed) {
form_set_error('', t('URL %url is not a valid patterns feed.', array('%url' => $form_state['values']['server_url'])));
return;
}
$feed = patterns_feed_rearrange_data($feed);
if (!$feed) {
form_set_error('', t('URL %url is not a valid patterns feed.', array('%url' => $form_state['values']['server_url'])));
return;
}
$form_state['storage']['step'] = 'get url';
$form_state['storage']['server_url'] = $form_state['values']['server_url'];
$form_state['storage']['feed_url'] = $feed_url;
$form_state['storage']['feed'] = $feed;
}
else {
$form_state['storage']['step'] = 'select patterns';
}
}
function patterns_import_server_submit($form, &$form_state) {
if ($form_state['storage']['step'] == 'get url') {
return;
}
$pids = array_keys(array_filter($form_state['values']['patterns']));
$feed = $form_state['storage']['feed'];
$errors = array();
foreach ($pids as $pid) {
$url = $feed['info']['url'] .'/admin/build/patterns/get/'. $pid;
$pattern_info = $feed['patterns'][$pid];
if (!$source = file_get_contents($url)) {
$errors['get file'][] = $pattern_info;
continue;
}
// save file
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
$path .= '/'. $pattern_info['name'] .'.'. $pattern_info['file_type'];
if (!$saved = file_save_data($source, $path, FILE_EXISTS_ERROR)) {
$errors['save file'][] = $pattern_info;
continue;
}
// choose appropriate function based on the file extension
$func = 'patterns_load_'. $pattern_info['file_type'];
// Load pattern
if (!$pattern = $func($saved)) {
$errors['load pattern'][] = $pattern_info;
unlink($saved);
continue;
}
patterns_save_pattern($pattern, $saved, $pattern_info['name']);
}
if (!empty($errors)) {
$patterns = array();
foreach ($errors as $type => $files) {
foreach ($files as $file) {
$patterns[] = $file['title'] .' (cause: "'. $type .'" failed)';
}
$patterns = theme('item_list', $patterns);
}
drupal_set_message(t('Import failed for the following patterns: ') .'<br>'. $patterns, 'error');
return;
}
unset($form_state['storage']);
$form_state['redirect'] = 'admin/build/patterns';
}
function patterns_feed_rearrange_data($feed) {
unset($feed['tag']);
foreach ($feed as $key => $section) {
$tag = $section['tag'];
if ($tag == 'pattern') {
unset($section['tag']);
if (!isset($section['value'])) {
foreach ($section as $t) {
if ($t['tag'] == 'pid') {
$pid = $t['value'];
break;
}
}
$result[$pid] = patterns_feed_rearrange_data($section);
}
else {
$result[$tag] = $section['value'];
}
}
else {
unset($section['tag']);
if (!isset($section['value'])) {
$result[$tag] = patterns_feed_rearrange_data($section);
}
else {
$result[$tag] = $section['value'];
}
}
}
return $result;
}
function patterns_publish_pattern($pid) {
if (is_numeric($pid)) {
$result = db_query("UPDATE {patterns} SET public = 1 WHERE pid = %d", $pid);
}
drupal_set_message('Pattern published.');
drupal_goto('admin/build/patterns');
}
function patterns_unpublish_pattern($pid) {
if (is_numeric($pid)) {
$result = db_query("UPDATE {patterns} SET public = 0 WHERE pid = %d", $pid);
}
drupal_set_message('Pattern unpublished.');
drupal_goto('admin/build/patterns');
}
/**
* Display the import pattern file form
*/
function patterns_import_file(&$form_state) {
if (empty($form_state['post'])) {
drupal_set_message(t('Import feature currently supports only XML file format.'), 'warning');
}
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['xmlfile'] = array(
'#type' => 'file',
'#title' => t('Upload Pattern File'),
'#description' => t('Imported patterns are not executed until you run them manually.'),
'#size' => 48
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import')
);
$form['#validate'][] = 'patterns_import_validate';
$form['#submit'][] = 'patterns_import_submit';
return $form;
}
/**
* Display the import pattern url form
*/
function patterns_import_url(&$form_state) {
if (empty($form_state['post'])) {
drupal_set_message(t('Import feature currently supports only XML file format.'), 'warning');
}
$form['xmlurl'] = array(
'#type' => 'textfield',
'#title' => t('Specify an URL'),
'#description' => t('Import a pattern from a remote URL. Imported patterns are not executed until you run them manually.'),
'#size' => 48
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import')
);
$form['#validate'][] = 'patterns_import_validate';
$form['#submit'][] = 'patterns_import_submit';
return $form;
}
function patterns_import_validate($form, &$form_state) {
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (!file_check_directory($path, true)) {
$message = t("Destination folder doesn't exist: !path<br />", array('!path' => $path));
$link = l(t('status report'), 'admin/reports/status');
$message .= t('You might want to check the !link to ensure your files directory exists and is writable.', array('!link' => $link));
form_set_error('xmlfile', $message);
return;
}
$validators = array('file_validate_extensions' => array('xml'));
if (isset($form_state['values']['xmlfile']) && ($file = file_save_upload('xmlfile', $validators))) {
$form_state['values']['xmlsource'] = file_get_contents($file->filepath);
$form_state['pattern_file'] = $file;
$form_state['pattern_file']->destination = $path;
}
else if (isset($form_state['values']['xmlfile'])) {
form_set_error('files[xmlfile]', t('Error uploading XML file.'));
return;
}
else if ($form_state['values']['xmlurl']) {
if (!ini_get('allow_url_fopen')) {
form_set_error('xmlsource', t('allow_url_fopen must be enabled in your php configuration in order to use this feature.'));
return;
}
if (strtolower(substr($form_state['values']['xmlurl'], -4)) != '.xml') {
form_set_error('xmlsource', t('Invalid file extension. Only "XML" file extension is allowed.'));
return;
}
if (!($form_state['values']['xmlsource'] = file_get_contents($form_state['values']['xmlurl']))) {
form_set_error('xmlurl', t('Failed to retreive the pattern specified: '. $form_state['values']['xmlurl']) .'. Check your URL and try again.');
return;
}
$pattern = array('/\.[^\.]*$/', '/[^a-zA-Z0-9_]/');
$replacement = array('', '_');
$form_state['values']['xmlname'] = preg_replace($pattern, $replacement, basename($form_state['values']['xmlurl']));
}
if (strpos($form_state['values']['xmlsource'], '<?xml') !== 0) {
$form_state['values']['xmlsource'] = '<?xml version="1.0" encoding="ISO-8859-1"?>' . $form_state['values']['xmlsource'];
}
if ($form_state['values']['xmlname'] && preg_match('/[^a-zA-Z0-9_]/', $form_state['values']['xmlname'])) {
form_set_error('xmlname', t('You can only include letters, numbers, and underscores in the pattern identifier.'));
}
else if ($form_state['values']['xmlname'] && preg_match('/^_/', $form_state['values']['xmlname'])) {
form_set_error('xmlname', t('You cannot start the pattern identifier with an underscore.'));
}
// @TODO validate XML and don't allow import if validation fails
$parse = drupal_xml_parser_create($form_state['values']['xmlsource']);
$success = xml_parse_into_struct($parse, $form_state['values']['xmlsource'], $vals, $index);
// Check that the xml was properly parsed and also that the
// root <pattern> tag and also an <info> tag were used.
if (!$success || !$vals || $vals[0]['tag'] != 'PATTERN' || $vals[1]['tag'] != 'INFO') {
form_set_error('xmlsource', t('Error parsing the XML, please check your syntax and try again.'));
}
}
function patterns_import_submit($form, &$form_state) {
if (isset($form_state['pattern_file'])) {
$saved = file_copy($form_state['pattern_file']->filepath, $form_state['pattern_file']->destination);
}
else if ($form_state['values']['xmlsource']) {
$saved = file_save_data($form_state['values']['xmlsource'], variable_get('patterns_save_xml', 'patterns') .'/'. $form_state['values']['xmlname'] .'.xml', FILE_EXISTS_REPLACE);
}
if ($saved) {
// Reload patterns
patterns_get_patterns(true);
drupal_set_message('Pattern successfully imported.');
}
else {
drupal_set_message("File couldn't be saved on the server. Import failed.", 'error');
}
$form_state['redirect'] = 'admin/build/patterns';
}
function patterns_list() {
drupal_add_css(drupal_get_path('module', 'patterns') .'/patterns.css');
drupal_add_js(drupal_get_path('module', 'patterns') .'/patterns.js');
patterns_load_components();
$patterns = patterns_get_patterns();
if (empty($patterns)) return t('No patterns available.');
// $header = array(t('Title'), t('Status'), t('Version'), t('Public'), t('Actions'));
$header = array(t('Title'), t('Status'), t('Version'), t('Actions'));
// List all patterns
$rows = array();
foreach($patterns as $pid => $pattern) {
+
+ $subpattern_only = (isset($pattern->info['subpattern_only']) && 1==$pattern->info['subpattern_only']);
+ $hidden = (isset($pattern->info['hidden']) && 1 == $pattern->info['hidden']);
+
+ if ($hidden)
+ continue;
+
$actions = array();
- if (!$pattern->status) {
- $actions[] = l(t('Run'), 'admin/build/patterns/enable/'. $pid);
- }
- else if ($pattern->enabled >= $pattern->updated) {
- $actions[] = l(t('Re-Run'), 'admin/build/patterns/enable/'. $pid);
- }
- else {
- $actions[] = l(t('Run Update'), 'admin/build/patterns/enable/'. $pid);
+
+ // cannot run pattern on its own if it's 'subpattern_only'
+ if (!$subpattern_only) {
+ if (!$pattern->status) {
+ $actions[] = l(t('Run'), 'admin/build/patterns/enable/'. $pid);
+ }
+ else if ($pattern->enabled >= $pattern->updated) {
+ $actions[] = l(t('Re-Run'), 'admin/build/patterns/enable/'. $pid);
+ }
+ else {
+ $actions[] = l(t('Run Update'), 'admin/build/patterns/enable/'. $pid);
+ }
}
+
$actions[] = l(t('Edit'), 'admin/build/patterns/edit/'. $pid);
if (variable_get('patterns_allow_publish', FALSE)) {
$actions[] = $pattern->public ? l(t('Unpublish'), 'admin/build/patterns/unpublish/'. $pid) : l(t('Publish'), 'admin/build/patterns/publish/'. $pid);
}
$actions = implode(' ', $actions);
$cells = array();
// $title = l($pattern->title, 'admin/build/patterns/info/'. $pid, array('attributes' => array('class' => 'pattern-title', 'id' => 'pid-'. $pid)));
- $title = '<span id="pid-'. $pid .'" class="pattern-title">'. $pattern->title .'</span>';
+ $title = '<span id="pid-'. $pid .'" class="pattern-title">'. $pattern->title . ($subpattern_only ? ' <em>(sub-pattern)</em>' : '') . '</span>';
// $view_more = '<div>'. t('Clik on pattern title to see more details.') .'</div>';
$info = array();
$info[] = t('Author: ') . $pattern->info['author'];
$info[] = t('Email: ') . $pattern->info['author_email'];
$info[] = t('Web: ') . $pattern->info['author_website'];
$author = theme('item_list', $info);
$title .= '<div id="pid-'. $pid .'-info" class="pattern-info">'. $author . $pattern->description . $view_more .'</div>';
$cells[] = array('data' => $title, 'class' => 'title');
$cells[] = array('data' => $pattern->status ? t('Enabled') : t('Disabled'), 'class' => 'status');
$cells[] = array('data' => $pattern->info['version'], 'class' => 'version');
// $cells[] = $pattern->public ? t('Yes') : t('No');
$cells[] = array('data' => $actions, 'class' => 'actions');
$category = $pattern->info['category'] ? $pattern->info['category'] : t('Other');
$rows[$category][] = $cells;
}
ksort($rows);
foreach ($rows as $title => $category) {
$fieldset = array(
'#title' => t($title),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#value' => theme('table', $header, $category, array('class' => 'patterns-list')),
);
$output .= theme('fieldset', $fieldset);
}
return $output;
}
/**
* Menu callback to undo a patterns update changes
*/
// function patterns_revert($pid) {
// if ($name = db_result(db_query('SELECT name FROM {patterns} WHERE pid = "%d"', $pid))) {
// $path = file_create_path(variable_get('patterns_save_xml', 'patterns') .'/enabled/'. $name .'.xml');
// $new = db_result(db_query('SELECT file FROM {patterns} WHERE pid = "%d"'));
// }
// else {
// drupal_set_message(t('The pattern you specified does not exist.'), 'error');
// drupal_goto('admin/build/patterns');
// }
//
// if (file_exists($path)) {
// if (file_move($path, $new, FILE_EXISTS_REPLACE)) {
// drupal_set_message(t('This pattern was reverted to the state it was at when it was enabled.'));
// drupal_goto();
// }
// }
// else {
// drupal_set_message(t('The patterns enabled-state was not saved properly, therefore it cannot be reverted.'), 'error');
// }
//
// drupal_goto('admin/build/patterns');
// }
/**
* Menu callback to display patterns details page
*/
// function patterns_info($pid = null) {
// if (!is_numeric($pid)) {
// drupal_set_message(t('You must specify a pattern.'));
// return;
// }
//
// $pattern = patterns_get_pattern($pid);
//
// $output = '';
// return $output;
// }
/**
* Menu callback to edit a patterns data
*/
function patterns_edit(&$form_state, $pid = null) {
if (!is_numeric($pid)) {
drupal_set_message(t('You must specify a pattern to edit.'));
return;
}
$pattern = patterns_get_pattern($pid);
// TODO: Turn php into xml here.
// For now just allow modifying the original xml, which
// means the modification cannot be further modified
if (!$pattern->file) {
drupal_set_message(t('This pattern does not seem to have an XML source file to base the modifications off of.'), 'error');
return;
}
$xml = file_get_contents($pattern->file);
$form['name'] = array(
'#type' => 'value',
'#value' => $pattern->name
);
$form['pid'] = array(
'#type' => 'value',
'#value' => $pattern->pid
);
// if ($pattern->enabled <= $pattern->updated) {
// $form['revert'] = array(
// '#type' => 'markup',
// '#value' => l(t('Undo update changes to the state when you enabled the pattern.'), 'admin/build/patterns/revert/'. $pid, array(), drupal_get_destination())
// );
// }
$form['format'] = array(
'#type' => 'select',
'#title' => t('Pattern syntax'),
'#options' => array_combine(patterns_file_types(), patterns_file_types()),
'#default_value' => 'xml'
);
$form['xml'] = array(
'#type' => 'textarea',
'#title' => t('Pattern\'s code'),
'#rows' => 25,
'#default_value' => $xml
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}
/**
* Validate pattern modifications (make sure proper XML)
*/
function patterns_edit_validate($form, &$form_state) {
// @TODO Do validations....
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (!file_check_directory($path, true)) {
form_set_error('form_token', t('Unable to create @path to save the new pattern to.', array('@path' => $path)));
}
}
/**
* Submit edits to the pattern
*/
function patterns_edit_submit($form, &$form_state) {
// If this is an enabled pattern, make sure the enabled pattern is saved in its current state
if ($file = db_result(db_query('SELECT file FROM {patterns} WHERE status = 1 AND name = "%s"', $form_state['values']['name']))) {
$dir = file_directory_path() .'/'. variable_get('patterns_save_xml', 'patterns') .'/enabled';
file_check_directory($dir, true);
$path = $dir .'/'. $form_state['values']['name'] .'.'. $form_state['values']['format'];
if (!file_exists($path)) {
file_copy($file, $path, FILE_EXISTS_ERROR);
}
}
// Save the new pattern into the pattern files dir.
$path = file_directory_path() .'/'. variable_get('patterns_save_xml', 'patterns') .'/'. $form_state['values']['name'] .'.'. $form_state['values']['format'];
file_save_data($form_state['values']['xml'], $path, FILE_EXISTS_REPLACE);
$old = db_result(db_query('SELECT file FROM {patterns} WHERE name = "%s"', $form_state['values']['name']));
// Load and save pattern
$load_func = 'patterns_load_' .$form_state['values']['format'];
if ($pattern = $load_func($path)) {
if ($old) {
db_query('UPDATE {patterns} SET file = "%s", updated = "%s" WHERE pid = "%d"', $path, time(), $form_state['values']['pid']);
}
patterns_save_pattern($pattern, $path, $form_state['values']['name']);
drupal_set_message(t('%name was saved.', array('%name' => $form_state['values']['name'])));
$form_state['redirect'] = 'admin/build/patterns';
}
else {
drupal_set_message(t("Pattern '%name' couldn't be saved. Make sure edited code is well-formed.", array('%name' => $form_state['values']['name'])), 'error');
}
}
/**
* List the modules used by a particular pattern
*/
function patterns_modules_page($pid) {
$pattern = patterns_get_pattern($pid);
drupal_set_title($pattern->title .' '. t('(Pattern Modules)'));
$modules = isset($pattern->pattern['modules']) ? $pattern->pattern['modules'] : array();
$modules_info = module_rebuild_cache();
$modules_list = module_list();
// Get module name, whether its to be disabled or enabled,
// whether the module is available or not, and whether it is
// currently enabled or not
foreach($modules as $module) {
$row = array();
$delete = is_array($module) ? $module['delete'] : false;
$module = is_array($module) ? $module['value'] : $module;
$available = array_key_exists($module, $modules_info);
$enabled = array_key_exists($module, $modules_list);
$row[] = $module;
$row[] = $available ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $enabled ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $delete ? t('Delete') : t('Enable');
$rows[] = $row;
if (!$available) {
$not_available = true;
}
}
if ($not_available) {
drupal_set_message(t('Some modules are not availalble, please download them before running this pattern.'), 'error');
}
else {
drupal_set_message(t('All modules required by this module are available. Click !here to run this pattern.', array('!here' => l(t('here'), 'admin/build/patterns/enable/'. $pid))));
}
return theme('table', array(t('Name'), t('Available'), t('Enabled'), t('Pattern Action')), $rows, t('Modules used for this pattern'));
}
function patterns_load_components() {
static $loaded = false;
if ($loaded) {
return;
}
require_once drupal_get_path('module', 'patterns') .'/patterns.inc';
// Get a list of directories to search
$paths = module_invoke_all('patterns_directory');
foreach($paths as $path) {
foreach(file_scan_directory($path .'/components', '.\.inc$') as $file) {
include_once $file->filename;
}
}
$loaded = true;
}
function patterns_get_patterns($reset = true) {
patterns_load_components();
if ($reset || !variable_get('patterns_loaded', false)) {
// Get a listing of enabled patterns
$enabled = array();
$result = db_query('SELECT file FROM {patterns} WHERE status = 1');
while ($pattern = db_fetch_object($result)) {
$enabled[] = $result->file;
}
$priority = array();
$errors = array();
// Get list of directories to scan for patterns
$patterns_paths = patterns_paths();
// get valid file extensions
$mask = '.\.('. implode('|', patterns_file_types()) .')$';
// prepare list of files/folders to be excluded
// 'enabled' - Don't save enabled pattern backups
$no_mask = array('.', '..', 'CVS', '.svn', 'enabled');
foreach ($patterns_paths as $path) {
foreach(file_scan_directory($path, $mask, $no_mask) as $file) {
// Can't update existing patterns that are enabled
if (in_array($file->filename, $enabled) || in_array($file->name, $priority)) {
continue;
}
$priority[] = $file->name;
// choose appropriate function based on the file extension
$func = 'patterns_load_'. substr($file->basename, strlen($file->name) + 1);
// Load and save pattern
if ($pattern = $func($file->filename)) {
patterns_save_pattern($pattern, $file->filename, $file->name);
}
else {
$errors[] = $file->filename;
}
}
}
variable_set('patterns_loaded', time());
}
$result = db_query('SELECT * FROM {patterns}');
$messages = array();
while ($pattern = db_fetch_object($result)) {
// skip pattern if its file is missing
if (!is_file($pattern->file)) continue;
// skip pattern if loading failed and report that to the user
if (in_array($pattern->file, $errors)) {
$messages[] = t("Pattern couldn't be loaded from the file '%file'", array('%file' => $pattern->file));
continue;
}
$patterns[$pattern->pid] = $pattern;
$data = unserialize($pattern->pattern);
$patterns[$pattern->pid]->pattern = $data;
$patterns[$pattern->pid]->info = $data['info'];
}
if (!empty($messages)) {
drupal_set_message(implode('<br>', $messages) .'<br>'. t('Make sure that above file(s) are readable and contain valid data.'), 'error');
}
return $patterns;
}
/**
* return a list of paths that will be scanned for patterns
*/
function patterns_paths() {
global $profile;
if (!isset($profile)) {
$profile = variable_get('install_profile', 'default');
}
// array of all the paths where we should look for patterns
$patterns_paths = array(
conf_path() .'/patterns',
'profiles/'. $profile .'/patterns',
'sites/all/patterns'
);
// allow any module to include patterns too
foreach(module_invoke_all('patterns_directory') as $path) {
if (is_dir($path)) {
$patterns_paths[] = $path .'/patterns';
}
}
// also prepend files folder if it's valid
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (file_check_directory($path)) {
array_unshift($patterns_paths, $path);
}
return $patterns_paths;
}
/**
* Implementation of hook_patterns_directory()
*
* Let us know about where the pattern files are at
*/
function patterns_patterns_directory() {
return drupal_get_path('module', 'patterns');
}
function patterns_save_pattern($pattern, $path = '', $name = '') {
$title = $pattern['info']['title'];
$description = $pattern['info']['description'];
$author = $pattern['info']['author'];
if ($pid = db_result(db_query('SELECT pid FROM {patterns} WHERE name = "%s"', $name))) {
$updated = db_result(db_query('SELECT updated FROM {patterns} WHERE pid = "%d"', $pid));
if (($new_updated = filemtime($path)) > $updated) {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", updated = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $new_updated, $description, $pid);
}
else {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $description, $pid);
}
}
else {
db_query('INSERT INTO {patterns} (name, status, file, updated, enabled, title, description, pattern) VALUES ( "%s", 0, "%s", "%s", 0, "%s", "%s", "%s")', $name, $path, time(), $title, $description, serialize($pattern));
}
}
function patterns_get_pattern($id) {
if (is_numeric($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE pid = "%d"', $id));
}
else if (is_string($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE name = "%s"', $id));
}
if (!$pattern) return FALSE;
// Get the actual data. Data is stored in serialized form in the db.
$pattern->pattern = unserialize($pattern->pattern);
return $pattern;
}
/**
* Check if pattern array contains only allowed keys
*
* @param $pattern
* pattern array obtained by parsing pattern file
* @return
* TRUE when only allowed array keys are found, FALSE otherwise
*
* @todo expand this function to include much more detailed validation
*/
function patterns_validate_pattern($pattern) {
if (empty($pattern)) {
return FALSE;
}
$allowed_keys = array('info', 'modules', 'actions');
$diff = array_diff(array_keys($pattern), $allowed_keys);
return empty($diff) ? TRUE : FALSE;
}
/**
* Return file extensions supported by patterns module
*
* @return array of supported file types
*
* @todo convert this into pluggable system
*/
function patterns_file_types() {
$result = array('xml', 'php');
if (file_exists(drupal_get_path('module', 'patterns') .'/spyc/spyc.php')) {
$result[] = 'yaml';
}
return $result;
}
function patterns_load_yaml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
include_once 'spyc/spyc.php';
$pattern = Spyc::YAMLLoad($path);
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
function patterns_load_string_yaml($source) {
// loading yaml from source doesn't preserve line breaks
// so we need to save it as a file first
$path = file_directory_temp() .'/import.yaml';
file_save_data($source, $path, FILE_EXISTS_REPLACE);
$pattern = patterns_load_yaml($path);
unlink($path);
return $pattern;
}
function patterns_load_xml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
if (!$xml = file_get_contents($path)) {
return FALSE;
}
return patterns_load_string_xml($xml);
}
function patterns_load_string_xml($source) {
$pattern = patterns_from_source($source);
if (empty($pattern) || $pattern['tag'] != 'pattern') {
return FALSE;
}
// Rearrange the data in a nice way for each component.
// Make sure actions are processed differently so order is preserved.
$pattern = patterns_rearrange_data($pattern);
foreach($pattern as $key => $values) {
$pattern[$values['tag']] = $values;
unset($pattern[$values['tag']]['tag']);
unset($pattern[$key]);
// ensure the 'modules' array is collapsed - this is necessary to do if,
// for example, we're including multiple sub-patterns which each include
// their own list of modules
if ('modules' == $values['tag']) {
if (isset($values['module'])) {
if (is_array($values['module'])) {
$pattern['modules'] = $values['module'];
} else {
$pattern['modules'] = array($values['module']);
}
}
}
}
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
/**
* Read and evaluate a php file to return a 'pattern'
*/
function patterns_load_php($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
$pattern = array();
|
hiddentao/patterns2
|
2eb034f97a312804c5b02c5627c3fd02aff1d49f
|
1) Added a 'menu_trail' tag which allows you to configure the Menu Trails module (node type <-> menu mappings) using a pattern.
|
diff --git a/components/menutrails.inc b/components/menutrails.inc
new file mode 100644
index 0000000..640eedc
--- /dev/null
+++ b/components/menutrails.inc
@@ -0,0 +1,155 @@
+<?php
+/**
+ * Component for updating menutrails configuration.
+ * @author Ramesh Nair (hiddentao)
+ */
+
+
+function menutrails_patterns($op, $id = null, &$data = null) {
+ switch($op) {
+ // Return the valid tags that this component can prepare and process
+ case 'tags':
+ return array('menu_trail');
+ break;
+
+ // Return a list of forms/actions this component can handle
+ case 'actions':
+ return array(
+ 'menutrails_settings_form' => t('Menu Trails: Add/configure trails'),
+ );
+ break;
+
+ // Return a summary of an action
+ case 'summary':
+ if ('menutrails_settings_form' == $id && isset($data['type'])) {
+ return t('Configuring trail for node type: %name', array('%name' => $data['type']));
+ }
+ break;
+
+ // Prepare data for processing
+ case 'prepare':
+ break;
+
+ // Pre validate actions
+ case 'pre-validate':
+ if (!module_exists('menutrails')) {
+ return t('Menu Trails module must be enabled.');
+ }
+ if (!isset($data['menu']) || !isset($data['menu']['parent']) || !isset($data['menu']['item'])) {
+ return t('Valid "menu" (with "parent" and "item") required.');
+ }
+ if (!isset($data['type'])) {
+ return t('You must specify a "type" to associate with the menu.');
+ }
+ break;
+
+ // Return the form_id('s) for each action
+ case 'form_id':
+ return 'menutrails_settings_form';
+
+ break;
+
+ // Prepare for valid processing of this type of component
+ case 'build':
+ if ('menutrails_settings_form' == $id) {
+
+ // node type
+ $types = node_get_types('types');
+ $type_internal_name = '';
+ foreach ($types as $type => $info) {
+ if ($info->name == $data['type']) {
+ $type_internal_name = $type;
+ break;
+ } else if ($type == $data['type']) {
+ $type_internal_name = $type;
+ break;
+ }
+ }
+
+ // menu item
+ $menus = menu_get_menus(TRUE);
+ $menu_internal_name = '';
+ foreach ($menus as $name => $title) {
+ if ($title == $data['menu']['parent']) {
+ $menu_internal_name = $name;
+ break;
+ } else if ($name == $data['menu']['parent']) {
+ $menu_internal_name = $name;
+ break;
+ }
+ }
+ $tree = menu_tree_all_data($menu_internal_name);
+ $menu_item = _menutrails_patterns_get_menu_item($tree, $data['menu']['item']);
+
+ // update params
+ $data['menutrails_node_types'][$type_internal_name] = $menu_item['link']['href'];
+ }
+
+ return $data;
+ break;
+
+ // Validate the values for an action before running the pattern
+ //
+ // Check here rather than in pre-validate in case we're adding
+ // roles or filters in the same pattern.
+ //
+ case 'validate':
+
+ // check node type
+ $types = node_get_types('types');
+ $found = FALSE;
+ foreach ($types as $type => $info) {
+ if ($type == $data['type'] || $info->name == $data['type']) {
+ $found = TRUE;
+ break;
+ }
+ }
+ if (!$found) {
+ return t('Invalid content type: %type', array('%type' => $data['type']));
+ }
+
+ // check menu
+ $menus = menu_get_menus(TRUE);
+ $found = FALSE;
+ $name = '';
+ foreach ($menus as $name => $title) {
+ if ($title == $data['menu']['parent'] || $name == $data['menu']['parent']) {
+ $found = TRUE;
+ break;
+ }
+ }
+ if (!$found)
+ return t('Invalid menu name: %menu', array('%menu' => $data['menu']['parent']));
+
+ // check menu item
+ $tree = menu_tree_all_data($name);
+ $menu_item = _menutrails_patterns_get_menu_item($tree, $data['menu']['item']);
+ if (!$menu_item)
+ return t('Invalid menu item: %item', array('%item' => $data['menu']['item']));
+
+ break;
+
+ // Build a patterns actions and parameters
+ case 'params':
+ return array();
+ break;
+
+ }
+}
+
+
+function _menutrails_patterns_get_menu_item(&$tree, $menu_item_name) {
+ foreach ($tree as $item) {
+ // only want content nodes that are hidden
+ if ($menu_item_name == $item['link']['title']) {
+ return $item;
+ }
+ if (isset($item['below']) && is_array($item['below']) && !empty($item['below'])) {
+ $ret = _menutrails_patterns_get_menu_item($item['below'], $menu_item_name);
+ if ($ret) {
+ return $ret;
+ }
+ }
+ }
+ return FALSE;
+}
diff --git a/patterns.module b/patterns.module
index f892a89..76e7da4 100644
--- a/patterns.module
+++ b/patterns.module
@@ -1,699 +1,704 @@
<?php
// $Id: patterns.module,v 1.1.2.2.2.80 2009/10/02 09:15:47 vaish Exp $
/**
* @file
* Enables extremely simple adding/removing features to your site with minimal to no configuration
*/
/**
* @todo:
* @ Enable pattern configurations
* @ **done**Enable actions to see ids created/updated from other actions inside the pattern (tokens?)
* @ **semi-done** Reset patterns
* @ Enable components to analyze the current pattern for better validation
* @ Allow module version restricting
* @ Put in functionality to auto-download modules (and the correct version)
* @ Enable backups before running patterns and reverting back to those backups
* @ Implement a progress meter
* @ Handle default values better to allow for absolute minimal actions
* @ Enable interactive actions by allowing patterns to resume from a saved position
* @ Implement an export feature for all available form_ids
* @ Allow resuming failed patterns
* @ In the pattern details, list any sub-patterns directly on the patterns listing page
*/
+
+
+
/**
* Implementation of hook_perm().
*/
function patterns_perm() {
return array('administer patterns');
}
/**
* Implementation of hook_menu().
*/
function patterns_menu() {
$items = array();
$items['admin/build/patterns'] = array(
'title' => 'Patterns',
'description' => 'Administer patterns available for your site',
'page callback' => 'patterns_list',
'access arguments' => array('administer patterns')
);
$items['admin/build/patterns/list'] = array(
'title' => 'List',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10
);
$items['admin/build/patterns/edit'] = array(
'title' => 'Edit Pattern',
'page callback' => 'drupal_get_form',
'page arguments' => array('patterns_edit'),
'access arguments' => array('administer patterns'),
'type' => MENU_CALLBACK
);
$items['admin/build/patterns/enable'] = array(
'title' => 'Enable Pattern',
'page callback' => 'drupal_get_form',
'page arguments' => array('patterns_enable_pattern'),
'access arguments' => array('administer patterns'),
'type' => MENU_CALLBACK
);
$items['admin/build/patterns/publish'] = array(
'title' => 'Publish Pattern',
'page callback' => 'patterns_publish_pattern',
'access arguments' => array('administer patterns'),
'type' => MENU_CALLBACK
);
$items['admin/build/patterns/unpublish'] = array(
'title' => 'Unpublish Pattern',
'page callback' => 'patterns_unpublish_pattern',
'access arguments' => array('administer patterns'),
'type' => MENU_CALLBACK
);
$items['patterns.xml'] = array(
'title' => 'Published Patterns',
'page callback' => 'patterns_feed',
'access callback' => TRUE,
'type' => MENU_CALLBACK
);
$items['admin/build/patterns/settings'] = array(
'title' => 'Settings',
'page callback' => 'drupal_get_form',
'page arguments' => array('patterns_settings'),
'access arguments' => array('administer patterns'),
'type' => MENU_LOCAL_TASK,
'weight' => 10
);
$items['admin/build/patterns/get'] = array(
'title' => 'Download Pattern Source',
'page callback' => 'patterns_get_source',
'access callback' => TRUE,
'type' => MENU_CALLBACK
);
// $items[] = array('path' => 'admin/build/patterns/configure',
// 'title' => t('Configure Pattern'),
// 'callback' => 'drupal_get_form',
// 'callback arguments' => array('patterns_configure_pattern'),
// 'type' => MENU_CALLBACK
// );
// $items[] = array('path' => 'admin/build/patterns/info',
// 'title' => t('Pattern Details'),
// 'callback' => 'patterns_info',
// 'type' => MENU_CALLBACK
// );
// $items[] = array('path' => 'admin/build/patterns/disable',
// 'access' => user_access('administer patterns'),
// 'title' => t('Disable Pattern'),
// 'callback' => 'drupal_get_form',
// 'callback arguments' => array('patterns_disable_pattern'),
// 'type' => MENU_CALLBACK
// );
$items['admin/build/patterns/modules'] = array(
'title' => 'Pattern Modules',
'page callback' => 'patterns_modules_page',
'access arguments' => array('administer patterns'),
'type' => MENU_CALLBACK
);
// $items[] = array('path' => 'admin/build/patterns/revert',
// 'access' => user_access('administer patterns'),
// 'title' => t('Revert Pattern'),
// 'callback' => 'patterns_revert',
// 'type' => MENU_CALLBACK
// );
$items['admin/build/patterns/import'] = array(
'title' => 'Import',
'page callback' => 'drupal_get_form',
'page arguments' => array('patterns_import_source'),
'access arguments' => array('administer patterns'),
'type' => MENU_LOCAL_TASK
);
$items['admin/build/patterns/import/source'] = array(
'title' => 'Import Source Code',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10
);
$items['admin/build/patterns/import/file'] = array(
'title' => 'Import File',
'page callback' => 'drupal_get_form',
'page arguments' => array('patterns_import_file'),
'access arguments' => array('administer patterns'),
'type' => MENU_LOCAL_TASK
);
$items['admin/build/patterns/import/url'] = array(
'title' => 'Import from URL',
'page callback' => 'drupal_get_form',
'page arguments' => array('patterns_import_url'),
'access arguments' => array('administer patterns'),
'type' => MENU_LOCAL_TASK
);
$items['admin/build/patterns/server'] = array(
'title' => 'Patterns Server',
'page callback' => 'drupal_get_form',
'page arguments' => array('patterns_import_server'),
'access arguments' => array('administer patterns'),
'type' => MENU_LOCAL_TASK,
'weight' => -5
);
return $items;
}
/**
* Implementation of hook_help().
*/
function patterns_help($section, $arg = NULL) {
$output = '';
switch ($section) {
case 'admin/build/patterns':
$output = t('Patterns will be looked for in files under the following locations: ') . theme('item_list', patterns_paths());
break;
}
return $output;
}
+
+
/**
* Display the pattern settings form
*/
function patterns_settings(&$form_state) {
$form['patterns_form_helper'] = array(
'#type' => 'checkbox',
'#title' => t('Enable Patterns Form Helper'),
'#description' => t('When enabled, patterns form helper will dump $form_id and $form_state variables at the bottom of each page. Dump will always contain values from the latest form submission. This may be very helpful while writing your own patterns.'),
'#default_value' => variable_get('patterns_form_helper', FALSE),
);
$form['patterns_allow_publish'] = array(
'#type' => 'checkbox',
'#title' => t('Share your patterns'),
'#description' => t('When enabled, you will be able to "publish" selected patterns and make them available to other patterns users on the following URL: %url.', array('%url' => url(NULL, array('absolute' => TRUE)) . (variable_get('clean_url', 0) ? '' : '?q=') .'patterns.xml')),
'#default_value' => variable_get('patterns_allow_publish', FALSE),
);
// Reload patterns while we are here and ensure the lists are up to date
patterns_get_patterns(TRUE);
return system_settings_form($form);
}
/**
* Display the import pattern form
*/
function patterns_import_source(&$form_state) {
if (empty($form_state['post'])) {
drupal_set_message(t('Import feature currently supports only XML file format.'), 'warning');
}
$form['xmlname'] = array(
'#type' => 'textfield',
'#title' => t('Pattern Identifier'),
'#description' => t('Machine readable name for the pattern. The actual title should be included in the pattern itself.'),
'#required' => true
);
$form['xmlsource'] = array(
'#type' => 'textarea',
'#rows' => 15,
'#title' => t('Enter Pattern Source Code'),
'#description' => t('Imported patterns are not executed until you run them manually.')
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import')
);
$form['#validate'][] = 'patterns_import_validate';
$form['#submit'][] = 'patterns_import_submit';
return $form;
}
/**
* Menu callback - returns source code of the requested pattern
* if the pattern is public
*
* @param $pid
* pattern id
* @return
* source code of the requested pattern
*/
function patterns_get_source($pid) {
if (!is_numeric($pid)) {
exit;
}
$pattern = patterns_get_pattern($pid);
// make sure pattern is public (published)
if (!$pattern->public) {
exit;
}
$content_type = 'text/plain';
if (substr($pattern->file,-4) == '.xml') {
$content_type = 'text/xml';
}
drupal_set_header('Content-Type: '. $content_type .'; charset=utf-8');
print file_get_contents($pattern->file);
exit;
}
/**
* Prints XML Feed of published (public) patterns
*
*/
function patterns_feed() {
global $base_url;
if (!variable_get('patterns_allow_publish', FALSE)) {
return drupal_not_found();
}
$patterns = variable_get('patterns_allow_publish', FALSE) ? patterns_get_patterns() : array();
foreach ($patterns as $pattern) {
if (!$pattern->public) {
continue;
}
preg_match('/[^\.]*$/', $pattern->file, $matches);
$extension = $matches[0];
$item = " <pattern>\n";
$item .= " <pid>". $pattern->pid ."</pid>\n";
$item .= " <name>". $pattern->name . "</name>\n";
$item .= " <title>". $pattern->title . "</title>\n";
$item .= " <description>". $pattern->description . "</description>\n";
$item .= " <category>". $pattern->pattern['info']['category'] . "</category>\n";
$item .= " <file_type>". $extension . "</file_type>\n";
$item .= " </pattern>\n";
$items .= $item;
}
$header = " <info>\n";
$header .= " <url>". $base_url ."</url>\n";
// $header .= " <description>". $description ."</description>\n";
$header .= " </info>\n";
$feed = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$feed .= "<patterns_feed>\n";
$feed .= $header;
$feed .= " <patterns>\n";
$feed .= $items;
$feed .= " </patterns>\n";
$feed .= "</patterns_feed>\n";
drupal_set_header('Content-Type: text/xml; charset=utf-8');
print $feed;
exit;
}
/**
* Display the import pattern from server form
*/
function patterns_import_server(&$form_state) {
if (empty($form_state['storage'])) {
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (!file_check_directory($path, true)) {
$message = t("In order to save imported patterns, directory %path must be writable.<br />", array('%path' => $path));
$link = l(t('status report'), 'admin/reports/status');
$message .= t('You might want to check the !link to ensure your files directory exists and is writable.', array('!link' => $link));
drupal_set_message($message, 'error');
return array();
}
$form['server_url'] = array(
'#type' => 'textfield',
'#title' => t('Specify Patterns Server URL'),
'#description' => t('URL of the web site you want to import patterns from. Example: http://patterns.graviteklabs.com'),
'#default_value' => variable_get('patterns_default_server', 'http://patterns.graviteklabs.com'),
'#size' => 48
);
}
else {
$feed = $form_state['storage']['feed'];
$form['patterns'] = array(
'#type' => 'fieldset',
'#tree' => TRUE,
'#title' => t('Patterns'),
);
foreach ($feed['patterns'] as $pattern) {
$form['patterns'][$pattern['pid']] = array(
'#type' => 'checkbox',
'#title' => $pattern['title'],
'#description' => $pattern['description'],
'#disabled' => in_array($pattern['file_type'], patterns_file_types()) ? FALSE : TRUE,
);
}
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => empty($form_state['storage']) ? t('Get Patterns List') : t('Import')
);
$form['#validate'][] = 'patterns_import_server_validate';
$form['#submit'][] = 'patterns_import_server_submit';
return $form;
}
function patterns_import_server_validate($form, &$form_state) {
if (empty($form_state['storage'])) {
if (!ini_get('allow_url_fopen')) {
form_set_error('fopen', t('allow_url_fopen must be enabled in your php configuration in order to use this feature.'));
return;
}
$feed_url = $form_state['values']['server_url'] .'/patterns.xml';
if (empty($feed_url)) {
form_set_error('server_url', t('Please enter Patterns Server URL.'));
return;
}
if (!$xml = file_get_contents($feed_url)) {
form_set_error('server_url', t('Failed to retreive the patterns feed from: %url. Please check your URL and try again.', array('%url' => $form_state['values']['server_url'])));
return;
}
// @todo: replace this with proper XML validation
if (strpos($xml, '<?xml') !== 0) {
form_set_error('', t('URL %url is not a valid XML file.', array('%url' => $form_state['values']['server_url'])));
return;
}
$feed = patterns_from_source($xml);
if (!$feed) {
form_set_error('', t('URL %url is not a valid patterns feed.', array('%url' => $form_state['values']['server_url'])));
return;
}
$feed = patterns_feed_rearrange_data($feed);
if (!$feed) {
form_set_error('', t('URL %url is not a valid patterns feed.', array('%url' => $form_state['values']['server_url'])));
return;
}
$form_state['storage']['step'] = 'get url';
$form_state['storage']['server_url'] = $form_state['values']['server_url'];
$form_state['storage']['feed_url'] = $feed_url;
$form_state['storage']['feed'] = $feed;
}
else {
$form_state['storage']['step'] = 'select patterns';
}
}
function patterns_import_server_submit($form, &$form_state) {
if ($form_state['storage']['step'] == 'get url') {
return;
}
$pids = array_keys(array_filter($form_state['values']['patterns']));
$feed = $form_state['storage']['feed'];
$errors = array();
foreach ($pids as $pid) {
$url = $feed['info']['url'] .'/admin/build/patterns/get/'. $pid;
$pattern_info = $feed['patterns'][$pid];
if (!$source = file_get_contents($url)) {
$errors['get file'][] = $pattern_info;
continue;
}
// save file
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
$path .= '/'. $pattern_info['name'] .'.'. $pattern_info['file_type'];
if (!$saved = file_save_data($source, $path, FILE_EXISTS_ERROR)) {
$errors['save file'][] = $pattern_info;
continue;
}
// choose appropriate function based on the file extension
$func = 'patterns_load_'. $pattern_info['file_type'];
// Load pattern
if (!$pattern = $func($saved)) {
$errors['load pattern'][] = $pattern_info;
unlink($saved);
continue;
}
patterns_save_pattern($pattern, $saved, $pattern_info['name']);
}
if (!empty($errors)) {
$patterns = array();
foreach ($errors as $type => $files) {
foreach ($files as $file) {
$patterns[] = $file['title'] .' (cause: "'. $type .'" failed)';
}
$patterns = theme('item_list', $patterns);
}
drupal_set_message(t('Import failed for the following patterns: ') .'<br>'. $patterns, 'error');
return;
}
unset($form_state['storage']);
$form_state['redirect'] = 'admin/build/patterns';
}
function patterns_feed_rearrange_data($feed) {
unset($feed['tag']);
foreach ($feed as $key => $section) {
$tag = $section['tag'];
if ($tag == 'pattern') {
unset($section['tag']);
if (!isset($section['value'])) {
foreach ($section as $t) {
if ($t['tag'] == 'pid') {
$pid = $t['value'];
break;
}
}
$result[$pid] = patterns_feed_rearrange_data($section);
}
else {
$result[$tag] = $section['value'];
}
}
else {
unset($section['tag']);
if (!isset($section['value'])) {
$result[$tag] = patterns_feed_rearrange_data($section);
}
else {
$result[$tag] = $section['value'];
}
}
}
return $result;
}
function patterns_publish_pattern($pid) {
if (is_numeric($pid)) {
$result = db_query("UPDATE {patterns} SET public = 1 WHERE pid = %d", $pid);
}
drupal_set_message('Pattern published.');
drupal_goto('admin/build/patterns');
}
function patterns_unpublish_pattern($pid) {
if (is_numeric($pid)) {
$result = db_query("UPDATE {patterns} SET public = 0 WHERE pid = %d", $pid);
}
drupal_set_message('Pattern unpublished.');
drupal_goto('admin/build/patterns');
}
/**
* Display the import pattern file form
*/
function patterns_import_file(&$form_state) {
if (empty($form_state['post'])) {
drupal_set_message(t('Import feature currently supports only XML file format.'), 'warning');
}
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['xmlfile'] = array(
'#type' => 'file',
'#title' => t('Upload Pattern File'),
'#description' => t('Imported patterns are not executed until you run them manually.'),
'#size' => 48
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import')
);
$form['#validate'][] = 'patterns_import_validate';
$form['#submit'][] = 'patterns_import_submit';
return $form;
}
/**
* Display the import pattern url form
*/
function patterns_import_url(&$form_state) {
if (empty($form_state['post'])) {
drupal_set_message(t('Import feature currently supports only XML file format.'), 'warning');
}
$form['xmlurl'] = array(
'#type' => 'textfield',
'#title' => t('Specify an URL'),
'#description' => t('Import a pattern from a remote URL. Imported patterns are not executed until you run them manually.'),
'#size' => 48
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import')
);
$form['#validate'][] = 'patterns_import_validate';
$form['#submit'][] = 'patterns_import_submit';
return $form;
}
function patterns_import_validate($form, &$form_state) {
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (!file_check_directory($path, true)) {
$message = t("Destination folder doesn't exist: !path<br />", array('!path' => $path));
$link = l(t('status report'), 'admin/reports/status');
$message .= t('You might want to check the !link to ensure your files directory exists and is writable.', array('!link' => $link));
form_set_error('xmlfile', $message);
return;
}
$validators = array('file_validate_extensions' => array('xml'));
if (isset($form_state['values']['xmlfile']) && ($file = file_save_upload('xmlfile', $validators))) {
$form_state['values']['xmlsource'] = file_get_contents($file->filepath);
$form_state['pattern_file'] = $file;
$form_state['pattern_file']->destination = $path;
}
else if (isset($form_state['values']['xmlfile'])) {
form_set_error('files[xmlfile]', t('Error uploading XML file.'));
return;
}
else if ($form_state['values']['xmlurl']) {
if (!ini_get('allow_url_fopen')) {
form_set_error('xmlsource', t('allow_url_fopen must be enabled in your php configuration in order to use this feature.'));
return;
}
if (strtolower(substr($form_state['values']['xmlurl'], -4)) != '.xml') {
form_set_error('xmlsource', t('Invalid file extension. Only "XML" file extension is allowed.'));
return;
}
if (!($form_state['values']['xmlsource'] = file_get_contents($form_state['values']['xmlurl']))) {
form_set_error('xmlurl', t('Failed to retreive the pattern specified: '. $form_state['values']['xmlurl']) .'. Check your URL and try again.');
return;
}
$pattern = array('/\.[^\.]*$/', '/[^a-zA-Z0-9_]/');
$replacement = array('', '_');
$form_state['values']['xmlname'] = preg_replace($pattern, $replacement, basename($form_state['values']['xmlurl']));
}
if (strpos($form_state['values']['xmlsource'], '<?xml') !== 0) {
$form_state['values']['xmlsource'] = '<?xml version="1.0" encoding="ISO-8859-1"?>' . $form_state['values']['xmlsource'];
}
if ($form_state['values']['xmlname'] && preg_match('/[^a-zA-Z0-9_]/', $form_state['values']['xmlname'])) {
form_set_error('xmlname', t('You can only include letters, numbers, and underscores in the pattern identifier.'));
}
else if ($form_state['values']['xmlname'] && preg_match('/^_/', $form_state['values']['xmlname'])) {
form_set_error('xmlname', t('You cannot start the pattern identifier with an underscore.'));
}
// @TODO validate XML and don't allow import if validation fails
$parse = drupal_xml_parser_create($form_state['values']['xmlsource']);
$success = xml_parse_into_struct($parse, $form_state['values']['xmlsource'], $vals, $index);
// Check that the xml was properly parsed and also that the
// root <pattern> tag and also an <info> tag were used.
if (!$success || !$vals || $vals[0]['tag'] != 'PATTERN' || $vals[1]['tag'] != 'INFO') {
form_set_error('xmlsource', t('Error parsing the XML, please check your syntax and try again.'));
}
}
function patterns_import_submit($form, &$form_state) {
if (isset($form_state['pattern_file'])) {
$saved = file_copy($form_state['pattern_file']->filepath, $form_state['pattern_file']->destination);
}
else if ($form_state['values']['xmlsource']) {
$saved = file_save_data($form_state['values']['xmlsource'], variable_get('patterns_save_xml', 'patterns') .'/'. $form_state['values']['xmlname'] .'.xml', FILE_EXISTS_REPLACE);
}
if ($saved) {
// Reload patterns
patterns_get_patterns(true);
drupal_set_message('Pattern successfully imported.');
}
else {
drupal_set_message("File couldn't be saved on the server. Import failed.", 'error');
}
$form_state['redirect'] = 'admin/build/patterns';
}
function patterns_list() {
drupal_add_css(drupal_get_path('module', 'patterns') .'/patterns.css');
drupal_add_js(drupal_get_path('module', 'patterns') .'/patterns.js');
patterns_load_components();
$patterns = patterns_get_patterns();
if (empty($patterns)) return t('No patterns available.');
// $header = array(t('Title'), t('Status'), t('Version'), t('Public'), t('Actions'));
$header = array(t('Title'), t('Status'), t('Version'), t('Actions'));
// List all patterns
$rows = array();
foreach($patterns as $pid => $pattern) {
$actions = array();
if (!$pattern->status) {
$actions[] = l(t('Run'), 'admin/build/patterns/enable/'. $pid);
}
else if ($pattern->enabled >= $pattern->updated) {
$actions[] = l(t('Re-Run'), 'admin/build/patterns/enable/'. $pid);
}
else {
$actions[] = l(t('Run Update'), 'admin/build/patterns/enable/'. $pid);
}
$actions[] = l(t('Edit'), 'admin/build/patterns/edit/'. $pid);
if (variable_get('patterns_allow_publish', FALSE)) {
$actions[] = $pattern->public ? l(t('Unpublish'), 'admin/build/patterns/unpublish/'. $pid) : l(t('Publish'), 'admin/build/patterns/publish/'. $pid);
}
$actions = implode(' ', $actions);
$cells = array();
// $title = l($pattern->title, 'admin/build/patterns/info/'. $pid, array('attributes' => array('class' => 'pattern-title', 'id' => 'pid-'. $pid)));
$title = '<span id="pid-'. $pid .'" class="pattern-title">'. $pattern->title .'</span>';
// $view_more = '<div>'. t('Clik on pattern title to see more details.') .'</div>';
$info = array();
$info[] = t('Author: ') . $pattern->info['author'];
$info[] = t('Email: ') . $pattern->info['author_email'];
$info[] = t('Web: ') . $pattern->info['author_website'];
$author = theme('item_list', $info);
$title .= '<div id="pid-'. $pid .'-info" class="pattern-info">'. $author . $pattern->description . $view_more .'</div>';
$cells[] = array('data' => $title, 'class' => 'title');
$cells[] = array('data' => $pattern->status ? t('Enabled') : t('Disabled'), 'class' => 'status');
$cells[] = array('data' => $pattern->info['version'], 'class' => 'version');
// $cells[] = $pattern->public ? t('Yes') : t('No');
$cells[] = array('data' => $actions, 'class' => 'actions');
$category = $pattern->info['category'] ? $pattern->info['category'] : t('Other');
$rows[$category][] = $cells;
}
ksort($rows);
@@ -863,1218 +868,1227 @@ function patterns_edit_submit($form, &$form_state) {
*/
function patterns_modules_page($pid) {
$pattern = patterns_get_pattern($pid);
drupal_set_title($pattern->title .' '. t('(Pattern Modules)'));
$modules = isset($pattern->pattern['modules']) ? $pattern->pattern['modules'] : array();
$modules_info = module_rebuild_cache();
$modules_list = module_list();
// Get module name, whether its to be disabled or enabled,
// whether the module is available or not, and whether it is
// currently enabled or not
foreach($modules as $module) {
$row = array();
$delete = is_array($module) ? $module['delete'] : false;
$module = is_array($module) ? $module['value'] : $module;
$available = array_key_exists($module, $modules_info);
$enabled = array_key_exists($module, $modules_list);
$row[] = $module;
$row[] = $available ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $enabled ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $delete ? t('Delete') : t('Enable');
$rows[] = $row;
if (!$available) {
$not_available = true;
}
}
if ($not_available) {
drupal_set_message(t('Some modules are not availalble, please download them before running this pattern.'), 'error');
}
else {
drupal_set_message(t('All modules required by this module are available. Click !here to run this pattern.', array('!here' => l(t('here'), 'admin/build/patterns/enable/'. $pid))));
}
return theme('table', array(t('Name'), t('Available'), t('Enabled'), t('Pattern Action')), $rows, t('Modules used for this pattern'));
}
function patterns_load_components() {
static $loaded = false;
if ($loaded) {
return;
}
require_once drupal_get_path('module', 'patterns') .'/patterns.inc';
// Get a list of directories to search
$paths = module_invoke_all('patterns_directory');
foreach($paths as $path) {
foreach(file_scan_directory($path .'/components', '.\.inc$') as $file) {
include_once $file->filename;
}
}
$loaded = true;
}
function patterns_get_patterns($reset = true) {
patterns_load_components();
if ($reset || !variable_get('patterns_loaded', false)) {
// Get a listing of enabled patterns
$enabled = array();
$result = db_query('SELECT file FROM {patterns} WHERE status = 1');
while ($pattern = db_fetch_object($result)) {
$enabled[] = $result->file;
}
$priority = array();
$errors = array();
// Get list of directories to scan for patterns
$patterns_paths = patterns_paths();
// get valid file extensions
$mask = '.\.('. implode('|', patterns_file_types()) .')$';
// prepare list of files/folders to be excluded
// 'enabled' - Don't save enabled pattern backups
$no_mask = array('.', '..', 'CVS', '.svn', 'enabled');
foreach ($patterns_paths as $path) {
foreach(file_scan_directory($path, $mask, $no_mask) as $file) {
// Can't update existing patterns that are enabled
if (in_array($file->filename, $enabled) || in_array($file->name, $priority)) {
continue;
}
$priority[] = $file->name;
// choose appropriate function based on the file extension
$func = 'patterns_load_'. substr($file->basename, strlen($file->name) + 1);
// Load and save pattern
if ($pattern = $func($file->filename)) {
patterns_save_pattern($pattern, $file->filename, $file->name);
}
else {
$errors[] = $file->filename;
}
}
}
variable_set('patterns_loaded', time());
}
$result = db_query('SELECT * FROM {patterns}');
$messages = array();
while ($pattern = db_fetch_object($result)) {
// skip pattern if its file is missing
if (!is_file($pattern->file)) continue;
// skip pattern if loading failed and report that to the user
if (in_array($pattern->file, $errors)) {
$messages[] = t("Pattern couldn't be loaded from the file '%file'", array('%file' => $pattern->file));
continue;
}
$patterns[$pattern->pid] = $pattern;
$data = unserialize($pattern->pattern);
$patterns[$pattern->pid]->pattern = $data;
$patterns[$pattern->pid]->info = $data['info'];
}
if (!empty($messages)) {
drupal_set_message(implode('<br>', $messages) .'<br>'. t('Make sure that above file(s) are readable and contain valid data.'), 'error');
}
return $patterns;
}
/**
* return a list of paths that will be scanned for patterns
*/
function patterns_paths() {
global $profile;
if (!isset($profile)) {
$profile = variable_get('install_profile', 'default');
}
// array of all the paths where we should look for patterns
$patterns_paths = array(
conf_path() .'/patterns',
'profiles/'. $profile .'/patterns',
'sites/all/patterns'
);
// allow any module to include patterns too
foreach(module_invoke_all('patterns_directory') as $path) {
if (is_dir($path)) {
$patterns_paths[] = $path .'/patterns';
}
}
// also prepend files folder if it's valid
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (file_check_directory($path)) {
array_unshift($patterns_paths, $path);
}
return $patterns_paths;
}
/**
* Implementation of hook_patterns_directory()
*
* Let us know about where the pattern files are at
*/
function patterns_patterns_directory() {
return drupal_get_path('module', 'patterns');
}
function patterns_save_pattern($pattern, $path = '', $name = '') {
$title = $pattern['info']['title'];
$description = $pattern['info']['description'];
$author = $pattern['info']['author'];
if ($pid = db_result(db_query('SELECT pid FROM {patterns} WHERE name = "%s"', $name))) {
$updated = db_result(db_query('SELECT updated FROM {patterns} WHERE pid = "%d"', $pid));
if (($new_updated = filemtime($path)) > $updated) {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", updated = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $new_updated, $description, $pid);
}
else {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $description, $pid);
}
}
else {
db_query('INSERT INTO {patterns} (name, status, file, updated, enabled, title, description, pattern) VALUES ( "%s", 0, "%s", "%s", 0, "%s", "%s", "%s")', $name, $path, time(), $title, $description, serialize($pattern));
}
}
function patterns_get_pattern($id) {
if (is_numeric($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE pid = "%d"', $id));
}
else if (is_string($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE name = "%s"', $id));
}
if (!$pattern) return FALSE;
// Get the actual data. Data is stored in serialized form in the db.
$pattern->pattern = unserialize($pattern->pattern);
return $pattern;
}
/**
* Check if pattern array contains only allowed keys
*
* @param $pattern
* pattern array obtained by parsing pattern file
* @return
* TRUE when only allowed array keys are found, FALSE otherwise
*
* @todo expand this function to include much more detailed validation
*/
function patterns_validate_pattern($pattern) {
if (empty($pattern)) {
return FALSE;
}
$allowed_keys = array('info', 'modules', 'actions');
$diff = array_diff(array_keys($pattern), $allowed_keys);
return empty($diff) ? TRUE : FALSE;
}
/**
* Return file extensions supported by patterns module
*
* @return array of supported file types
*
* @todo convert this into pluggable system
*/
function patterns_file_types() {
$result = array('xml', 'php');
if (file_exists(drupal_get_path('module', 'patterns') .'/spyc/spyc.php')) {
$result[] = 'yaml';
}
return $result;
}
function patterns_load_yaml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
include_once 'spyc/spyc.php';
$pattern = Spyc::YAMLLoad($path);
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
function patterns_load_string_yaml($source) {
// loading yaml from source doesn't preserve line breaks
// so we need to save it as a file first
$path = file_directory_temp() .'/import.yaml';
file_save_data($source, $path, FILE_EXISTS_REPLACE);
$pattern = patterns_load_yaml($path);
unlink($path);
return $pattern;
}
function patterns_load_xml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
if (!$xml = file_get_contents($path)) {
return FALSE;
}
return patterns_load_string_xml($xml);
}
function patterns_load_string_xml($source) {
$pattern = patterns_from_source($source);
if (empty($pattern) || $pattern['tag'] != 'pattern') {
return FALSE;
}
// Rearrange the data in a nice way for each component.
// Make sure actions are processed differently so order is preserved.
$pattern = patterns_rearrange_data($pattern);
foreach($pattern as $key => $values) {
$pattern[$values['tag']] = $values;
unset($pattern[$values['tag']]['tag']);
unset($pattern[$key]);
// ensure the 'modules' array is collapsed - this is necessary to do if,
// for example, we're including multiple sub-patterns which each include
// their own list of modules
if ('modules' == $values['tag']) {
if (isset($values['module'])) {
if (is_array($values['module'])) {
$pattern['modules'] = $values['module'];
} else {
$pattern['modules'] = array($values['module']);
}
}
}
}
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
/**
* Read and evaluate a php file to return a 'pattern'
*/
function patterns_load_php($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
$pattern = array();
@include($path);
// That should have declared a 'pattern' into current scope.
if (!patterns_validate_pattern($pattern)) {
trigger_error("Failed to evaluate a useful pattern from the input file $path. Pattern did not validate. May have been invalid syntax. ", E_USER_WARNING);
return FALSE;
}
return $pattern;
}
/**
* Create a pattern from an XML data source
*/
function patterns_from_source($xml) {
$parse = drupal_xml_parser_create($xml);
if (!xml_parse_into_struct($parse, $xml, $vals, $index)) {
return false;
}
// Create a multi-dimensional array representing the XML structure
$pattern = current(_patterns_parse_tag($vals));
return $pattern;
}
/**
* Recurse through the values of a parsed xml file to create a
* multi-dimensional representation of the data.
*/
function _patterns_parse_tag($data, &$index = 0) {
$pattern = array();
while (isset($data[$index]) && ($current = $data[$index])) {
$type = $current['type'];
if (isset($current['attributes'])) {
foreach((array)$current['attributes'] as $key => $value) {
$current[strtolower($key)] = $value;
}
}
$current['tag'] = strtolower($current['tag']);
unset($current['type'], $current['level'], $current['attributes']);
if (isset($current['value']) && !trim($current['value']) && $current['value'] != "0") {
unset($current['value']);
}
switch($type) {
case 'open':
$index++;
$current += _patterns_parse_tag($data, $index);
$pattern[] = $current;
break;
case 'close':
$index++;
return $pattern;
break;
case 'complete':
// In order to support more complex/non-standard features we can use serialized data
if (isset($current['attributes']) && $current['attributes']['serialized']) {
$value = unserialize($current['value']);
if (isset($value)) {
$current['value'] = $value;
}
}
// If no value was specified, make sure an empty value is there
if (!isset($current['value'])) {
$current['value'] = '';
}
$pattern[] = $current;
break;
}
$index++;
}
return $pattern;
}
// function patterns_disable_pattern($pid) {
// $form['pid'] = array(
// '#type' => 'value',
// '#value' => $pid
// );
//
// $pattern = patterns_get_pattern($pid);
//
// return confirm_form($form, t('Proceed with disabling pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', '');
// }
function patterns_enable_pattern(&$form_state, $pid) {
$form['pid'] = array(
'#type' => 'value',
'#value' => $pid
);
$options = array(
'first-update' => t('only if disabled or if updated since last run (recommended)'),
'always' => t('always'),
'update' => t('only if updated since last run'),
'first' => t('only if disabled'),
'never' => t("don't run sub-patterns at all"),
);
$form['run-subpatterns'] = array(
'#type' => 'radios',
'#title' => t('Run sub-patterns:'),
'#description' => t("Decide when to run sub-patterns that are called by the currently run pattern. If unsure, stick to recommended setting. Note that your choice won't have any effect if your pattern doesn't contain sub-patterns or if this setting has been defined within the pattern file itself."),
'#options' => $options,
'#default_value' => 'first-update',
);
$disclaimer = t('Please be sure to backup your site before running a pattern. Patterns are not guaranteed to be reversable in case they do not execute well or if unforseen side effects occur.');
$pattern = patterns_get_pattern($pid);
return confirm_form($form, t('Proceed with running pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', $disclaimer);
}
// function patterns_disable_pattern_submit($form_id, $form_values) {
// $pid = $form_values['pid'];
// $pattern = patterns_get_pattern($pid);
//
// if (patterns_execute_pattern($pattern, true, true)) {
// return 'admin/build/patterns';
// }
// }
function patterns_enable_pattern_submit($form, &$form_state) {
$pid = $form_state['values']['pid'];
patterns_load_components();
$pattern = patterns_get_pattern($pid);
patterns_execute_pattern($pattern, $form_state['values']);
$form_state['redirect'] = 'admin/build/patterns';
}
/**
* Execute default configuration for module during the module installation
*
* This function should be called by other modules from
* within their hook_enable() implementation.
* Module should also provide modulename.config file containing PHP array
* with the actions that need to be executed.
*
* @param $module
* name of the module calling the function
*/
function patterns_execute_config($module) {
// since this function is called from hook_enable(), we need to ensure that
// it's executed only at module installation (first time module is enabled)
if (drupal_get_installed_schema_version($module) == SCHEMA_INSTALLED) return;
$path = drupal_get_path('module', $module) .'/'. $module .'.config';
if (file_exists($path)) {
include_once($path);
if (empty($actions)) return;
$pattern = new stdClass();
$pattern->title = t('Default configuration for @module module', array('@module' => $module));
$pattern->status = false;
$pattern->pattern['actions'] = $actions;
patterns_execute_pattern($pattern);
}
}
function patterns_execute_pattern($pattern, $params = array(), $mode = 'batch') {
+ patterns_processing_config_reset();
+
$args = array($pattern, $params);
$function = 'patterns_execute_pattern_'. $mode;
if (!function_exists($function) || !is_object($pattern)) return FALSE;
return call_user_func_array($function, $args);
}
function patterns_execute_pattern_batch($pattern, $params = array()) {
set_time_limit(0);
if (!is_object($pattern)) {
$pattern = patterns_get_pattern($pattern);
if (!$pattern) {
return FALSE;
}
}
$pattern->subpatterns_run_mode = isset($params['run-subpatterns']) ? $params['run-subpatterns'] : FALSE;
$pattern_details = patterns_get_pattern_details($pattern, TRUE);
$modules = $pattern_details['modules'];
$actions = $pattern_details['actions'];
$actions_map = array('patterns' => $pattern_details['info'], 'map' => $pattern_details['actions_map']);
$info = reset($pattern_details['info']);
// If there are no actions or modules, most likely the pattern
// was not created correctly.
if (empty($actions) && empty($modules)) {
drupal_set_message(t('Could not recognize pattern %title, aborting.', array('%title' => $info['title'])), 'error');
return FALSE;
}
$result = patterns_install_modules($modules);
if (!$result['success']) {
drupal_set_message($result['error_message'], 'error');
return FALSE;
}
// lets clear the caches here to ensure that newly added modules
// and future pattern actions work as expected.
module_load_include('inc', 'system', 'system.admin');
$form = $form_state = array();
system_clear_cache_submit($form, $form_state);
$result = patterns_prepare_actions($actions, $actions_map);
if (!$result['success']) {
drupal_set_message($result['error_message'], 'error');
return FALSE;
}
$batch = array(
'title' => t('Processing pattern %pattern', array('%pattern' => $info['title'])),
// 'init_message' => t('Running action @current out of @total', array('@current' => 1, '@total' => count($actions))),
'progress_message' => t('Running action @current out of @total'),
'operations' => array(),
'finished' => 'patterns_batch_finish'
);
for($i=0;$i<count($actions);$i++) {
$batch['operations'][] = array('patterns_batch_actions', array($actions[$i], $i, $actions_map));
}
$_SESSION['patterns_batch_info'] = $pattern_details['info'];
batch_set($batch);
return TRUE;
}
function patterns_install_modules(&$modules) {
$result = array('success' => TRUE);
if (empty($modules)) return $result;
$missing = patterns_check_module_dependencies($modules, TRUE);
if (!empty($missing)) {
$result['success'] = FALSE;
$result['error_message'] = t('Following required modules are missing: %modules', array('%modules' => implode(', ', $missing)));
$result['missing_modules'] = $missing;
return $result;
}
require_once './includes/install.inc';
drupal_install_modules($modules);
module_rebuild_cache();
$result['installed_modules'] = $modules;
return $result;
}
function patterns_locate_action($key, $actions_map) {
$result['key'] = $actions_map['map'][$key]['index'];
$result['title'] = $actions_map['patterns'][$actions_map['map'][$key]['pid']]['title'];
$result['file'] = $actions_map['patterns'][$actions_map['map'][$key]['pid']]['file'];
return $result;
}
function patterns_prepare_actions(&$actions, $actions_map) {
$result = array('success' => TRUE);
if (empty($actions)) return $result;
patterns_load_components();
// Keep a list of what modules handle what tags
$tag_modules = patterns_invoke($empty, 'tag modules');
// TODO Finish basic setup and execution of the 'config' operation
// TODO Make a better streamlined config framework process. For instance collect form_ids
// from here and give the form_id and matching data to the 'build' process
foreach($actions as $key => &$data) {
if (($config = patterns_invoke($actions[$key], 'config')) && !empty($config)) {
patterns_config_data($data, $config);
}
}
// Prepare actions for validation/processing
foreach($actions as $key => &$data) {
patterns_invoke($actions[$key], 'prepare');
}
$errors = array();
// Pre validate tags with their appropriate components
foreach($actions as $key => &$data) {
$action_location = patterns_locate_action($key, $actions_map);
$index = $action_location['key'];
$pattern_title = $action_location['title'];
// $pattern_file = $action_location['file'];
if (!array_key_exists($data['tag'], $tag_modules)) {
$errors[] = t('Action #%num (%tag) in pattern %title: <%tag> is not a valid tag', array('%num' => $index+1, '%tag' => $data['tag'], '%title' => $pattern_title));
}
else {
$error = patterns_invoke($actions[$key], 'pre-validate');
if ($error) {
$errors[] = t('Action #%num (%tag) in pattern %title: !msg', array('!msg' => $error, '%num' => $index+1, '%tag' => $data['tag'], '%title' => $pattern_title));
}
}
}
if (count($errors)) {
$message = t('Errors encountered during pre-processing:') .'<br>'. implode('<br>', $errors);
$result['success'] = FALSE;
$result['error_message'] = $message;
}
return $result;
}
/**
* Execute a batch action
*/
function patterns_batch_actions($action, $place, $actions_map, &$context) {
patterns_load_components();
// Nothing to do if there is no action
if (empty($action)) {
$context['finished'] = 1;
return;
}
// Start a timer. Since we want each action to be its own http request, we need
// to ensure the batch api will decide to do it like that by making each action
// take at least a second to execute
timer_start('patterns_action');
// skip action execution if an error is encountered in some of the previous operations
if (!empty($context['results']['abort'])) return;
$result = patterns_implement_action($action, $context['results']['identifiers'], $place, $actions_map);
if (!$result['success']) {
- // we use 'results' to keep track of errors and abort execution if required
- $context['results']['abort'] = TRUE;
- $context['results']['error_message'] = $result['error_message'];
+ if (!isset($_SESSION[PATTERNS_IGNORE_FAILED_ACTIONS])) {
+ // we use 'results' to keep track of errors and abort execution if required
+ $context['results']['error_message'] .= $result['error_message'];
+ $context['results']['abort'] = TRUE;
+ } else {
+ drupal_set_message('ERROR: ' . $result['error_message'], 'warning');
+ }
}
if (timer_read('patterns_action') < 1000) {
@usleep(1000 - timer_read('patterns_action'));
}
}
/**
* Finish a batch operation
*/
function patterns_batch_finish($success, $results, $operations) {
+
+ patterns_processing_config_reset();
+
$info = $_SESSION['patterns_batch_info'];
if (!isset($results['abort']) || !($results['abort'])) {
foreach ($info as $key => $i) {
drupal_set_message(t('Pattern "@pattern" ran successfully.', array('@pattern' => $i['title'])));
db_query('UPDATE {patterns} SET status = 1, enabled = "%s" WHERE pid = %d', time(), $key);
}
}
else {
$pattern = reset($info);
drupal_set_message(t('Pattern "@pattern" ran with the errors. Check the error messages to get more details.', array('@pattern' => $pattern['title'])));
drupal_set_message($results['error_message'], 'error');
}
unset($_SESSION['patterns_batch_info']);
drupal_flush_all_caches();
}
/**
* Setup and run an action
*/
function patterns_implement_action($action, &$identifiers, $place = 0, $actions_map = NULL) {
patterns_set_error_handler();
$result = array('success' => TRUE);
// Prepare actions for processing, ensure smooth pattern executions, and return form ids for execution
$return = patterns_invoke($action, 'form_id');
// If prepare removed the data, dont continue with this action
if (!$action || !$return) {
return $result;
}
if (is_string($return)) {
$form_ids = array($return);
}
else if ($return) {
$form_ids = $return;
}
$action_descriptions = patterns_invoke($action, 'actions');
$action_location = patterns_locate_action($place, $actions_map);
$index = $action_location['key'] + 1;
$pattern_title = $action_location['title'];
$pattern_file = $action_location['file'];
// Build the action
foreach($form_ids as $form_id) {
$clone = $action;
$action_description = isset($action_descriptions[$form_id]) ? $action_descriptions[$form_id] : t('System: Execute form');
$result['action_descriptions'][$place][] = $action_description;
// If tokens are enabled, apply tokens to the action values
// before processing
if (module_exists('token')) {
_patterns_recurse_tokens($clone, $identifiers);
//array_walk($clone, '_patterns_replace_tokens', $identifiers);
}
$error = patterns_invoke($clone, 'validate', $form_id);
if ($message = patterns_error_get_last('validate', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
if ($error) {
$message = t('An error occured while validating action #%num (%action) in %title pattern', array('%num' => $index, '%action' => $action_description, '%title' => $pattern_title));
$result['error_message'] = $message .'<br>'. $error;
$result['success'] = FALSE;
return $result;
}
// Get the form data for the action. This can either just be the form values,
// or it can be the full form_state object
$form_obj = patterns_invoke($clone, 'build', $form_id);
if ($message = patterns_error_get_last('build', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
// Dont execute the action if a string was returned, indicating the pattern component
// most likely handled the action on its own and this is the message to display.
if (is_string($form_obj)) {
drupal_set_message($form_obj);
}
else {
// We check for the 'storage' and 'submitted' values in the object to see
// if it is a form_state instead of form_values. There could be a better way
// to do this.
if (array_key_exists('submitted', (array)$form_obj) && array_key_exists('storage', (array)$form_obj)) {
$action_state = $form_obj;
}
else {
$action_state = array(
'storage' => null,
'submitted' => false,
'values' => $form_obj
);
}
// Get any extra parameters required for the action
$params = patterns_invoke($clone, 'params', $form_id, $action_state);
if ($message = patterns_error_get_last('params', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
// A single, simple value can be returned as a parameter, which is then
// put into an array here.
if (isset($params) && !is_array($params)) {
$params = array($params);
}
// Execute action
patterns_execute_action($form_id, $action_state, $params);
if ($message = patterns_error_get_last('execute', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
if ($errors = form_get_errors()) {
$result['error_message'] = t('Above error(s) occured while executing action #%num (%action) in %title pattern. Error location(s) are: %errors', array('%num' => $index, '%action' => $action_description, '%title' => $pattern_title, '%errors' => str_replace('][', '->', implode(', ', array_keys($errors)))));
$result['success'] = FALSE;
return $result;
}
// Let a component cleanup after each action
patterns_invoke($clone, 'cleanup', $form_id, $action_state);
if ($message = patterns_error_get_last('cleanup', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
}
// Clear the cache in case it causes problems
cache_clear_all();
// Rebuild the menu
// TODO Should this go at the end only when a pattern successfully runs?
variable_set('menu_rebuild_needed', true);
}
// Get any primary identifiers from the action for further actions to take advantage of
$id = null;
$id = patterns_invoke($clone, 'identifier', $form_id, $action_state);
if (isset($id)) {
$index = isset($clone['action_label']) ? $clone['action_label'] : $place+1;
$identifiers[$index] = $id;
}
patterns_restore_error_handler();
return $result;
}
/**
* Execute an action
*/
function patterns_execute_action($form_id, &$form_state, $params) {
// Make sure we always have a clear cache for everything
// Beware - this direct database access needs to be db-prefix-safe!
global $db_prefix;
$result = db_query('SHOW TABLES LIKE "{cache}_%"');
while ($table = db_fetch_array($result)) {
// Remove the db prefix if any. cache_clear_all() will put it back again.
$table = substr(current($table), strlen($db_prefix));
cache_clear_all(null, $table);
}
$args = array($form_id, &$form_state);
if (is_array($params)) {
$args = array_merge($args, $params);
}
patterns_executing(true);
// If we are in batch mode, trick the form api to think
// otherwise to avoid potential problems
$batch =& batch_get();
$batch_clone = $batch;
$batch = null;
//$form = call_user_func_array('drupal_retrieve_form', $args);
//$form['#post'] = $values;
//$return = drupal_process_form($form_id, $form);
//dpm($args);
// drupal_execute fails to keep $form_state in-sync through the
// whole FAPI process. Issue http://drupal.org/node/346244
//$return = call_user_func_array('drupal_execute', $args);
// Fix some parts of the #post values based on the original form
patterns_sync_form_values($args);
// Copy of drupal_execute until above issue is fixed
$form = call_user_func_array('drupal_retrieve_form', $args);
$form['#post'] = $form_state['values'];
drupal_prepare_form($form_id, $form, $form_state);
// If you call drupal_validate_form() on the same form more
// than once per page request, validation is not performed
// on any but the first call.
// see issue: http://drupal.org/node/260934
// drupal_process_form($form_id, $form, $form_state);
// Until above issue is fixed we use our own implementation
// of drupal_process_form() and drupal_validate_form().
_patterns_process_form($form_id, $form, $form_state);
patterns_executing(false);
$batch = $batch_clone;
return $return;
}
function patterns_executing($b = null) {
static $executing = false;
if (is_bool($b)) {
$executing = $b;
}
return $executing;
}
function patterns_rearrange_data($pattern) {
foreach($pattern as $key => $value) {
if (is_string($key)) {
unset($pattern[$key]);
}
else {
if ($value['tag'] == 'actions') {
$pattern[$key] = patterns_rearrange_data($value);
$pattern[$key]['tag'] = 'actions';
}
else {
$pattern[$key] = _patterns_rearrange_data($value);
}
}
}
return $pattern;
}
/**
* Return an array with detailed information about the pattern
*/
function patterns_get_pattern_details($pattern, $recursive = FALSE, &$pids = array()) {
// prevent infinite recursion
if (in_array($pattern->pid, $pids)) return array();
$pids[$pattern->pid] = $pattern->pid;
$actions = !empty($pattern->pattern['actions']) ? $pattern->pattern['actions'] : array();
$modules = !empty($pattern->pattern['modules']) ? $pattern->pattern['modules'] : array();
$patterns[$pattern->pid] = (array)$pattern;
$patterns[$pattern->pid] = array_merge($patterns[$pattern->pid], $patterns[$pattern->pid]['pattern']['info']);
unset($patterns[$pattern->pid]['pattern']);
if ($recursive) {
$result = array('modules' => $modules, 'info' => $patterns);
foreach($actions as $key => $action) {
if ($action['tag'] == 'pattern') {
// determine pattern name
if (!empty($action['value'])) {
$name = $action['value'];
}
elseif (!empty($action['name'])) {
$name = $action['name'];
}
if (!$p = patterns_get_pattern($name)) {
// just give a warning and try to continue
drupal_set_message(t('Action #%key in %file: Pattern %pattern not found.<br>Pattern execution will try to continue without it.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'warning');
continue;
}
// Decide if sub-pattern needs to be run based on the mode defined within the pattern or selected in UI at the time of form submission
// @TODO: UI setting should be able to override a setting defined within the pattern
$modes = array('first-update', 'always', 'update', 'first', 'never');
if (!empty($action['run']) && in_array($action['run'], $modes)) {
$mode = $action['run'];
}
else {
$mode = $pattern->subpatterns_run_mode;
}
switch ($mode) {
case 'never':
// don't run sub-pattern
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to be skipped.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
break;
case 'first':
// Only run on first run
if ($p->status) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on the first run.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'update':
// Only run on pattern update
if ($p->enabled >= $p->updated) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on pattern update.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'first-update':
// Only run on first run or pattern update
if ($p->status && $p->enabled >= $p->updated) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on first run or update.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'always':
default:
// Run always
break;
}
$a = patterns_get_pattern_details($p, TRUE, $pids);
if (is_array($a) && empty($a)) {
// An empty array is returned on infinite recursion detection
drupal_set_message(t('Action #%key in %file: Infinite recursion detected while attempting to run pattern %pattern.<br>Pattern execution will try to continue without it.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'warning');
continue;
}
// array_merge doesn't preserve numeric array keys
// so we handle 'info' separately
$info = $result['info'];
$result = array_merge_recursive($result, $a);
$result['info'] = $info + $a['info'];
}
else {
$result['actions'][] = $action;
$result['actions_map'][] = array(
'pid' => $pattern->pid,
'index' => $key,
);
}
}
$result['modules'] = array_merge(array_unique($result['modules']));
// Remove pid from recursion stack
//unset($pids[$pattern->pid]);
return $result;
}
// Remove pid from recursion stack
//unset($pids[$pattern->pid]);
return array('actions' => $actions, 'modules' => $modules, 'info' => $patterns);
}
//function patterns_process_modules($modules, $op = 'enable') {
// // Enable at the beginning of the pattern. Disable at the end.
// for($i=0;$module=$modules[$i];$i++) {
// if (($op == 'enable' && $module['delete']) || ($op == 'disable' && !$module['delete'])) {
// unset($modules[$i]);
// }
// }
//
// patterns_invoke($empty, 'tag modules');
// $error = patterns_invoke($modules, 'pre-validate');
//
// // Error validating modules
// if ($error) {
// return $error;
// }
//
// patterns_invoke($modules, 'prepare');
//}
function patterns_invoke(&$data, $op, $form_id = null, &$a = null) {
static $tag_modules;
if (!is_array($tag_modules) || $op == 'tag modules') {
// Get a list of tags and their modules
foreach(module_implements('patterns') as $module) {
$tags = module_invoke($module, 'patterns', 'tags');
foreach($tags as $tag => $value) {
if (is_array($value)) {
$tag_modules[$tag] = $module;
}
else {
$tag_modules[$value] = $module;
}
}
}
}
// If you just want the modules list
if ($op == 'tag modules') {
return $tag_modules;
}
$tag = $data['tag'];
unset($data['tag']);
$module = $tag_modules[$tag];
$func = $module .'_patterns';
if (function_exists($func)) {
if ($form_id) {
$return = $func($op, $form_id, $data, $a);
}
else {
$return = $func($op, $tag, $data, $a);
}
}
$data['tag'] = $tag;
return $return;
}
function _patterns_rearrange_data($data, $parent = '') {
$numeric = array();
$count=0;
foreach($data as $key => $value) {
##! Patch to ensure we don't skips tags containing nested data
if (!isset($value['value']) && !isset($value['tag']))
continue;
if (isset($value['value'])) {
if ($value['value'] == 'false') {
$value['value'] = false;
}
else if ($value['value'] == 'true') {
$value['value'] = true;
}
}
if (is_numeric($key) && is_array($value) && count($value) == 2 && isset($value['tag']) && isset($value['value'])) {
unset($data[$key]);
if (isset($data[$value['tag']])) {
$numeric[] = $value['tag'];
$data[$count++] = $data[$value['tag']];
$data[$count++] = $value['value'];
unset($data[$value['tag']]);
}
else if (in_array($value['tag'], $numeric)) {
$data[$count++] = $value['value'];
}
else {
$data[$value['tag']] = $value['value'];
}
}
else if (is_numeric($key)) {
$tag = $value['tag'];
unset($value['tag']);
$data[$tag][] = _patterns_rearrange_data($value, $tag);
unset($data[$key]);
}
}
foreach($data as $key => $value) {
if (is_array($value) && count($value) == 1 && $value[0]) {
$data[$key] = $data[$key][0];
}
}
return $data;
}
function patterns_form_alter(&$form, &$form_state, $form_id) {
if (user_access('administer patterns') && variable_get('patterns_form_helper', FALSE)) {
$form['#after_build'][] = 'patterns_form_helper';
}
if (patterns_executing()) {
// Ensure that parent and related dropdowns display all the terms
// including those created during current pattern execution.
// Without this, those terms would be omitted due to the static
// caching within taxonomy_get_tree().
$form_ids = array('taxonomy_form_term');
if (in_array($form_id, $form_ids)) {
$tid = $form['#term']['tid'];
$vid = $form['#vocabulary']['vid'];
$parent = array_keys(taxonomy_get_parents($tid));
$children = _patterns_taxonomy_get_tree($vid, $tid);
// A term can't be the child of itself, nor of its children.
foreach ($children as $child) {
$exclude[] = $child->tid;
}
$exclude[] = $tid;
$form['advanced']['parent'] = _patterns_taxonomy_term_select(t('Parents'), 'parent', $parent, $vid, t('Parent terms') .'.', 1, '<'. t('root') .'>', $exclude);
$form['advanced']['relations'] = _patterns_taxonomy_term_select(t('Related terms'), 'relations', array_keys(taxonomy_get_related($tid)), $vid, NULL, 1, '<'. t('none') .'>', array($tid));
}
// Ensure that parent item dropdown displays all the menu items
// including those created during current pattern execution.
// Without this, those menu items would be omitted due to the
// static caching within menu_tree_all_data().
$form_ids = array('menu_edit_item');
if (in_array($form_id, $form_ids)) {
if (empty($form['menu']['#item'])) {
@@ -2696,513 +2710,602 @@ function patterns_array_fetch($path, &$data, $context = null) {
// Return the list of matches containing references to their respective data objects
return $matches;
}
/**
* Helper function to create a context array based on the supplied object
* Supplying a parent object will set the parent for this context
*/
function _patterns_array_context(&$obj, &$current = null) {
// If a current context is set, use it's parent and key values
if (!($trace = $current['trace'])) {
$trace = array();
}
if (!($key = $current['key'])) {
$key = null;
}
if (!($parent = &$current['parent'])) {
$parent = null;
}
$context = array('trace' => $trace, 'key' => $key, 'item' => &$obj, 'parent' => &$parent);
$refs = array(&$context);
while (!empty($refs)) {
$ref = &$refs[0];
$parent = &$ref['item'];
array_splice($refs, 0, 1);
if (is_array($parent) && !empty($parent)) {
$i = 0;
foreach($parent as $index => &$child) {
// TODO possible optimizations can be done here (with the parent trace)
$ref[$i] = array('trace' => _patterns_array_trace($ref), 'key' => $index, 'item' => &$child, 'parent' => &$ref);
array_unshift($refs, '');
$refs[0] = &$ref[$i++];
}
}
}
return $context;
}
/**
* Helper function to filter values of the list of matches
*/
function _patterns_array_filter(&$matches, $operator, $value = null) {
for($i=count($matches)-1;$i>=0;$i--) {
$match = &$matches[$i];
switch($operator) {
case '=':
if ($match['item'] != $value) {
array_splice($matches, $i, 1);
}
break;
}
}
}
/**
* Helper function to create a list of parent keys given a context item
*/
function _patterns_array_trace($obj) {
// Loop back up through the parents to fill in the trace value.
$up = &$obj;
$trace = array();
while(isset($up['parent'])) {
array_unshift($trace, $up['key']);
$up = &$up['parent'];
}
return $trace;
}
/**
* Check if all the module dependencies are available
*
* @param $modules
* array of module names
* @param $update_list
* if TRUE, add all the dependecies to pattern's module list
* @return
* empty array if all dependencies are available
* array of missing module's names if some dependencies are not available
*
*/
function patterns_check_module_dependencies(&$modules, $update_list = FALSE) {
if (empty($modules)) return array();
$modules_info = module_rebuild_cache();
$result = array();
$dependencies = array();
foreach($modules as $module) {
$module = is_array($module) ? $module['value'] : $module;
if (array_key_exists($module, $modules_info)) {
// check also for module's dependencies
foreach ($modules_info[$module]->info['dependencies'] as $dependency) {
if (array_key_exists($dependency, $modules_info)) {
$dependencies[] = $dependency;
}
else {
$result[] = $dependency;
}
}
}
else {
$result[] = $module;
}
}
if ($update_list && empty($result) && !empty($dependencies)) {
$modules = array_unique(array_merge($modules, $dependencies));
}
return $result;
}
function patterns_set_error_handler() {
// set custom error handler
set_error_handler('patterns_error_handler');
// trigger dummy error
// this will be used as a refrence to determine if any real error
// occured during the pattern execution
@trigger_error('patterns_error');
}
function patterns_restore_error_handler() {
restore_error_handler();
}
/**
* Custom error handler used only during patterns execution
* in order to catch and properly handle PHP errors.
* Based on drupal_error_handler().
*/
function patterns_error_handler($errno, $message, $filename, $line, $context) {
if ($errno & (E_ALL ^ E_NOTICE)) {
$types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning', 4096 => 'recoverable fatal error');
// For database errors, we want the line number/file name of the place that
// the query was originally called, not _db_query().
if (isset($context[DB_ERROR])) {
$backtrace = array_reverse(debug_backtrace());
// List of functions where SQL queries can originate.
$query_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
// Determine where query function was called, and adjust line/file
// accordingly.
foreach ($backtrace as $index => $function) {
if (in_array($function['function'], $query_functions)) {
$line = $backtrace[$index]['line'];
$filename = $backtrace[$index]['file'];
break;
}
}
}
// 'patterns_error' is not a real error and should be skipped
if ($message != 'patterns_error') {
watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
patterns_error_set_last(array('message' => $message, 'type' => $errno, 'file' => $filename, 'line' => $line));
}
}
return TRUE;
}
function patterns_error_set_last($error = NULL) {
static $last_error = array();
if (isset($error)) {
$last_error = $error;
}
return $last_error;
}
/**
* Check and report PHP errors during patterns execution
*
* @param $op
* operation within hook_patterns() during which error occured
* @param $key
* number of the action currently proccessed
* @param $description
* description of the current action
* @param $pattern_title
* title of the pattern currently proccessed
* @param $pattern_file
* path to pattern file currently proccessed
* @return
* error message if new error encountered
* FALSE if there are no new errors
*
*/
function patterns_error_get_last($op, $key, $description, $pattern_title, $pattern_file) {
$error = patterns_error_set_last();
if (!empty($error) && $error['message'] != 'patterns_error') {
$types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning', 4096 => 'recoverable fatal error');
$php_error_message = $types[$error['type']] .': '. $error['message'] .' in '. $error['file'] .' on line '. $error['line'] .'.';
$message = t('Pattern %title (%pattern_file)<br>Action #%key: %description (op "%op")<br>PHP error occured:<br>%error', array('%key' => $key, '%title' => $pattern_title, '%op' => $op, '%description' => $description, '%error' => $php_error_message, '%pattern_file' => $pattern_file));
return $message;
}
return FALSE;
}
/**
* Custom implementation of drupal_process_form()
*
* Enables validation to be performed for each executed form
* by calling our custom _patterns_validate_form() function
* see issue: http://drupal.org/node/260934
*/
function _patterns_process_form($form_id, &$form, &$form_state) {
$form_state['values'] = array();
$form = form_builder($form_id, $form, $form_state);
// Only process the form if it is programmed or the form_id coming
// from the POST data is set and matches the current form_id.
if ((!empty($form['#programmed'])) || (!empty($form['#post']) && (isset($form['#post']['form_id']) && ($form['#post']['form_id'] == $form_id)))) {
_patterns_validate_form($form_id, $form, $form_state);
// form_clean_id() maintains a cache of element IDs it has seen,
// so it can prevent duplicates. We want to be sure we reset that
// cache when a form is processed, so scenerios that result in
// the form being built behind the scenes and again for the
// browser don't increment all the element IDs needlessly.
form_clean_id(NULL, TRUE);
if ((!empty($form_state['submitted'])) && !form_get_errors() && empty($form_state['rebuild'])) {
$form_state['redirect'] = NULL;
form_execute_handlers('submit', $form, $form_state);
// We'll clear out the cached copies of the form and its stored data
// here, as we've finished with them. The in-memory copies are still
// here, though.
if (variable_get('cache', CACHE_DISABLED) == CACHE_DISABLED && !empty($form_state['values']['form_build_id'])) {
cache_clear_all('form_'. $form_state['values']['form_build_id'], 'cache_form');
cache_clear_all('storage_'. $form_state['values']['form_build_id'], 'cache_form');
}
// If batches were set in the submit handlers, we process them now,
// possibly ending execution. We make sure we do not react to the batch
// that is already being processed (if a batch operation performs a
// drupal_execute).
if ($batch =& batch_get() && !isset($batch['current_set'])) {
// The batch uses its own copies of $form and $form_state for
// late execution of submit handers and post-batch redirection.
$batch['form'] = $form;
$batch['form_state'] = $form_state;
$batch['progressive'] = !$form['#programmed'];
batch_process();
// Execution continues only for programmatic forms.
// For 'regular' forms, we get redirected to the batch processing
// page. Form redirection will be handled in _batch_finished(),
// after the batch is processed.
}
// If no submit handlers have populated the $form_state['storage']
// bundle, and the $form_state['rebuild'] flag has not been set,
// we're finished and should redirect to a new destination page
// if one has been set (and a fresh, unpopulated copy of the form
// if one hasn't). If the form was called by drupal_execute(),
// however, we'll skip this and let the calling function examine
// the resulting $form_state bundle itself.
if (!$form['#programmed'] && empty($form_state['rebuild']) && empty($form_state['storage'])) {
drupal_redirect_form($form, $form_state['redirect']);
}
}
}
}
/**
* Custom implementation of drupal_validate_form()
*
* Removed static variable that prevented same form_id to be
* validated more then once during a single page request
*/
function _patterns_validate_form($form_id, $form, &$form_state) {
// If the session token was set by drupal_prepare_form(), ensure that it
// matches the current user's session.
if (isset($form['#token'])) {
if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
// Setting this error will cause the form to fail validation.
form_set_error('form_token', t('Validation error, please try again. If this error persists, please contact the site administrator.'));
}
}
_form_validate($form, $form_state, $form_id);
}
/**
* Custom implementation of Drupal's _taxonomy_term_select()
*
* Used to override static caching in taxonmy_get_tree()
* which is preventing terms added during patterns execution
* to be included in parents and relations dropdowns and
* causes validation errors.
* Hopefully, we can find better solution for this.
*/
function _patterns_taxonomy_term_select($title, $name, $value, $vocabulary_id, $description, $multiple, $blank, $exclude = array()) {
$tree = _patterns_taxonomy_get_tree($vocabulary_id);
$options = array();
if ($blank) {
$options[''] = $blank;
}
if ($tree) {
foreach ($tree as $term) {
if (!in_array($term->tid, $exclude)) {
$choice = new stdClass();
$choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
$options[] = $choice;
}
}
}
return array('#type' => 'select',
'#title' => $title,
'#default_value' => $value,
'#options' => $options,
'#description' => $description,
'#multiple' => $multiple,
'#size' => $multiple ? min(9, count($options)) : 0,
'#weight' => -15,
'#theme' => 'taxonomy_term_select',
);
}
/**
* Custom implementation of Drupal's taxonomy_get_tree()
*
* Removed static caching.
* New terms may be created during patterns execution and
* static caching prevents them from being returned in
* all subsequent calls to taxonomy_get_tree() during
* the current pattern execution (within current page request)
*/
function _patterns_taxonomy_get_tree($vid, $parent = 0, $depth = -1, $max_depth = NULL) {
$depth++;
$children[$vid] = array();
$result = db_query(db_rewrite_sql('SELECT t.tid, t.*, parent FROM {term_data} t INNER JOIN {term_hierarchy} h ON t.tid = h.tid WHERE t.vid = %d ORDER BY weight, name', 't', 'tid'), $vid);
while ($term = db_fetch_object($result)) {
$children[$vid][$term->parent][] = $term->tid;
$parents[$vid][$term->tid][] = $term->parent;
$terms[$vid][$term->tid] = $term;
}
$max_depth = (is_null($max_depth)) ? count($children[$vid]) : $max_depth;
$tree = array();
if (!empty($children[$vid][$parent])) {
foreach ($children[$vid][$parent] as $child) {
if ($max_depth > $depth) {
$term = drupal_clone($terms[$vid][$child]);
$term->depth = $depth;
// The "parent" attribute is not useful, as it would show one parent only.
unset($term->parent);
$term->parents = $parents[$vid][$child];
$tree[] = $term;
if (!empty($children[$vid][$child])) {
$tree = array_merge($tree, _patterns_taxonomy_get_tree($vid, $child, $depth, $max_depth));
}
}
}
}
return $tree;
}
/**
* Custom implementation of Drupal's taxonomy_form()
*
* Used to override static caching for taxonomy terms on node edit form.
*/
function _patterns_taxonomy_form($vid, $value = 0, $help = NULL, $name = 'taxonomy') {
$vocabulary = taxonomy_vocabulary_load($vid);
$help = ($help) ? $help : $vocabulary->help;
if (!$vocabulary->multiple) {
$blank = ($vocabulary->required) ? t('- Please choose -') : t('- None selected -');
}
else {
$blank = ($vocabulary->required) ? 0 : t('- None -');
}
return _patterns_taxonomy_term_select(check_plain($vocabulary->name), $name, $value, $vid, $help, intval($vocabulary->multiple), $blank);
}
/**
* Custom implementation of Drupal's menu_parent_options()
*
* Used to override static caching in menu_tree_all_data()
* which is preventing menu items created during patterns execution
* to be included in 'parent item' dropdown and causes validation errors.
* Hopefully, we can find better solution for this.
*/
function _patterns_menu_parent_options($menus, $item) {
// The menu_links table can be practically any size and we need a way to
// allow contrib modules to provide more scalable pattern choosers.
// hook_form_alter is too late in itself because all the possible parents are
// retrieved here, unless menu_override_parent_selector is set to TRUE.
if (variable_get('menu_override_parent_selector', FALSE)) {
return array();
}
// If the item has children, there is an added limit to the depth of valid parents.
if (isset($item['parent_depth_limit'])) {
$limit = $item['parent_depth_limit'];
}
else {
$limit = _menu_parent_depth_limit($item);
}
foreach ($menus as $menu_name => $title) {
$tree = _patterns_menu_tree_all_data($menu_name, NULL);
$options[$menu_name .':0'] = '<'. $title .'>';
_menu_parents_recurse($tree, $menu_name, '--', $options, $item['mlid'], $limit);
}
return $options;
}
/**
* Custom implementation of Drupal's menu_tree_all_data()
*
* Removed static caching.
* New menu items may be created during pattern execution and
* static caching prevents them from being returned in
* all subsequent calls to menu_tree_all_data() during
* the current pattern execution (within current page request)
*/
function _patterns_menu_tree_all_data($menu_name = 'navigation', $item = NULL) {
$tree = array();
// Use $mlid as a flag for whether the data being loaded is for the whole tree.
$mlid = isset($item['mlid']) ? $item['mlid'] : 0;
// Generate a cache ID (cid) specific for this $menu_name and $item.
$cid = 'links:'. $menu_name .':all-cid:'. $mlid;
// If the static variable doesn't have the data, check {cache_menu}.
$cache = cache_get($cid, 'cache_menu');
if ($cache && isset($cache->data)) {
// If the cache entry exists, it will just be the cid for the actual data.
// This avoids duplication of large amounts of data.
$cache = cache_get($cache->data, 'cache_menu');
if ($cache && isset($cache->data)) {
$data = $cache->data;
}
}
// If the tree data was not in the cache, $data will be NULL.
if (!isset($data)) {
// Build and run the query, and build the tree.
if ($mlid) {
// The tree is for a single item, so we need to match the values in its
// p columns and 0 (the top level) with the plid values of other links.
$args = array(0);
for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
$args[] = $item["p$i"];
}
$args = array_unique($args);
$placeholders = implode(', ', array_fill(0, count($args), '%d'));
$where = ' AND ml.plid IN ('. $placeholders .')';
$parents = $args;
$parents[] = $item['mlid'];
}
else {
// Get all links in this menu.
$where = '';
$args = array();
$parents = array();
}
array_unshift($args, $menu_name);
// Select the links from the table, and recursively build the tree. We
// LEFT JOIN since there is no match in {menu_router} for an external
// link.
$data['tree'] = menu_tree_data(db_query("
SELECT m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.title, m.title_callback, m.title_arguments, m.type, m.description, ml.*
FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path
WHERE ml.menu_name = '%s'". $where ."
ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC", $args), $parents);
$data['node_links'] = array();
menu_tree_collect_node_links($data['tree'], $data['node_links']);
// Cache the data, if it is not already in the cache.
$tree_cid = _menu_tree_cid($menu_name, $data);
if (!cache_get($tree_cid, 'cache_menu')) {
cache_set($tree_cid, $data, 'cache_menu');
}
// Cache the cid of the (shared) data using the menu and item-specific cid.
cache_set($cid, $tree_cid, 'cache_menu');
}
// Check access for the current user to each item in the tree.
menu_tree_check_access($data['tree'], $data['node_links']);
$tree[$cid] = $data['tree'];
return $tree[$cid];
}
function patterns_debug_batch($var = null) {
$var = print_r($var, true);
$var = str_replace(" ", ' ', $var);
$var = str_replace("\n", "<br />", $var);
print drupal_to_js(array('status' => 0, 'data' => $var));
exit;
-}
\ No newline at end of file
+}
+
+
+// ----------------------------------------------------------------------- //
+// Patterns config tags
+// ----------------------------------------------------------------------- //
+
+// Patterns configuration directives
+define('PATTERNS_IGNORE_FAILED_ACTIONS','ignore-failed-actions');
+
+function patterns_patterns($op, $id = null, &$data = null) {
+ switch($op) {
+ // Return the valid tags that this component can prepare and process
+ case 'tags':
+ return array('patterns-config');
+ break;
+
+ // Return a list of forms/actions this component can handle
+ case 'actions':
+ return array(
+ 'patterns_processing_config_form' => t('Patterns config: Configure the patterns processor'),
+ );
+ break;
+
+ // Return a summary of an action
+ case 'summary':
+ return t('Setting processing flag "%name" to value "%value"', array('%name' => $data['name'], $data['value']));
+ break;
+
+ // Pre validate actions
+ case 'pre-validate':
+ if (!isset($data['name']) || !isset($data['value'])) {
+ return t('Both "name" and "value" are required attributes.');
+ }
+ if (!in_array($data['name'], array(PATTERNS_IGNORE_FAILED_ACTIONS))) {
+ return t('Unrecognized processing directive: %name', array('%name' => $data['name']));
+ }
+ break;
+
+ // Return the form_id('s) for each action
+ case 'form_id':
+ return 'patterns_processing_config_form';
+
+ break;
+
+ // Prepare for valid processing of this type of component
+ case 'build':
+ return $data;
+ break;
+
+ // Build a patterns actions and parameters
+ case 'params':
+ return array();
+ break;
+
+ }
+}
+
+function patterns_processing_config_form($form_state) {
+ $form = array();
+ $form['name'] = array( '#type' => 'textfield' );
+ $form['value'] = array( '#type' => 'textfield' );
+ return $form;
+}
+
+function patterns_processing_config_form_submit($form, &$form_state) {
+ switch ($form_state['values']['name']) {
+ case PATTERNS_IGNORE_FAILED_ACTIONS:
+ if (1 == $form_state['values']['value']) {
+ $_SESSION[PATTERNS_IGNORE_FAILED_ACTIONS] = TRUE;
+ patterns_processing_config_show_msg(t('%flag turned ON',array('%flag' => PATTERNS_IGNORE_FAILED_ACTIONS)));
+ } else {
+ unset($_SESSION[PATTERNS_IGNORE_FAILED_ACTIONS]);
+ patterns_processing_config_show_msg(t('%flag turned OFF',array('%flag' => PATTERNS_IGNORE_FAILED_ACTIONS)));
+ }
+ break;
+ }
+}
+
+function patterns_processing_config_show_msg($msg) {
+ drupal_set_message("PATTERNS CONFIG: $msg", 'warning');
+}
+
+/**
+ * Reset all processing configuration.
+ */
+function patterns_processing_config_reset() {
+ unset($_SESSION[PATTERNS_IGNORE_FAILED_ACTIONS]);
+}
+
|
hiddentao/patterns2
|
94fb87f6455bf597d4a0db8ecc82e548e9981372
|
Made the Patterns form synhronization code a little bit more robust.
|
diff --git a/patterns.module b/patterns.module
index 06e8e27..f892a89 100644
--- a/patterns.module
+++ b/patterns.module
@@ -1882,1025 +1882,1025 @@ function patterns_get_pattern_details($pattern, $recursive = FALSE, &$pids = arr
case 'update':
// Only run on pattern update
if ($p->enabled >= $p->updated) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on pattern update.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'first-update':
// Only run on first run or pattern update
if ($p->status && $p->enabled >= $p->updated) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on first run or update.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'always':
default:
// Run always
break;
}
$a = patterns_get_pattern_details($p, TRUE, $pids);
if (is_array($a) && empty($a)) {
// An empty array is returned on infinite recursion detection
drupal_set_message(t('Action #%key in %file: Infinite recursion detected while attempting to run pattern %pattern.<br>Pattern execution will try to continue without it.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'warning');
continue;
}
// array_merge doesn't preserve numeric array keys
// so we handle 'info' separately
$info = $result['info'];
$result = array_merge_recursive($result, $a);
$result['info'] = $info + $a['info'];
}
else {
$result['actions'][] = $action;
$result['actions_map'][] = array(
'pid' => $pattern->pid,
'index' => $key,
);
}
}
$result['modules'] = array_merge(array_unique($result['modules']));
// Remove pid from recursion stack
//unset($pids[$pattern->pid]);
return $result;
}
// Remove pid from recursion stack
//unset($pids[$pattern->pid]);
return array('actions' => $actions, 'modules' => $modules, 'info' => $patterns);
}
//function patterns_process_modules($modules, $op = 'enable') {
// // Enable at the beginning of the pattern. Disable at the end.
// for($i=0;$module=$modules[$i];$i++) {
// if (($op == 'enable' && $module['delete']) || ($op == 'disable' && !$module['delete'])) {
// unset($modules[$i]);
// }
// }
//
// patterns_invoke($empty, 'tag modules');
// $error = patterns_invoke($modules, 'pre-validate');
//
// // Error validating modules
// if ($error) {
// return $error;
// }
//
// patterns_invoke($modules, 'prepare');
//}
function patterns_invoke(&$data, $op, $form_id = null, &$a = null) {
static $tag_modules;
if (!is_array($tag_modules) || $op == 'tag modules') {
// Get a list of tags and their modules
foreach(module_implements('patterns') as $module) {
$tags = module_invoke($module, 'patterns', 'tags');
foreach($tags as $tag => $value) {
if (is_array($value)) {
$tag_modules[$tag] = $module;
}
else {
$tag_modules[$value] = $module;
}
}
}
}
// If you just want the modules list
if ($op == 'tag modules') {
return $tag_modules;
}
$tag = $data['tag'];
unset($data['tag']);
$module = $tag_modules[$tag];
$func = $module .'_patterns';
if (function_exists($func)) {
if ($form_id) {
$return = $func($op, $form_id, $data, $a);
}
else {
$return = $func($op, $tag, $data, $a);
}
}
$data['tag'] = $tag;
return $return;
}
function _patterns_rearrange_data($data, $parent = '') {
$numeric = array();
$count=0;
foreach($data as $key => $value) {
##! Patch to ensure we don't skips tags containing nested data
if (!isset($value['value']) && !isset($value['tag']))
continue;
if (isset($value['value'])) {
if ($value['value'] == 'false') {
$value['value'] = false;
}
else if ($value['value'] == 'true') {
$value['value'] = true;
}
}
if (is_numeric($key) && is_array($value) && count($value) == 2 && isset($value['tag']) && isset($value['value'])) {
unset($data[$key]);
if (isset($data[$value['tag']])) {
$numeric[] = $value['tag'];
$data[$count++] = $data[$value['tag']];
$data[$count++] = $value['value'];
unset($data[$value['tag']]);
}
else if (in_array($value['tag'], $numeric)) {
$data[$count++] = $value['value'];
}
else {
$data[$value['tag']] = $value['value'];
}
}
else if (is_numeric($key)) {
$tag = $value['tag'];
unset($value['tag']);
$data[$tag][] = _patterns_rearrange_data($value, $tag);
unset($data[$key]);
}
}
foreach($data as $key => $value) {
if (is_array($value) && count($value) == 1 && $value[0]) {
$data[$key] = $data[$key][0];
}
}
return $data;
}
function patterns_form_alter(&$form, &$form_state, $form_id) {
if (user_access('administer patterns') && variable_get('patterns_form_helper', FALSE)) {
$form['#after_build'][] = 'patterns_form_helper';
}
if (patterns_executing()) {
// Ensure that parent and related dropdowns display all the terms
// including those created during current pattern execution.
// Without this, those terms would be omitted due to the static
// caching within taxonomy_get_tree().
$form_ids = array('taxonomy_form_term');
if (in_array($form_id, $form_ids)) {
$tid = $form['#term']['tid'];
$vid = $form['#vocabulary']['vid'];
$parent = array_keys(taxonomy_get_parents($tid));
$children = _patterns_taxonomy_get_tree($vid, $tid);
// A term can't be the child of itself, nor of its children.
foreach ($children as $child) {
$exclude[] = $child->tid;
}
$exclude[] = $tid;
$form['advanced']['parent'] = _patterns_taxonomy_term_select(t('Parents'), 'parent', $parent, $vid, t('Parent terms') .'.', 1, '<'. t('root') .'>', $exclude);
$form['advanced']['relations'] = _patterns_taxonomy_term_select(t('Related terms'), 'relations', array_keys(taxonomy_get_related($tid)), $vid, NULL, 1, '<'. t('none') .'>', array($tid));
}
// Ensure that parent item dropdown displays all the menu items
// including those created during current pattern execution.
// Without this, those menu items would be omitted due to the
// static caching within menu_tree_all_data().
$form_ids = array('menu_edit_item');
if (in_array($form_id, $form_ids)) {
if (empty($form['menu']['#item'])) {
$item = array('link_title' => '', 'mlid' => 0, 'plid' => 0, 'menu_name' => $form_state['values']['menu']['menu_name'], 'weight' => 0, 'link_path' => '', 'options' => array(), 'module' => 'menu', 'expanded' => 0, 'hidden' => 0, 'has_children' => 0);
}
else {
$item = $form['menu']['#item'];
}
$form['menu']['parent']['#options'] = _patterns_menu_parent_options(menu_get_menus(), $item);
}
// Ensure that taxonomy dropdowns on node edit form display all the terms
// including those created during current pattern execution.
if (!empty($form['taxonomy']) && isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
foreach ($form['taxonomy'] as $vid => $v) {
if (!is_numeric($vid)) continue;
$form['taxonomy'][$vid] = _patterns_taxonomy_form($vid, $form['taxonomy'][$vid]['#default_value'], $form['taxonomy'][$vid]['#description']);
}
}
}
}
function patterns_form_helper($form, $form_state) {
static $form_id;
if (!$form_id && $form_state['submitted'] && !form_get_errors()) {
$form_id = $form_state['values']['form_id'];
$_SESSION['patterns_form_helper'] = array('form_id' => $form_id, 'form_values' => $form_state['values']);
}
return $form;
}
function patterns_exit($destination = null) {
$batch =& batch_get();
if (variable_get('patterns_form_helper', FALSE) && $_SESSION['patterns_form_helper'] && !$destination && empty($batch)) {
if (module_exists('devel')) {
//dpm($_SESSION['patterns_form_helper']);
kprint_r($_SESSION['patterns_form_helper']);
}
else {
print theme('patterns_form_helper', $_SESSION['patterns_form_helper']['form_id'], $_SESSION['patterns_form_helper']['form_values']);
}
}
}
/**
* Implementation of hook_token_values()
*
* @If these get implementated directly into token.module, this should be removed
*/
function patterns_token_values($type, $object = NULL, $options = array()) {
if ($type == 'global') {
$path = conf_path();
$tokens['confpath'] = $path;
return $tokens;
}
}
/**
* Function callback
*/
function _patterns_modify_value(&$form) {
foreach($form as $key => $value) {
if (is_array($value) && isset($value['#type']) && $value['#type'] == 'value') {
$form[$key]['#default_value'] = $value['#value'];
unset($form[$key]['#value']);
}
else if (is_array($value)) {
_patterns_modify_value($form[$key]);
}
}
}
/**
* Recurse an array and replace with tokens
* @ This is used instead of array_walk_recursive because
* of some strange issues with token_get_values failing.
*/
function _patterns_recurse_tokens(&$object, $identifiers) {
foreach($object as $key => $value) {
if (is_array($value)) {
_patterns_recurse_tokens($object[$key], $identifiers);
}
else if (is_scalar($value)) {
$old_key = $key;
_patterns_replace_tokens($object[$key], $key, $identifiers);
// The key was changed, change it
if ($old_key != $key) {
$keys = array_keys($object);
$keys[array_search($old_key, $keys)] = $key;
$object = array_combine($keys, array_values($object));
}
}
}
}
/**
* Array walk callback to replace tokens inside form values
*/
function _patterns_replace_tokens(&$a, &$b, $identifiers = array()) {
static $count = 0;
// Replace IDs with identifiers from the current executing pattern
if (preg_match('/@([a-zA-Z0-9_]+)@/', $a, $match)) {
$a = str_replace($match[0], $identifiers[$match[1]], $a);
}
if (preg_match('/__([a-zA-Z0-9_]+)__/', $b, $match)) {
$b = str_replace($match[0], $identifiers[$match[1]], $a);
}
// Replace tokens
$a = token_replace($a, 'global', NULL, '@', '@');
$b = token_replace($b, 'global', NULL, '__', '__');
}
/**
* Check if a .htaccess file exists to prevent downloads of pattern files
*/
function _patterns_check_file_dir() {
return false;
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (!is_file($path .'/.htaccess')) {
$content = '# Prevent downloading site patterns
<FilesMatch "\.xml$">
Order allow,deny
</FilesMatch>
';
file_save_data($content, $path .'/.htaccess');
}
}
function theme_patterns_form_helper_menu($forms) {
$output = '<ul class="patterns-form-menu">';
foreach ($forms as $form_id => $values) {
$output .= '<li class="patterns-form-menu-item">'. $form_id .'</li>';
}
$output .= '</li>';
return $output;
}
function theme_patterns_form_helper($form_id, $values) {
$output = '<div class="patterns-form" id="patterns-form-'. $form_id .'">';
$output .= '<div class="patterns-form-title">'. t('Form values for %key', array('%key' => $form_id)) .'</div>';
foreach($values as $key => $value) {
$output .= '<div class="patterns-form-item"><div class="patterns-form-key">'. $key .' => </div>';
$output .= '<div class="patterns-form-value">'. print_r($value, true) .'</div></div>';
}
$output .= '</div>';
return $output;
}
/**
* Implementation of hook_theme().
*/
function patterns_theme() {
return array(
'patterns_form_helper' => array(
'arguments' => array('form_id' => NULL, 'values' => NULL),
),
'patterns_form_helper_menu' => array(
'forms' => NULL
)
);
}
/**
* Make some modifications to the form values based on the form
* In particular, make sure form elements with #options and #multiple
* set the keys of the array as the key of the value as how FAPI does it,
* but XML of course does not.
*/
function patterns_sync_form_values($args) {
$form_id = $args[0];
// this functionality is not working well with
// node forms (create/update node)
// so skip them until this issue is fixed
if (strpos($form_id, 'node_form') !== FALSE) {
return;
}
// References inside the form_state can cause potential problems,
// so we'll ensure no references to outside data exists
$form_state = unserialize(serialize($args[1]));
$form_values = $form_state['values'];
unset($args[1]['values']);
// Get the fully built fapi object with cloned form_state.
// We need to do this with a separate form_state because
// this can mess up the form values if they are setup incorrectly
// (it'll get fixed here)
$form = call_user_func_array('drupal_retrieve_form', $args);
drupal_prepare_form($form_id, $form, $form_state);
$form = form_builder($form_id, $form, $form_state);
// Loop through all form values looking for #options
$queue = array(&$form);
while (!empty($queue)) {
$check = &$queue[0];
array_shift($queue);
// Skip disabled items
if ($check['#disabled']) {
continue;
}
// Set default values for everything that the form is expecting values for.
// This can save work in the components as well as avoid bugs when a module
// expects values to be there that are not.
// Do not set default values when it is the type of value that a form submit
// would not set data in $_POST for. Like selects with no options or unchecked
// checkboxes
if ($check['#input'] && isset($check['#default_value']) &&
!($check['#type'] == 'select' && empty($check['#options'])) &&
!(in_array($check['#type'], array('checkbox', 'checkboxes')) && empty($check['#default_value']))) {
$match = &$form_values;
$found = true;
foreach($check['#parents'] as $path) {
if (!isset($match[$path])) {
$found = false;
$match[$path] = array();
}
// If this is not an array, the data was probably not completed properly
// in the pattern.
if (!is_array($match)) {
$message = t('Invalid pattern syntax at: !path. Expecting more child elements.', array('!path' => implode('->', $check['#parents'])));
patterns_error_handler(1, $message, '', '');
return;
}
$match = &$match[$path];
}
// Set the default value unless it is a type of value that would originally
// not be set in $_POST during form submit, like empty selects
if (!$found) {
$check['#missing_in_pattern'] = true;
$match = $check['#default_value'];
}
}
if (!empty($check['#options'])) {
$scalar = false;
if ((!$check['#tree'] && !$check['#multiple']) || (isset($check['#multiple']) && !$check['#multiple']) || in_array($check['#type'], array('radio', 'radios'))) {
$scalar = true;
}
// Find possible corresponding data in form values
$match = &$form_values;
$found = true;
foreach($check['#parents'] as $path) {
if (isset($match[$path])) {
$match = &$match[$path];
}
else {
$found = false;
break;
}
}
if ($found && isset($match)) {
// Check if we are overwriting or not.
//
// First, if the pattern value is there, but empty, we obviously
// should be overwriting. Next is to check if overwrite was specified
// manually
if (!$check['#missing_in_pattern'] && (empty($match) || (is_array($match) && isset($match['_overwrite_'])))) {
$overwrite = true;
if (is_array($match) && isset($match['_overwrite_'])) {
$match = $match['_overwrite_'];
}
}
// If overwriting, start the values array with all the
// possible values but empty. We will possibly fill them
// in with default values on update actions. Select types
// do not work when empty, non-selected, values are set
if (!$scalar && $overwrite && $check['#type'] != 'select') {
$values = $check['#options'];
foreach($values as &$v) {
$v = '';
}
}
else {
$values = array();
}
if (!$overwrite && !empty($check['#default_value'])) {
foreach((array)$check['#default_value'] as $value) {
$values[$value] = $value;
}
// Make sure we are still restricted to values available in #options
$values = array_intersect_key($values, $check['#options']);
}
// Flatten out the options in case it is trying to use optgroups
$options = patterns_options_flatten($check['#options']);
foreach((array)$match as $value) {
$key = array_search($value, $options);
// If the supplied value is an actual options value (not the label) use that
- if (array_key_exists($value, $options)) {
+ if ( (is_numeric($value) || is_string($value)) && array_key_exists($value, $options)) {
$values[$value] = $value;
}
// Or if the supplied value matches an options label, use that option
else if ($key !== FALSE) {
$values[$key] = $key;
}
// If we are trying to set an invalid value, at least select
// the first value for select forms since it is impossible to
// not select a good value there
else if ($check['#type'] == 'select') {
reset($options);
$values[key($options)] = key($options);
}
}
// If we are not on a multiple/tree form, the value should be singular/not an array.
// We make sure to use the last value here because the last value will absolutely
// be the user/pattern supplied value as opposed to the default_value
if ($scalar) {
$match = end($values);
}
else {
$match = $values;
}
}
}
foreach(element_children($check) as $element) {
$queue[] = &$check[$element];
}
}
// Make sure the new form_values will be used in the real executions
$args[1]['values'] = $form_values;
}
/**
* Helper function to flatter options, but keep the title/names in
*/
function patterns_options_flatten($array, $reset = TRUE) {
static $return;
if ($reset) {
$return = array();
}
foreach ($array as $key => $value) {
if (is_object($value)) {
patterns_options_flatten($value->option, FALSE);
}
else if (is_array($value)) {
patterns_options_flatten($value, FALSE);
}
else {
$return[$key] = $value;
}
}
return $return;
}
/**
* Take a $data and $config object and adjust $data
* based on the supplied configuration
*
* TODO Look for ways to optimize and increase performance
*/
function patterns_config_data(&$data, $configs) {
foreach($configs as $path => $config) {
// An alias key requires multiple paths
// for each alias and then a #real set
// to change all of them to the same key
// TODO test #alias
if ($config['#alias'] && is_array($config['#alias'])) {
$tokens = array_slice(preg_split('/(?<!=)\/(?![a-z]*\])/', $path), 1);
$real = end($tokens);
// Check for the real key
$matches = patterns_array_fetch($path, $data);
// If the real key was not found, get the aliases
if (empty($matches)) {
if (!$config['#key']) {
$config['#key'] = $real;
}
foreach($config['#alias'] as $alias) {
$tokens[count($tokens)-1] = $alias;
$matches += patterns_array_fetch('/'. implode('/', $tokens), $data);
}
}
}
else {
$matches = patterns_array_fetch($path, $data);
}
// If no matches were found and it is a required element
// return an error
if (empty($matches) && $config['#required']) {
$error = true;
}
foreach($matches as &$match) {
// Collect form_ids here.
// TODO Think of a better way to migrate components form_id operations here
if ($config['#form_id']) {
patterns_config_form_ids($data['tag'], $config['#form_id'], $match);
}
// Make sure values that should be arrays are set as such
if ($config['#array'] && !array_key_exists(0, $match['item'])) {
if (is_null($match['item']) || (is_array($match['item'] && empty($match['item'])))) {
$match['item'] = array();
}
else {
$match['item'] = array($match['item']);
}
// Update the context object to reflect new changes
$match = _patterns_array_context($match['item'], $match);
}
// Change the key of this match. Can get the key value via xpath as well.
// Any duplicate keys will return an error
if ($config['#key']) {
// Check that a single match is found via this xpath and that the resulting value is scalar
if ($config['#key']{0} == '/' && ($sub_matches = patterns_array_fetch($config['#key'], $match['item'], $match)) && count($sub_matches) == 1 && is_scalar($sub_matches[0]['item'])) {
// an xpath from the matched item is used to get the key value
$new_key = $sub_matches[0]['item'];
}
else if ($config['#default key']) {
$new_key = $config['#default key'];
}
else if ($config['#key']{0} == '/') {
// Could not find the appropriate key value from the xpath
$error = true;
}
else {
// Set the key to a static value. Typically used for allowing more user readable keys
$new_key = $config['#key'];
}
if ($new_key && array_key_exists($new_key, $match['parent']['item'])) {
// The new key already exists.
$error = true;
}
else if ($new_key) {
$key = $match['key'];
$match['parent']['item'][$new_key] = $match['item'];
// TODO This is buggy. Skip for now.
if(is_int($key) && false) {
array_splice($match['parent']['item'], $key, 1);
}
else {
unset($match['parent']['item'][$key]);
}
// Update the parent context object to reflect new changes
$match['parent'] = _patterns_array_context($match['parent']['item'], $match['parent']);
// Update to the new current match
for($i=0;$i<count($match['parent']);$i++) {
if ($match['parent'][$i]['key'] == $new_key) {
$match = &$match['parent'][$i];
break;
}
}
}
}
// Create empty key elements if they don't exist but should (and are not required)
// This is useful when using 'move' to ensure that the destination exists
if ($config['#create'] && is_array($match['item']) && !array_key_exists($config['#create'], $match['item'])) {
$match['item'][$config['#create']] = $config['#create value'];
}
// Move(or copy) this match to somewhere else in the object. If more than one destination
// match is found, this value is copied to each one
// TODO Make move automatically create the destination if it doesn't exist
// TODO Support move in (put inside array) and move to (replace) actions
if (!empty($match['parent']) && ($config['#move']{0} == '/' && ($dest_path = $config['#move']) && ($op = 'move')) ||
($config['#copy']{0} == '/' && ($dest_path = $config['#copy']) && ($op = 'copy'))) {
$dests = patterns_array_fetch($dest_path, $match['item'], $match);
$parent = &$match['parent'];
$obj = $match['item'];
foreach($dests as $dest) {
// Can't move to items that are not an array
if (!is_array($dest['item'])) {
continue;
}
if (!is_int($match['key'])) {
$dest['item'][$match['key']] = $obj;
}
else {
$dest['item'][] = $obj;
}
// Update the dest object to reflect the change
$dest = _patterns_array_context($dest['item'], $dest);
}
if ($op == 'move') {
if (!is_int($match['key'])) {
unset($parent['item'][$match['key']]);
}
else {
array_splice($parent['item'], $match['key'], 1);
}
// Update the parent object to reflect the change (removal)
$parent = _patterns_array_context($parent['item'], $parent);
unset($match);
}
}
}
}
}
/**
* Find parts of an array based on
* a semi-compatible xpath syntax.
*
* Returns an array of constructs that includes the
* references 'item' and 'parent' from the matching values
* in the $data object along with extra keys 'key' for the key
* of the current match and 'trace' for a full list of keys
* till the root of the $data object
*
* Loosely based off of Cake function Set::extract
*
* @Note: Ensure this always only returns matches from a single level
* in the array. Changes made to matches in different levels can possibly
* mess up the above-level matches. To this end, you cannot change the keys
* of a current match because the other matches cannot change their keys as well
* to sync with the new parent array.
* @TODO: Think of a solution for the above note (BROKEN RIGHT NOW)
*/
function patterns_array_fetch($path, &$data, $context = null) {
if (!$context && (empty($data) || !is_array($data))) {
return array();
}
if ($path === '/') {
return $data;
}
// Construct our contexts object that allows us to traverse the array
if(!$context) {
$context = _patterns_array_context($data);
}
// Make our context actually a list of contexts
$context = array($context);
// Create a list of tokens based on the supplied path
$tokens = array_slice(preg_split('/(?<!=)\/(?![a-z]*\])/', $path), 1);
while(!empty($tokens)) {
$token = array_shift($tokens);
// TODO Implement better conditionals for each token
// Currently only supports element=value conditions
$conditions = array();
if (preg_match('/(=)(.*)/', $token, $m)) {
$conditions[$m[1]] = $m[2];
$token = substr($token, 0, strpos($token, $m[1]));
}
$matches = array();
foreach ($context as &$piece) {
if ($token === '..') {
$matches[] = &$piece['parent'];
continue;
}
$match = false;
if (is_array($piece['item']) && ($token == '*' || array_key_exists($token, $piece['item']))) {
$i=0;
while(isset($piece[$i])) {
if ($piece[$i]['key'] === $token) {
$matches[] = &$piece[$i];
break;
}
else if ($token === '*') {
$matches[] = &$piece[$i];
}
$i++;
}
}
else if ($token === '.') {
$matches[] = &$piece;
}
}
// Filter matches from the matches list based on our conditions
foreach($conditions as $operator => $value) {
_patterns_array_filter($matches, $operator, $value);
}
// Update the context area to the next set of matches to dig into
$context = $matches;
}
// Return the list of matches containing references to their respective data objects
return $matches;
}
/**
* Helper function to create a context array based on the supplied object
* Supplying a parent object will set the parent for this context
*/
function _patterns_array_context(&$obj, &$current = null) {
// If a current context is set, use it's parent and key values
if (!($trace = $current['trace'])) {
$trace = array();
}
if (!($key = $current['key'])) {
$key = null;
}
if (!($parent = &$current['parent'])) {
$parent = null;
}
$context = array('trace' => $trace, 'key' => $key, 'item' => &$obj, 'parent' => &$parent);
$refs = array(&$context);
while (!empty($refs)) {
$ref = &$refs[0];
$parent = &$ref['item'];
array_splice($refs, 0, 1);
if (is_array($parent) && !empty($parent)) {
$i = 0;
foreach($parent as $index => &$child) {
// TODO possible optimizations can be done here (with the parent trace)
$ref[$i] = array('trace' => _patterns_array_trace($ref), 'key' => $index, 'item' => &$child, 'parent' => &$ref);
array_unshift($refs, '');
$refs[0] = &$ref[$i++];
}
}
}
return $context;
}
/**
* Helper function to filter values of the list of matches
*/
function _patterns_array_filter(&$matches, $operator, $value = null) {
for($i=count($matches)-1;$i>=0;$i--) {
$match = &$matches[$i];
switch($operator) {
case '=':
if ($match['item'] != $value) {
array_splice($matches, $i, 1);
}
break;
}
}
}
/**
* Helper function to create a list of parent keys given a context item
*/
function _patterns_array_trace($obj) {
// Loop back up through the parents to fill in the trace value.
$up = &$obj;
$trace = array();
while(isset($up['parent'])) {
array_unshift($trace, $up['key']);
$up = &$up['parent'];
}
return $trace;
}
/**
* Check if all the module dependencies are available
*
* @param $modules
* array of module names
* @param $update_list
* if TRUE, add all the dependecies to pattern's module list
* @return
* empty array if all dependencies are available
* array of missing module's names if some dependencies are not available
*
*/
function patterns_check_module_dependencies(&$modules, $update_list = FALSE) {
if (empty($modules)) return array();
$modules_info = module_rebuild_cache();
$result = array();
$dependencies = array();
foreach($modules as $module) {
$module = is_array($module) ? $module['value'] : $module;
if (array_key_exists($module, $modules_info)) {
// check also for module's dependencies
foreach ($modules_info[$module]->info['dependencies'] as $dependency) {
if (array_key_exists($dependency, $modules_info)) {
$dependencies[] = $dependency;
}
else {
$result[] = $dependency;
}
}
}
else {
$result[] = $module;
}
}
if ($update_list && empty($result) && !empty($dependencies)) {
$modules = array_unique(array_merge($modules, $dependencies));
}
return $result;
}
function patterns_set_error_handler() {
// set custom error handler
set_error_handler('patterns_error_handler');
// trigger dummy error
// this will be used as a refrence to determine if any real error
// occured during the pattern execution
@trigger_error('patterns_error');
}
function patterns_restore_error_handler() {
restore_error_handler();
}
/**
* Custom error handler used only during patterns execution
* in order to catch and properly handle PHP errors.
* Based on drupal_error_handler().
*/
function patterns_error_handler($errno, $message, $filename, $line, $context) {
if ($errno & (E_ALL ^ E_NOTICE)) {
$types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning', 4096 => 'recoverable fatal error');
// For database errors, we want the line number/file name of the place that
// the query was originally called, not _db_query().
if (isset($context[DB_ERROR])) {
$backtrace = array_reverse(debug_backtrace());
// List of functions where SQL queries can originate.
$query_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
// Determine where query function was called, and adjust line/file
// accordingly.
foreach ($backtrace as $index => $function) {
if (in_array($function['function'], $query_functions)) {
$line = $backtrace[$index]['line'];
$filename = $backtrace[$index]['file'];
break;
}
}
}
// 'patterns_error' is not a real error and should be skipped
if ($message != 'patterns_error') {
watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
patterns_error_set_last(array('message' => $message, 'type' => $errno, 'file' => $filename, 'line' => $line));
}
}
return TRUE;
}
function patterns_error_set_last($error = NULL) {
static $last_error = array();
if (isset($error)) {
$last_error = $error;
}
return $last_error;
}
/**
* Check and report PHP errors during patterns execution
*
* @param $op
* operation within hook_patterns() during which error occured
* @param $key
* number of the action currently proccessed
* @param $description
* description of the current action
* @param $pattern_title
* title of the pattern currently proccessed
* @param $pattern_file
* path to pattern file currently proccessed
* @return
* error message if new error encountered
* FALSE if there are no new errors
*
*/
function patterns_error_get_last($op, $key, $description, $pattern_title, $pattern_file) {
$error = patterns_error_set_last();
if (!empty($error) && $error['message'] != 'patterns_error') {
$types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning', 4096 => 'recoverable fatal error');
$php_error_message = $types[$error['type']] .': '. $error['message'] .' in '. $error['file'] .' on line '. $error['line'] .'.';
$message = t('Pattern %title (%pattern_file)<br>Action #%key: %description (op "%op")<br>PHP error occured:<br>%error', array('%key' => $key, '%title' => $pattern_title, '%op' => $op, '%description' => $description, '%error' => $php_error_message, '%pattern_file' => $pattern_file));
return $message;
}
return FALSE;
}
/**
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.