repo
string
commit
string
message
string
diff
string
saces/SchwachkopfEinsteck
4f8a85a3f7e802f5019bca0ea01f02ba796c7d53
add eclipse project files
diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..8690a31 --- /dev/null +++ b/.classpath @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="src" path="lib/jgit/org.eclipse.jgit/src"/> + <classpathentry kind="src" path="lib/jsch/src"/> + <classpathentry kind="src" path="lib/jzlib"/> + <classpathentry kind="src" path="lib/ernie/src"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry combineaccessrules="false" kind="src" path="/fred"/> + <classpathentry kind="output" path="build"/> +</classpath> diff --git a/.externalToolBuilders/SchwachkopfEinsteck.launch b/.externalToolBuilders/SchwachkopfEinsteck.launch new file mode 100644 index 0000000..f9b2316 --- /dev/null +++ b/.externalToolBuilders/SchwachkopfEinsteck.launch @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType"> +<booleanAttribute key="org.eclipse.ant.ui.ATTR_TARGETS_UPDATED" value="true"/> +<booleanAttribute key="org.eclipse.ant.ui.DEFAULT_VM_INSTALL" value="false"/> +<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS"> +<listEntry value="/SchwachkopfEinsteck/build.xml"/> +</listAttribute> +<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES"> +<listEntry value="1"/> +</listAttribute> +<booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/> +<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/> +<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="true"/> +<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="SchwachkopfEinsteck"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/SchwachkopfEinsteck/build.xml}"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,"/> +<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/> +</launchConfiguration> diff --git a/.project b/.project new file mode 100644 index 0000000..b28e71a --- /dev/null +++ b/.project @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>SchwachkopfEinsteck</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.ui.externaltools.ExternalToolBuilder</name> + <triggers>full,incremental,</triggers> + <arguments> + <dictionary> + <key>LaunchConfigHandle</key> + <value>&lt;project&gt;/.externalToolBuilders/SchwachkopfEinsteck.launch</value> + </dictionary> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription>
saces/SchwachkopfEinsteck
ae9eac37f10bf62d305e9ca8ae1fdcada9fddec3
add sources
diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..72c63dc --- /dev/null +++ b/build.xml @@ -0,0 +1,183 @@ +<?xml version="1.0"?> +<!-- ant build file for SchwachkopfEinsteck --> + +<project name="SchwachkopfEinsteck" default="dist" basedir="."> + <property name="freenet-cvs-snapshot.location" location="../fred/lib/freenet-cvs-snapshot.jar"/> + <property name="freenet-ext.location" location="../fred/lib/freenet-ext.jar"/> + <property name="svn.revision" value="@custom@"/> + <property name="source-version" value="1.5"/> + <property name="target-version" value="1.5"/> + <property name="build" location="build/"/> + <property name="build-test" location="build-test/"/> + <property name="dist" location="dist/"/> + <property name="src" location="src/"/> + <property name="junit.location" value="/usr/share/java/junit.jar"/> + <property name="version.src" value="plugins/schwachkopfeinsteck/Version.java" /> + <property name="version.build" value="plugins/schwachkopfeinsteck/Version.class" /> + + <available file="src/plugins/schwachkopfeinsteck/Version.java" property="version.present"/> + <available file="${junit.location}" property="junit.present"/> + + <exec executable="git" + failifexecutionfails="false" + errorProperty="git.errror" + outputproperty="git.describe" + resultproperty="git.result"> + <arg value="describe" /> + <arg value="--always" /> + <arg value="--abbrev=4" /> + </exec> + + <condition property="git.revision" value="${git.describe}" else="@unknown@"> + <and> + <equals arg1="${git.result}" arg2="0" /> + <isset property="git.describe" /> + </and> + </condition> + + <target name="mkdir"> + <mkdir dir="${build}"/> + <mkdir dir="${build-test}"/> + <mkdir dir="${dist}"/> + <echo message="Using ${freenet-cvs-snapshot.location} as freenet-cvs-snapshot.jar"/> + <echo message="Using ${freenet-ext.location} as freenet-ext.jar"/> + </target> + + <!-- ================================================== --> + <target name="compile" depends="mkdir" > + <!-- Create the time stamp --> + <tstamp/> + <!-- Create the build directory structure used by compile --> + + <!-- Create the Version file with patched revision number in ${build} --> + <copy file="${src}/${version.src}" tofile="${build}/${version.src}" overwrite="true" /> + <delete file="${build}/${version.build}" quiet="true" /> + <replace file="${build}/${version.src}"> + <replacefilter token="@custom@" value="${git.revision}"/> + </replace> + <echo message="Updated build version to ${git.revision} in ${build}/${version.src}"/> + + <!-- Force compile of Version.java in case compile of ${src} didn't trigger it --> + <javac srcdir="${build}" destdir="${build}" debug="on" optimize="on" source="${source-version}" target="${target-version}"> + <classpath> + <pathelement location="${freenet-ext.location}"/> + <pathelement location="${freenet-cvs-snapshot.location}"/> + </classpath> + <include name="${version.src}"/> + </javac> + + <!-- FIXME: remove the debug and replace with optimize --> + <javac srcdir="lib/jzlib" destdir="${build}" debug="on" optimize="on" source="${source-version}" target="${target-version}"> + <classpath> + <pathelement location="${freenet-ext.location}"/> + <pathelement location="${freenet-cvs-snapshot.location}"/> + </classpath> + <include name="**/*.java"/> + <exclude name="**/*Test.java"/> + <exclude name="${version.src}"/> + </javac> + + <!-- FIXME: remove the debug and replace with optimize --> + <javac srcdir="lib/jsch/src" destdir="${build}" debug="on" optimize="on" source="${source-version}" target="${target-version}"> + <classpath> + <pathelement location="${freenet-ext.location}"/> + <pathelement location="${freenet-cvs-snapshot.location}"/> + </classpath> + <include name="**/*.java"/> + <exclude name="**/*Test.java"/> + <exclude name="${version.src}"/> + </javac> + + <!-- FIXME: remove the debug and replace with optimize --> + <javac srcdir="lib/jgit/org.eclipse.jgit/src" destdir="${build}" debug="on" optimize="on" source="${source-version}" target="${target-version}"> + <classpath> + <pathelement location="${freenet-ext.location}"/> + <pathelement location="${freenet-cvs-snapshot.location}"/> + </classpath> + <include name="**/*.java"/> + <exclude name="**/*Test.java"/> + <exclude name="${version.src}"/> + </javac> + + <!-- FIXME: remove the debug and replace with optimize --> + <javac srcdir="lib/ernie/src" destdir="${build}" debug="on" optimize="on" source="${source-version}" target="${target-version}"> + <classpath> + <pathelement location="${freenet-ext.location}"/> + <pathelement location="${freenet-cvs-snapshot.location}"/> + </classpath> + <include name="**/*.java"/> + <exclude name="**/*Test.java"/> + <exclude name="${version.src}"/> + </javac> + + <!-- FIXME: remove the debug and replace with optimize --> + <javac srcdir="${src}" destdir="${build}" debug="on" optimize="on" source="${source-version}" target="${target-version}"> + <classpath> + <pathelement location="${freenet-ext.location}"/> + <pathelement location="${freenet-cvs-snapshot.location}"/> + <pathelement location="lib/jgit/org.eclipse.jgit/src"/> + </classpath> + <include name="**/*.java"/> + <exclude name="**/*Test.java"/> + <exclude name="${version.src}"/> + </javac> + </target> + + <!-- ================================================== --> + + <target name="unit-build" depends="compile" if="junit.present" unless="skip_tests"> + <javac srcdir="src/" destdir="${build-test}" debug="on" optimize="on" source="1.5"> + <classpath> + <pathelement path="${build}"/> + <pathelement location="${freenet-ext.location}"/> + <pathelement location="${freenet-cvs-snapshot.location}"/> + <pathelement location="${junit.location}"/> + </classpath> + <compilerarg value="-Xlint"/> + <include name="**/*Test.java"/> + </javac> + </target> + + <target name="junit" depends="unit-build" if="junit.present" unless="skip_tests"> + <junit printsummary="yes" fork="yes" haltonfailure="yes"> + <classpath> + <pathelement path="${build}"/> + <pathelement path="${build-test}"/> + <pathelement location="${freenet-ext.location}"/> + <pathelement location="${freenet-cvs-snapshot.location}"/> + <pathelement location="${junit.location}"/> + </classpath> + + <formatter type="plain" usefile="false"/> + + <batchtest fork="yes"> + <fileset dir="${build-test}"> + <include name="**/*Test.class"/> + </fileset> + </batchtest> + <sysproperty key="benchmark" value="${benchmark}" /> + <sysproperty key="extensiveTesting" value="${extensiveTesting}" /> + </junit> + </target> + + <!-- ================================================== --> + <target name="dist" depends="compile,junit" + description="generate the distribution" > + <jar jarfile="${dist}/SchwachkopfEinsteck.jar" duplicate="fail"> + <manifest> + <attribute name="Plugin-Main-Class" value="plugins.schwachkopfeinsteck.GitPlugin"/> + </manifest> + <fileset dir="src/" casesensitive="no"> + <include name="*.txt"/> + </fileset> + <fileset dir="${build}/"/> + </jar> + </target> + + <!-- ================================================== --> + <target name="clean" description="Delete class files and docs dir."> + <delete dir="${build}"/> + <delete dir="${build-test}"/> + <delete dir="${dist}"/> + </target> +</project> diff --git a/src/plugins/schwachkopfeinsteck/AdminToadlet.java b/src/plugins/schwachkopfeinsteck/AdminToadlet.java new file mode 100644 index 0000000..2c4ad81 --- /dev/null +++ b/src/plugins/schwachkopfeinsteck/AdminToadlet.java @@ -0,0 +1,149 @@ +package plugins.schwachkopfeinsteck; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.LinkedList; +import java.util.List; + +import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon; + +import freenet.clients.http.PageNode; +import freenet.clients.http.ToadletContext; +import freenet.clients.http.ToadletContextClosedException; +import freenet.support.HTMLNode; +import freenet.support.api.HTTPRequest; +import freenet.support.plugins.helpers1.PluginContext; +import freenet.support.plugins.helpers1.WebInterfaceToadlet; + +public class AdminToadlet extends WebInterfaceToadlet { + + private static final String PARAM_PORT = "port"; + private static final String PARAM_BINDTO = "bindto"; + private static final String PARAM_ALLOWEDHOSTS = "allowedhosts"; + private static final String CMD_START = "start"; + private static final String CMD_STOP = "stop"; + private static final String CMD_RESTART = "restart"; + private static final String PARAM_CACHEDIR = "chachedir"; + private static final String CMD_APPLY = "apply"; + + private final AnonymousGitDaemon daemon; + + public AdminToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) { + super(context, GitPlugin.PLUGIN_URI, "admin"); + daemon = simpleDaemon; + } + + public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException { + List<String> errors = new LinkedList<String>(); + if (!normalizePath(req.getPath()).equals("/")) { + errors.add("The path '"+uri+"' was not found"); + } + makePage(ctx, errors); + } + + public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException { + + List<String> errors = new LinkedList<String>(); + + if (!isFormPassword(request)) { + errors.add("Invalid form password"); + makePage(ctx, errors); + return; + } + + String path = normalizePath(request.getPath()); + + if (request.isPartSet(CMD_STOP)) { + daemon.stop(); + } else { + String bindTo = request.getPartAsString(PARAM_BINDTO, 50); + int port = request.getIntPart(PARAM_PORT, 9481); + String allowedHosts = request.getPartAsString(PARAM_ALLOWEDHOSTS, 50); + if (request.isPartSet(CMD_START)) { + daemon.setAdress(bindTo, port, allowedHosts, false); + daemon.start(); + } else if (request.isPartSet(CMD_RESTART)) { + daemon.stop(); + try { + //sleep 3 sec, give the old bind a chanche to vanish… + Thread.sleep(3000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + daemon.setAdress(bindTo, port, allowedHosts, false); + daemon.start(); + } else { + errors.add("Unknown command."); + } + } + makePage(ctx, errors); + } + + private void makePage(ToadletContext ctx, List<String> errors) throws ToadletContextClosedException, IOException { + PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin the git server", ctx); + HTMLNode outer = pageNode.outer; + HTMLNode contentNode = pageNode.content; + + if (errors.size() > 0) { + contentNode.addChild(createErrorBox(errors, path(), null, null)); + errors.clear(); + } + + makeCommonBox(contentNode); + makeSimpleBox(contentNode); + makeSSHBox(contentNode); + + writeHTMLReply(ctx, 200, "OK", outer.generate()); + } + + private void makeCommonBox(HTMLNode parent) { + HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Common settings", parent); + HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "commonForm"); + boxForm.addChild("#", "GitPlugin uses a local cache to serve from. Congratulation, you have found the reference point for 'backup'."); + boxForm.addChild("br"); + boxForm.addChild("#", "Cache dir: \u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "size", "value", "disabled"}, new String[] { "text", PARAM_CACHEDIR, "50", daemon.getCacheDir(), "disabled" }); + boxForm.addChild("br"); + boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_APPLY, "Apply", "disabled" }); + } + + private void makeSimpleBox(HTMLNode parent) { + HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Simple git server (git://)", parent); + HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "simpleServerForm"); + boxForm.addChild("#", "This is the anonymous git server. No authentication/encryption/accesscontrol at all. Be carefully."); + boxForm.addChild("br"); + boxForm.addChild("#", "Port: \u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_PORT, "7", "9418" }); + boxForm.addChild("br"); + boxForm.addChild("#", "Bind to: \u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_BINDTO, "20", "127.0.0.1" }); + boxForm.addChild("br"); + boxForm.addChild("#", "Allowed hosts: \u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "size", "value"}, new String[] { "text", PARAM_ALLOWEDHOSTS, "20", "127.0.0.1" }); + boxForm.addChild("br"); + if (daemon.isRunning()) { + boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_START, "Start", "disabled" }); + boxForm.addChild("#", "\u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_STOP, "Stop" }); + boxForm.addChild("#", "\u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_RESTART, "Restart" }); + } else { + boxForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", CMD_START, "Start"}); + boxForm.addChild("#", "\u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_STOP, "Stop", "disabled" }); + boxForm.addChild("#", "\u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_RESTART, "Restart", "disabled" }); + } + } + + private void makeSSHBox(HTMLNode parent) { + HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "SSH git server (git+ssh://)", parent); + HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "sshServerForm"); + boxForm.addChild("#", "Setting up SSH for an 'Just an idea' implementation is far to much. Sorry folks."); + boxForm.addChild("br"); + boxForm.addChild("#", "Basic code for SSH (jSch) is in, just send patches ;)"); + } + +} diff --git a/src/plugins/schwachkopfeinsteck/BrowseToadlet.java b/src/plugins/schwachkopfeinsteck/BrowseToadlet.java new file mode 100644 index 0000000..adab126 --- /dev/null +++ b/src/plugins/schwachkopfeinsteck/BrowseToadlet.java @@ -0,0 +1,53 @@ +package plugins.schwachkopfeinsteck; + +import java.io.IOException; +import java.net.URI; + +import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon; + +import freenet.clients.http.PageNode; +import freenet.clients.http.ToadletContext; +import freenet.clients.http.ToadletContextClosedException; +import freenet.support.HTMLNode; +import freenet.support.api.HTTPRequest; +import freenet.support.plugins.helpers1.PluginContext; +import freenet.support.plugins.helpers1.WebInterfaceToadlet; + +public class BrowseToadlet extends WebInterfaceToadlet { + + private static final String PARAM_URI = "URI"; + private static final String CMD_BROWSE = "browse"; + + private final AnonymousGitDaemon daemon; + + public BrowseToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) { + super(context, GitPlugin.PLUGIN_URI, ""); + daemon = simpleDaemon; + } + + public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException { + if (!normalizePath(req.getPath()).equals("/")) { + sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found"); + return; + } + makePage(ctx); + } + + private void makePage(ToadletContext ctx) throws ToadletContextClosedException, IOException { + PageNode pageNode = pluginContext.pageMaker.getPageNode("Browse git repos", ctx); + HTMLNode outer = pageNode.outer; + HTMLNode contentNode = pageNode.content; + + HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Browsa a git repos", contentNode); + HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "uriForm"); + boxForm.addChild("#", "Not implemented yet."); + boxForm.addChild("br"); + boxForm.addChild("#", "Repos URI: \u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "size"}, new String[] { "text", PARAM_URI, "70" }); + boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_BROWSE, "Open", "disabled" }); + + writeHTMLReply(ctx, 200, "OK", outer.generate()); + } + + +} diff --git a/src/plugins/schwachkopfeinsteck/GitPlugin.java b/src/plugins/schwachkopfeinsteck/GitPlugin.java new file mode 100644 index 0000000..85d5703 --- /dev/null +++ b/src/plugins/schwachkopfeinsteck/GitPlugin.java @@ -0,0 +1,81 @@ +package plugins.schwachkopfeinsteck; + +import java.net.InetSocketAddress; + +import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon; + +import freenet.l10n.BaseL10n.LANGUAGE; +import freenet.pluginmanager.FredPlugin; +import freenet.pluginmanager.FredPluginL10n; +import freenet.pluginmanager.FredPluginRealVersioned; +import freenet.pluginmanager.FredPluginThreadless; +import freenet.pluginmanager.FredPluginVersioned; +import freenet.pluginmanager.PluginRespirator; +import freenet.support.Logger; +import freenet.support.plugins.helpers1.PluginContext; +import freenet.support.plugins.helpers1.WebInterface; + +public class GitPlugin implements FredPlugin, FredPluginL10n, FredPluginThreadless, FredPluginVersioned, FredPluginRealVersioned { + + private static volatile boolean logMINOR; + private static volatile boolean logDEBUG; + + static { + Logger.registerClass(GitPlugin.class); + } + + public static final String PLUGIN_URI = "/GitPlugin"; + private static final String PLUGIN_CATEGORY = "Git Tools"; + public static final String PLUGIN_TITLE = "Git Plugin"; + + private PluginContext pluginContext; + private WebInterface webInterface; + + private AnonymousGitDaemon simpleDaemon; + + public void runPlugin(PluginRespirator pluginRespirator) { + pluginContext = new PluginContext(pluginRespirator); + simpleDaemon = new AnonymousGitDaemon("huhu", pluginContext.node.executor); + + webInterface = new WebInterface(pluginContext); + webInterface.addNavigationCategory(PLUGIN_URI+"/", PLUGIN_CATEGORY, "Git Toolbox", this); + + // Visible pages + BrowseToadlet browseToadlet = new BrowseToadlet(pluginContext, simpleDaemon); + webInterface.registerVisible(browseToadlet, PLUGIN_CATEGORY, "Browse", "Browse a git repository like GitWeb"); + AdminToadlet adminToadlet = new AdminToadlet(pluginContext, simpleDaemon); + webInterface.registerVisible(adminToadlet, PLUGIN_CATEGORY, "Admin", "Admin the git server"); + RepositoriesToadlet reposToadlet = new RepositoriesToadlet(pluginContext, simpleDaemon); + webInterface.registerVisible(reposToadlet, PLUGIN_CATEGORY, "Repositories", "Create & Delete server's repositories"); + + InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 9418); + + simpleDaemon.setCacheDir("./gitcache"); + //simpleDaemon.start(addr); + } + + public void terminate() { + webInterface.kill(); + if (simpleDaemon.isRunning()) + simpleDaemon.stop(); + simpleDaemon = null; + } + + public String getString(String key) { + return key; + } + + public void setLanguage(LANGUAGE newLanguage) { + // TODO Auto-generated method stub + + } + + public String getVersion() { + return Version.getLongVersionString(); + } + + public long getRealVersion() { + return Version.getRealVersion(); + } + +} diff --git a/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java new file mode 100644 index 0000000..7727451 --- /dev/null +++ b/src/plugins/schwachkopfeinsteck/RepositoriesToadlet.java @@ -0,0 +1,53 @@ +package plugins.schwachkopfeinsteck; + +import java.io.IOException; +import java.net.URI; + +import plugins.schwachkopfeinsteck.daemon.AnonymousGitDaemon; + +import freenet.clients.http.PageNode; +import freenet.clients.http.ToadletContext; +import freenet.clients.http.ToadletContextClosedException; +import freenet.support.HTMLNode; +import freenet.support.api.HTTPRequest; +import freenet.support.plugins.helpers1.PluginContext; +import freenet.support.plugins.helpers1.WebInterfaceToadlet; + +public class RepositoriesToadlet extends WebInterfaceToadlet { + + private static final String PARAM_URI = "URI"; + private static final String CMD_BROWSE = "browse"; + + private final AnonymousGitDaemon daemon; + + public RepositoriesToadlet(PluginContext context, AnonymousGitDaemon simpleDaemon) { + super(context, GitPlugin.PLUGIN_URI, "repos"); + daemon = simpleDaemon; + } + + public void handleMethodGET(URI uri, HTTPRequest req, ToadletContext ctx) throws ToadletContextClosedException, IOException { + if (!normalizePath(req.getPath()).equals("/")) { + sendErrorPage(ctx, 404, "Not found", "the path '"+uri+"' was not found"); + return; + } + makePage(ctx); + } + + private void makePage(ToadletContext ctx) throws ToadletContextClosedException, IOException { + PageNode pageNode = pluginContext.pageMaker.getPageNode("Admin server repos", ctx); + HTMLNode outer = pageNode.outer; + HTMLNode contentNode = pageNode.content; + + HTMLNode box = pluginContext.pageMaker.getInfobox("infobox-information", "Browsa a git repos", contentNode); + HTMLNode boxForm = pluginContext.pluginRespirator.addFormChild(box, path(), "uriForm"); + boxForm.addChild("#", "Not implemented yet."); + boxForm.addChild("br"); + boxForm.addChild("#", "Repos URI: \u00a0 "); + boxForm.addChild("input", new String[] { "type", "name", "size"}, new String[] { "text", PARAM_URI, "70" }); + boxForm.addChild("input", new String[] { "type", "name", "value", "disabled" }, new String[] { "submit", CMD_BROWSE, "Open", "disabled" }); + + writeHTMLReply(ctx, 200, "OK", outer.generate()); + } + + +} diff --git a/src/plugins/schwachkopfeinsteck/Version.java b/src/plugins/schwachkopfeinsteck/Version.java new file mode 100644 index 0000000..d334020 --- /dev/null +++ b/src/plugins/schwachkopfeinsteck/Version.java @@ -0,0 +1,31 @@ +/* This code is part of Freenet. It is distributed under the GNU General + * Public License, version 2 (or at your option any later version). See + * http://www.gnu.org/ for further details of the GPL. */ +package plugins.schwachkopfeinsteck; + +/** + * @author saces + * + */ +public class Version { + + /** SVN revision number. Only set if the plugin is compiled properly e.g. by emu. */ + public static final String gitRevision = "@custom@"; + + /** Version number of the plugin for getRealVersion(). Increment this on making + * a major change, a significant bugfix etc. These numbers are used in auto-update + * etc, at a minimum any build inserted into auto-update should have a unique + * version. + */ + private static final long realVersion = 0; + + private static final String longVersionString = "Just an idea " + gitRevision; + + public static String getLongVersionString() { + return longVersionString; + } + + public static long getRealVersion() { + return realVersion; + } +} diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java new file mode 100644 index 0000000..dddb3b1 --- /dev/null +++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitDaemon.java @@ -0,0 +1,38 @@ +package plugins.schwachkopfeinsteck.daemon; + +import java.io.File; + +import freenet.support.Executor; +import freenet.support.incubation.server.AbstractServer; +import freenet.support.incubation.server.AbstractService; + +public class AnonymousGitDaemon extends AbstractServer { + + private File reposdir; + + public AnonymousGitDaemon(String servername, Executor executor) { + super(servername, executor); + } + + @Override + protected AbstractService getService() { + return new AnonymousGitService(); + } + + public void setCacheDir(String dir) { + if (reposdir != null) { + // move + } else { + File newDir = new File(dir); + if (!newDir.exists()) { + newDir.mkdirs(); + } + reposdir = newDir; + } + } + + public String getCacheDir() { + return reposdir.getPath(); + } + +} diff --git a/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java new file mode 100644 index 0000000..62e218f --- /dev/null +++ b/src/plugins/schwachkopfeinsteck/daemon/AnonymousGitService.java @@ -0,0 +1,84 @@ +package plugins.schwachkopfeinsteck.daemon; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; + +import org.eclipse.jgit.lib.PersonIdent; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.transport.PacketLineIn; +import org.eclipse.jgit.transport.ReceivePack; +import org.eclipse.jgit.transport.UploadPack; + +import freenet.support.Logger; +import freenet.support.incubation.server.AbstractService; + +public class AnonymousGitService implements AbstractService { + + private static volatile boolean logMINOR; + private static volatile boolean logDEBUG; + + static { + Logger.registerClass(AnonymousGitService.class); + } + + private boolean isReadOnly = false; + + public void handle(Socket sock) throws IOException { + InputStream rawIn = new BufferedInputStream(sock.getInputStream()); + OutputStream rawOut = new BufferedOutputStream(sock.getOutputStream()); + + String cmd = new PacketLineIn(rawIn).readStringRaw(); + final int nul = cmd.indexOf('\0'); + if (nul >= 0) { + // Newer clients hide a "host" header behind this byte. + // Currently we don't use it for anything, so we ignore + // this portion of the command. + cmd = cmd.substring(0, nul); + } + + System.out.println("x händle request:"+cmd); + + String req[] = cmd.split(" "); + String command = req[0].startsWith("git-") ? req[0] : "git-" + req[0]; + String reposName = req[1]; + + System.out.print("händle:"+command); + System.out.println(" for:"+reposName); + + if ("git-upload-pack".equals(command)) { + // the client want to have missing objects + Repository db = getRepository(reposName); + final UploadPack rp = new UploadPack(db); + //rp.setTimeout(Daemon.this.getTimeout()); + rp.upload(rawIn, rawOut, null); + } else if ("git-receive-pack".equals(command)) { + // the client send us new objects + if (isReadOnly) return; + Repository db = getRepository(reposName); + final ReceivePack rp = new ReceivePack(db); + final String name = "anonymous"; + final String email = name + "@freenet"; + rp.setRefLogIdent(new PersonIdent(name, email)); + //rp.setTimeout(Daemon.this.getTimeout()); + rp.receive(rawIn, rawOut, null); + } else { + System.err.println("Unknown command: "+command); + } + + System.out.println("x händle request: pfertsch"); + + } + + private Repository getRepository(String reposname) throws IOException { + Repository db; + File path = new File("gitcache/test/.git").getCanonicalFile(); + db = new Repository(path); + return db; + } + +}
saces/SchwachkopfEinsteck
155deac44f4e416cc880df3c1828587db5514e84
add jzlib 1.0.7
diff --git a/lib/jzlib/ChangeLog b/lib/jzlib/ChangeLog new file mode 100644 index 0000000..c828fae --- /dev/null +++ b/lib/jzlib/ChangeLog @@ -0,0 +1,115 @@ +ChangeLog of JZlib +==================================================================== +Last modified: Thu Aug 18 16:16:06 UTC 2005 + + +Changes since version 1.0.6: +- change: memory and performance optimizations in the inflate operation. + Many thanks to Paul Wakefield at platx.org(http://www.platx.org), who + suggested above improvements. +- change: added the nowrap argument to Z{Input,Output}?Stream. + + +Changes since version 1.0.5: +- ZInputStream.read(byte[], int, int) method return sometimes zero + instead of -1 at the end of stream. +- ZOutputStream.end() method should not declare IOException. +- It should be possible to call ZOutputStream.end() method more times + (because you can call close() method and after it end() method in + finally block). +- ZOutputStream.finish() method should not ignore IOException from flush(). +Many thanks to Matej Kraus at seznam.cz , who pointed out above problems. + + +Changes since version 1.0.4: +- a minor bug fix in ZInputStream + + +Changes since version 1.0.3: +- fixed a bug in closing ZOutputStream. + The inflating and deflating processes were not finished successfully. +- added 'finish' and 'end' methods to ZOutputStream.java +- added 'example/test_stream_deflate_inflate.java' + + +Changes since version 1.0.2: +- enabled pure Java implementation of adler32 and + commented out the dependency on J2SE in Adler32.java for J2ME users. + + +Changes since version 1.0.1: +- fixed a bug in deflating some trivial data, for example, + large data chunk filled with zero. +- added 'version' method to JZlib class. + + +Changes since version 1.0.0: +- added ZInputStream and ZOutputStream classes. +- fixed a typo in LICENSE.txt. + + +Changes since version 0.0.9: +- fixed a bug in setting a dictionary in the inflation process. +- The license was changed to a BSD style license. +- Z{Input,Output}Stream classes were deleted. + + +Changes since version 0.0.8: +- fixed a bug in handling a preset dictionary in the inflation process. + + +Changes since version 0.0.7: +- added methods to control the window size (the size of the history + buffer) and to handle the no-wrap option (no zlib header or check), + which is the undocumented functionality of zlib. + + +Changes since version 0.0.6: +- updated InfBlocks.java as zlib did to fix the vulnerability related to + the 'double free'. Of course, JZlib is free from such a vulnerability + like the 'double free', but JZlib had crashed with NullPointerException + by a specially-crafted block of invalid deflated data. + + +Changes since version 0.0.5: +- added 'flush()' method to com.jcraft.jzlib.ZOutputStream. +- fixed to take care when occurring the buffer overflow in + com.jcraft.jzlib.ZOutputStream. +Many thanks to Tim Bendfelt at cs.wisc.edu , who pointed out above problems. + + +Changes since version 0.0.4: +............................ +- fixed a bug in Adler32 class. +- fixed a bug in ZInputStream class +- modified ZInputStream to be extended from InputStream + instead of FileInputStream. +- modified ZOutputStream to be extended from OutputStream + instead of FileOutputStream. +- modified ZStream to be changeable wbits. Give wbits value to + the method 'deflateInit' of ZStream. +Many thanks to Bryan Keller<[email protected]>, who reported bugs +and made suggestions. + + +Changes since version 0.0.3: +............................ +- fixed a bug in the compression level 0. +- modified to be compatible with JIKES's bug. +- added Z[Input,Output]Stream written by Lapo Luchini<[email protected]>. + + +Changes since version 0.0.2: +............................ +- fixed a critical bug, which had arisen in the deflating operation with + NO_FLUSH and DEFAULT_COMPRESSION mode. + Many thanks to Bryan Keller([email protected]), who reported this glitch. + + +Changes since version 0.0.1: +............................ +- fixed the bad compression ratio problem, which is reported from + Martin Smith([email protected]). The compression ratio was not so good + compared with the compression ration of zlib. Now, this problem has been + fixed and, I hope, that deflated files by JZlib and zlib are completely + same bit by bit. diff --git a/lib/jzlib/LICENSE.txt b/lib/jzlib/LICENSE.txt new file mode 100644 index 0000000..cdce500 --- /dev/null +++ b/lib/jzlib/LICENSE.txt @@ -0,0 +1,29 @@ +JZlib 0.0.* were released under the GNU LGPL license. Later, we have switched +over to a BSD-style license. + +------------------------------------------------------------------------------ +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/jzlib/README b/lib/jzlib/README new file mode 100644 index 0000000..45027db --- /dev/null +++ b/lib/jzlib/README @@ -0,0 +1,124 @@ + + JZlib + + zlib in pure Java(TM) + by [email protected], JCraft,Inc. + + http://www.jcraft.com/jzlib/ + +Last modified: Fri Feb 14 13:31:26 UTC 2003 + +Description +=========== +JZlib is a re-implementation of zlib in pure Java. +The first and final aim for hacking this stuff is +to add the packet compression support to pure Java SSH systems. + + +Documentation +============= +* README files all over the source tree have info related to the stuff + in the directories. +* ChangeLog: what changed from the previous version? +* LICENSE.txt + + +Directories & Files in the Source Tree +====================================== +* com/ has source trees of JZlib. +* example/ has some samples, which demonstrate the usages. +* misc/ has some stuffs. At present, this directory includes + a patch file for MindTerm v.1.2.1, which adds the packet compression + functionality. + + +Features +======== +* Needless to say, JZlib can inflate data, which is deflated by zlib and + JZlib can generate deflated data, which is acceptable and inflated by zlib. +* JZlib supports all compression level and all flushing mode in zlib. +* JZlib does not support gzip file handling supports. +* The performance has not been estimated yet, but it will be not so bad + in deflating/inflating data stream on the low bandwidth network. +* JZlib is licensed under BSD style license. +* Any invention has not been done in developing JZlib. + So, if zlib is patent free, JZlib is also not covered by any patents. + + +Why JZlib? +========== +Java Platform API provides packages 'java.util.zip.*' for +accessing to zlib, but that support is very limited +if you need to use the essence of zlib. For example, +we needed to full access to zlib to add the packet compression +support to pure Java SSH system, but they are useless for our requirements. +The Internet draft, SSH Transport Layer Protocol, says in the section '4.2 Compression' as follows, + + The following compression methods are currently defined: + none REQUIRED no compression + zlib OPTIONAL GNU ZLIB (LZ77) compression + The "zlib" compression is described in [RFC-1950] and in [RFC-1951]. The + compression context is initialized after each key exchange, and is + passed from one packet to the next with only a partial flush being + performed at the end of each packet. A partial flush means that all data + will be output, but the next packet will continue using compression + tables from the end of the previous packet. + +To implement this functionality, the Z_PARTIAL_FLUSH mode of zlib must be +used, however JDK does not permit us to do so. It seems that this problem has +been well known and some people have already reported to +JavaSoft's BugParade(for example, BugId:4255743), +but any positive response has not been returned from JavaSoft, +so this problem will not be solved forever. +This is our motivation to hack JZlib. + + +A unofficial patch for MindTerm v.1.2.1 +======================================= +A unofficial patch file for MindTerm v.1.2.1 has included in 'misc' directory. +It adds the packet compression support to MindTerm. +Please refer to 'misc/README' file. + + +Copyrights & Disclaimers +======================== +JZlib is copyrighted by ymnk, JCraft,Inc. and is licensed through BSD +style license. Read the LICENSE.txt file for the complete license. +ZInputStream and ZOutputStream classes were contributed by Lapo Luchini. + + +Credits +======= +JZlib has been developed by [email protected], +but he has just re-implemented zlib in pure Java. +So, all credit should go to authors Jean-loup Gailly and Mark Adler +and contributors of zlib. Here is the copyright notice of zlib version 1.1.3, + + |Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler + | + |This software is provided 'as-is', without any express or implied + |warranty. In no event will the authors be held liable for any damages + |arising from the use of this software. + | + |Permission is granted to anyone to use this software for any purpose, + |including commercial applications, and to alter it and redistribute it + |freely, subject to the following restrictions: + | + |1. The origin of this software must not be misrepresented; you must not + | claim that you wrote the original software. If you use this software + | in a product, an acknowledgment in the product documentation would be + | appreciated but is not required. + |2. Altered source versions must be plainly marked as such, and must not be + | misrepresented as being the original software. + |3. This notice may not be removed or altered from any source distribution. + | + |Jean-loup Gailly Mark Adler + |[email protected] [email protected] + + +If you have any comments, suggestions and questions, write us +at [email protected] + + +``SSH is a registered trademark and Secure Shell is a trademark of +SSH Communications Security Corp (www.ssh.com)''. diff --git a/lib/jzlib/com/jcraft/jzlib/Adler32.java b/lib/jzlib/com/jcraft/jzlib/Adler32.java new file mode 100644 index 0000000..d8b6ef8 --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/Adler32.java @@ -0,0 +1,94 @@ +/* -*-mode:java; c-basic-offset:2; -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +final class Adler32{ + + // largest prime smaller than 65536 + static final private int BASE=65521; + // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 + static final private int NMAX=5552; + + long adler32(long adler, byte[] buf, int index, int len){ + if(buf == null){ return 1L; } + + long s1=adler&0xffff; + long s2=(adler>>16)&0xffff; + int k; + + while(len > 0) { + k=len<NMAX?len:NMAX; + len-=k; + while(k>=16){ + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + s1+=buf[index++]&0xff; s2+=s1; + k-=16; + } + if(k!=0){ + do{ + s1+=buf[index++]&0xff; s2+=s1; + } + while(--k!=0); + } + s1%=BASE; + s2%=BASE; + } + return (s2<<16)|s1; + } + + /* + private java.util.zip.Adler32 adler=new java.util.zip.Adler32(); + long adler32(long value, byte[] buf, int index, int len){ + if(value==1) {adler.reset();} + if(buf==null) {adler.reset();} + else{adler.update(buf, index, len);} + return adler.getValue(); + } + */ +} diff --git a/lib/jzlib/com/jcraft/jzlib/Deflate.java b/lib/jzlib/com/jcraft/jzlib/Deflate.java new file mode 100644 index 0000000..9978802 --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/Deflate.java @@ -0,0 +1,1623 @@ +/* -*-mode:java; c-basic-offset:2; -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +public +final class Deflate{ + + static final private int MAX_MEM_LEVEL=9; + + static final private int Z_DEFAULT_COMPRESSION=-1; + + static final private int MAX_WBITS=15; // 32K LZ77 window + static final private int DEF_MEM_LEVEL=8; + + static class Config{ + int good_length; // reduce lazy search above this match length + int max_lazy; // do not perform lazy search above this match length + int nice_length; // quit search above this match length + int max_chain; + int func; + Config(int good_length, int max_lazy, + int nice_length, int max_chain, int func){ + this.good_length=good_length; + this.max_lazy=max_lazy; + this.nice_length=nice_length; + this.max_chain=max_chain; + this.func=func; + } + } + + static final private int STORED=0; + static final private int FAST=1; + static final private int SLOW=2; + static final private Config[] config_table; + static{ + config_table=new Config[10]; + // good lazy nice chain + config_table[0]=new Config(0, 0, 0, 0, STORED); + config_table[1]=new Config(4, 4, 8, 4, FAST); + config_table[2]=new Config(4, 5, 16, 8, FAST); + config_table[3]=new Config(4, 6, 32, 32, FAST); + + config_table[4]=new Config(4, 4, 16, 16, SLOW); + config_table[5]=new Config(8, 16, 32, 32, SLOW); + config_table[6]=new Config(8, 16, 128, 128, SLOW); + config_table[7]=new Config(8, 32, 128, 256, SLOW); + config_table[8]=new Config(32, 128, 258, 1024, SLOW); + config_table[9]=new Config(32, 258, 258, 4096, SLOW); + } + + static final private String[] z_errmsg = { + "need dictionary", // Z_NEED_DICT 2 + "stream end", // Z_STREAM_END 1 + "", // Z_OK 0 + "file error", // Z_ERRNO (-1) + "stream error", // Z_STREAM_ERROR (-2) + "data error", // Z_DATA_ERROR (-3) + "insufficient memory", // Z_MEM_ERROR (-4) + "buffer error", // Z_BUF_ERROR (-5) + "incompatible version",// Z_VERSION_ERROR (-6) + "" + }; + + // block not completed, need more input or more output + static final private int NeedMore=0; + + // block flush performed + static final private int BlockDone=1; + + // finish started, need only more output at next deflate + static final private int FinishStarted=2; + + // finish done, accept no more input or output + static final private int FinishDone=3; + + // preset dictionary flag in zlib header + static final private int PRESET_DICT=0x20; + + static final private int Z_FILTERED=1; + static final private int Z_HUFFMAN_ONLY=2; + static final private int Z_DEFAULT_STRATEGY=0; + + static final private int Z_NO_FLUSH=0; + static final private int Z_PARTIAL_FLUSH=1; + static final private int Z_SYNC_FLUSH=2; + static final private int Z_FULL_FLUSH=3; + static final private int Z_FINISH=4; + + static final private int Z_OK=0; + static final private int Z_STREAM_END=1; + static final private int Z_NEED_DICT=2; + static final private int Z_ERRNO=-1; + static final private int Z_STREAM_ERROR=-2; + static final private int Z_DATA_ERROR=-3; + static final private int Z_MEM_ERROR=-4; + static final private int Z_BUF_ERROR=-5; + static final private int Z_VERSION_ERROR=-6; + + static final private int INIT_STATE=42; + static final private int BUSY_STATE=113; + static final private int FINISH_STATE=666; + + // The deflate compression method + static final private int Z_DEFLATED=8; + + static final private int STORED_BLOCK=0; + static final private int STATIC_TREES=1; + static final private int DYN_TREES=2; + + // The three kinds of block type + static final private int Z_BINARY=0; + static final private int Z_ASCII=1; + static final private int Z_UNKNOWN=2; + + static final private int Buf_size=8*2; + + // repeat previous bit length 3-6 times (2 bits of repeat count) + static final private int REP_3_6=16; + + // repeat a zero length 3-10 times (3 bits of repeat count) + static final private int REPZ_3_10=17; + + // repeat a zero length 11-138 times (7 bits of repeat count) + static final private int REPZ_11_138=18; + + static final private int MIN_MATCH=3; + static final private int MAX_MATCH=258; + static final private int MIN_LOOKAHEAD=(MAX_MATCH+MIN_MATCH+1); + + static final private int MAX_BITS=15; + static final private int D_CODES=30; + static final private int BL_CODES=19; + static final private int LENGTH_CODES=29; + static final private int LITERALS=256; + static final private int L_CODES=(LITERALS+1+LENGTH_CODES); + static final private int HEAP_SIZE=(2*L_CODES+1); + + static final private int END_BLOCK=256; + + ZStream strm; // pointer back to this zlib stream + int status; // as the name implies + byte[] pending_buf; // output still pending + int pending_buf_size; // size of pending_buf + int pending_out; // next pending byte to output to the stream + int pending; // nb of bytes in the pending buffer + int noheader; // suppress zlib header and adler32 + byte data_type; // UNKNOWN, BINARY or ASCII + byte method; // STORED (for zip only) or DEFLATED + int last_flush; // value of flush param for previous deflate call + + int w_size; // LZ77 window size (32K by default) + int w_bits; // log2(w_size) (8..16) + int w_mask; // w_size - 1 + + byte[] window; + // Sliding window. Input bytes are read into the second half of the window, + // and move to the first half later to keep a dictionary of at least wSize + // bytes. With this organization, matches are limited to a distance of + // wSize-MAX_MATCH bytes, but this ensures that IO is always + // performed with a length multiple of the block size. Also, it limits + // the window size to 64K, which is quite useful on MSDOS. + // To do: use the user input buffer as sliding window. + + int window_size; + // Actual size of window: 2*wSize, except when the user input buffer + // is directly used as sliding window. + + short[] prev; + // Link to older string with same hash index. To limit the size of this + // array to 64K, this link is maintained only for the last 32K strings. + // An index in this array is thus a window index modulo 32K. + + short[] head; // Heads of the hash chains or NIL. + + int ins_h; // hash index of string to be inserted + int hash_size; // number of elements in hash table + int hash_bits; // log2(hash_size) + int hash_mask; // hash_size-1 + + // Number of bits by which ins_h must be shifted at each input + // step. It must be such that after MIN_MATCH steps, the oldest + // byte no longer takes part in the hash key, that is: + // hash_shift * MIN_MATCH >= hash_bits + int hash_shift; + + // Window position at the beginning of the current output block. Gets + // negative when the window is moved backwards. + + int block_start; + + int match_length; // length of best match + int prev_match; // previous match + int match_available; // set if previous match exists + int strstart; // start of string to insert + int match_start; // start of matching string + int lookahead; // number of valid bytes ahead in window + + // Length of the best match at previous step. Matches not greater than this + // are discarded. This is used in the lazy match evaluation. + int prev_length; + + // To speed up deflation, hash chains are never searched beyond this + // length. A higher limit improves compression ratio but degrades the speed. + int max_chain_length; + + // Attempt to find a better match only when the current match is strictly + // smaller than this value. This mechanism is used only for compression + // levels >= 4. + int max_lazy_match; + + // Insert new strings in the hash table only if the match length is not + // greater than this length. This saves time but degrades compression. + // max_insert_length is used only for compression levels <= 3. + + int level; // compression level (1..9) + int strategy; // favor or force Huffman coding + + // Use a faster search when the previous match is longer than this + int good_match; + + // Stop searching when current match exceeds this + int nice_match; + + short[] dyn_ltree; // literal and length tree + short[] dyn_dtree; // distance tree + short[] bl_tree; // Huffman tree for bit lengths + + Tree l_desc=new Tree(); // desc for literal tree + Tree d_desc=new Tree(); // desc for distance tree + Tree bl_desc=new Tree(); // desc for bit length tree + + // number of codes at each bit length for an optimal tree + short[] bl_count=new short[MAX_BITS+1]; + + // heap used to build the Huffman trees + int[] heap=new int[2*L_CODES+1]; + + int heap_len; // number of elements in the heap + int heap_max; // element of largest frequency + // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + // The same heap array is used to build all trees. + + // Depth of each subtree used as tie breaker for trees of equal frequency + byte[] depth=new byte[2*L_CODES+1]; + + int l_buf; // index for literals or lengths */ + + // Size of match buffer for literals/lengths. There are 4 reasons for + // limiting lit_bufsize to 64K: + // - frequencies can be kept in 16 bit counters + // - if compression is not successful for the first block, all input + // data is still in the window so we can still emit a stored block even + // when input comes from standard input. (This can also be done for + // all blocks if lit_bufsize is not greater than 32K.) + // - if compression is not successful for a file smaller than 64K, we can + // even emit a stored file instead of a stored block (saving 5 bytes). + // This is applicable only for zip (not gzip or zlib). + // - creating new Huffman trees less frequently may not provide fast + // adaptation to changes in the input data statistics. (Take for + // example a binary file with poorly compressible code followed by + // a highly compressible string table.) Smaller buffer sizes give + // fast adaptation but have of course the overhead of transmitting + // trees more frequently. + // - I can't count above 4 + int lit_bufsize; + + int last_lit; // running index in l_buf + + // Buffer for distances. To simplify the code, d_buf and l_buf have + // the same number of elements. To use different lengths, an extra flag + // array would be necessary. + + int d_buf; // index of pendig_buf + + int opt_len; // bit length of current block with optimal trees + int static_len; // bit length of current block with static trees + int matches; // number of string matches in current block + int last_eob_len; // bit length of EOB code for last block + + // Output buffer. bits are inserted starting at the bottom (least + // significant bits). + short bi_buf; + + // Number of valid bits in bi_buf. All bits above the last valid bit + // are always zero. + int bi_valid; + + Deflate(){ + dyn_ltree=new short[HEAP_SIZE*2]; + dyn_dtree=new short[(2*D_CODES+1)*2]; // distance tree + bl_tree=new short[(2*BL_CODES+1)*2]; // Huffman tree for bit lengths + } + + void lm_init() { + window_size=2*w_size; + + head[hash_size-1]=0; + for(int i=0; i<hash_size-1; i++){ + head[i]=0; + } + + // Set the default configuration parameters: + max_lazy_match = Deflate.config_table[level].max_lazy; + good_match = Deflate.config_table[level].good_length; + nice_match = Deflate.config_table[level].nice_length; + max_chain_length = Deflate.config_table[level].max_chain; + + strstart = 0; + block_start = 0; + lookahead = 0; + match_length = prev_length = MIN_MATCH-1; + match_available = 0; + ins_h = 0; + } + + // Initialize the tree data structures for a new zlib stream. + void tr_init(){ + + l_desc.dyn_tree = dyn_ltree; + l_desc.stat_desc = StaticTree.static_l_desc; + + d_desc.dyn_tree = dyn_dtree; + d_desc.stat_desc = StaticTree.static_d_desc; + + bl_desc.dyn_tree = bl_tree; + bl_desc.stat_desc = StaticTree.static_bl_desc; + + bi_buf = 0; + bi_valid = 0; + last_eob_len = 8; // enough lookahead for inflate + + // Initialize the first block of the first file: + init_block(); + } + + void init_block(){ + // Initialize the trees. + for(int i = 0; i < L_CODES; i++) dyn_ltree[i*2] = 0; + for(int i= 0; i < D_CODES; i++) dyn_dtree[i*2] = 0; + for(int i= 0; i < BL_CODES; i++) bl_tree[i*2] = 0; + + dyn_ltree[END_BLOCK*2] = 1; + opt_len = static_len = 0; + last_lit = matches = 0; + } + + // Restore the heap property by moving down the tree starting at node k, + // exchanging a node with the smallest of its two sons if necessary, stopping + // when the heap property is re-established (each father smaller than its + // two sons). + void pqdownheap(short[] tree, // the tree to restore + int k // node to move down + ){ + int v = heap[k]; + int j = k << 1; // left son of k + while (j <= heap_len) { + // Set j to the smallest of the two sons: + if (j < heap_len && + smaller(tree, heap[j+1], heap[j], depth)){ + j++; + } + // Exit if v is smaller than both sons + if(smaller(tree, v, heap[j], depth)) break; + + // Exchange v with the smallest son + heap[k]=heap[j]; k = j; + // And continue down the tree, setting j to the left son of k + j <<= 1; + } + heap[k] = v; + } + + static boolean smaller(short[] tree, int n, int m, byte[] depth){ + short tn2=tree[n*2]; + short tm2=tree[m*2]; + return (tn2<tm2 || + (tn2==tm2 && depth[n] <= depth[m])); + } + + // Scan a literal or distance tree to determine the frequencies of the codes + // in the bit length tree. + void scan_tree (short[] tree,// the tree to be scanned + int max_code // and its largest code of non zero frequency + ){ + int n; // iterates over all tree elements + int prevlen = -1; // last emitted length + int curlen; // length of current code + int nextlen = tree[0*2+1]; // length of next code + int count = 0; // repeat count of the current code + int max_count = 7; // max repeat count + int min_count = 4; // min repeat count + + if (nextlen == 0){ max_count = 138; min_count = 3; } + tree[(max_code+1)*2+1] = (short)0xffff; // guard + + for(n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[(n+1)*2+1]; + if(++count < max_count && curlen == nextlen) { + continue; + } + else if(count < min_count) { + bl_tree[curlen*2] += count; + } + else if(curlen != 0) { + if(curlen != prevlen) bl_tree[curlen*2]++; + bl_tree[REP_3_6*2]++; + } + else if(count <= 10) { + bl_tree[REPZ_3_10*2]++; + } + else{ + bl_tree[REPZ_11_138*2]++; + } + count = 0; prevlen = curlen; + if(nextlen == 0) { + max_count = 138; min_count = 3; + } + else if(curlen == nextlen) { + max_count = 6; min_count = 3; + } + else{ + max_count = 7; min_count = 4; + } + } + } + + // Construct the Huffman tree for the bit lengths and return the index in + // bl_order of the last bit length code to send. + int build_bl_tree(){ + int max_blindex; // index of last bit length code of non zero freq + + // Determine the bit length frequencies for literal and distance trees + scan_tree(dyn_ltree, l_desc.max_code); + scan_tree(dyn_dtree, d_desc.max_code); + + // Build the bit length tree: + bl_desc.build_tree(this); + // opt_len now includes the length of the tree representations, except + // the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + + // Determine the number of bit length codes to send. The pkzip format + // requires that at least 4 bit length codes be sent. (appnote.txt says + // 3 but the actual value used is 4.) + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (bl_tree[Tree.bl_order[max_blindex]*2+1] != 0) break; + } + // Update opt_len to include the bit length tree and counts + opt_len += 3*(max_blindex+1) + 5+5+4; + + return max_blindex; + } + + + // Send the header for a block using dynamic Huffman trees: the counts, the + // lengths of the bit length codes, the literal tree and the distance tree. + // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + void send_all_trees(int lcodes, int dcodes, int blcodes){ + int rank; // index in bl_order + + send_bits(lcodes-257, 5); // not +255 as stated in appnote.txt + send_bits(dcodes-1, 5); + send_bits(blcodes-4, 4); // not -3 as stated in appnote.txt + for (rank = 0; rank < blcodes; rank++) { + send_bits(bl_tree[Tree.bl_order[rank]*2+1], 3); + } + send_tree(dyn_ltree, lcodes-1); // literal tree + send_tree(dyn_dtree, dcodes-1); // distance tree + } + + // Send a literal or distance tree in compressed form, using the codes in + // bl_tree. + void send_tree (short[] tree,// the tree to be sent + int max_code // and its largest code of non zero frequency + ){ + int n; // iterates over all tree elements + int prevlen = -1; // last emitted length + int curlen; // length of current code + int nextlen = tree[0*2+1]; // length of next code + int count = 0; // repeat count of the current code + int max_count = 7; // max repeat count + int min_count = 4; // min repeat count + + if (nextlen == 0){ max_count = 138; min_count = 3; } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[(n+1)*2+1]; + if(++count < max_count && curlen == nextlen) { + continue; + } + else if(count < min_count) { + do { send_code(curlen, bl_tree); } while (--count != 0); + } + else if(curlen != 0){ + if(curlen != prevlen){ + send_code(curlen, bl_tree); count--; + } + send_code(REP_3_6, bl_tree); + send_bits(count-3, 2); + } + else if(count <= 10){ + send_code(REPZ_3_10, bl_tree); + send_bits(count-3, 3); + } + else{ + send_code(REPZ_11_138, bl_tree); + send_bits(count-11, 7); + } + count = 0; prevlen = curlen; + if(nextlen == 0){ + max_count = 138; min_count = 3; + } + else if(curlen == nextlen){ + max_count = 6; min_count = 3; + } + else{ + max_count = 7; min_count = 4; + } + } + } + + // Output a byte on the stream. + // IN assertion: there is enough room in pending_buf. + final void put_byte(byte[] p, int start, int len){ + System.arraycopy(p, start, pending_buf, pending, len); + pending+=len; + } + + final void put_byte(byte c){ + pending_buf[pending++]=c; + } + final void put_short(int w) { + put_byte((byte)(w/*&0xff*/)); + put_byte((byte)(w>>>8)); + } + final void putShortMSB(int b){ + put_byte((byte)(b>>8)); + put_byte((byte)(b/*&0xff*/)); + } + + final void send_code(int c, short[] tree){ + int c2=c*2; + send_bits((tree[c2]&0xffff), (tree[c2+1]&0xffff)); + } + + void send_bits(int value, int length){ + int len = length; + if (bi_valid > (int)Buf_size - len) { + int val = value; +// bi_buf |= (val << bi_valid); + bi_buf |= ((val << bi_valid)&0xffff); + put_short(bi_buf); + bi_buf = (short)(val >>> (Buf_size - bi_valid)); + bi_valid += len - Buf_size; + } else { +// bi_buf |= (value) << bi_valid; + bi_buf |= (((value) << bi_valid)&0xffff); + bi_valid += len; + } + } + + // Send one empty static block to give enough lookahead for inflate. + // This takes 10 bits, of which 7 may remain in the bit buffer. + // The current inflate code requires 9 bits of lookahead. If the + // last two codes for the previous block (real code plus EOB) were coded + // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode + // the last real code. In this case we send two empty static blocks instead + // of one. (There are no problems if the previous block is stored or fixed.) + // To simplify the code, we assume the worst case of last real code encoded + // on one bit only. + void _tr_align(){ + send_bits(STATIC_TREES<<1, 3); + send_code(END_BLOCK, StaticTree.static_ltree); + + bi_flush(); + + // Of the 10 bits for the empty block, we have already sent + // (10 - bi_valid) bits. The lookahead for the last real code (before + // the EOB of the previous block) was thus at least one plus the length + // of the EOB plus what we have just sent of the empty static block. + if (1 + last_eob_len + 10 - bi_valid < 9) { + send_bits(STATIC_TREES<<1, 3); + send_code(END_BLOCK, StaticTree.static_ltree); + bi_flush(); + } + last_eob_len = 7; + } + + + // Save the match info and tally the frequency counts. Return true if + // the current block must be flushed. + boolean _tr_tally (int dist, // distance of matched string + int lc // match length-MIN_MATCH or unmatched char (if dist==0) + ){ + + pending_buf[d_buf+last_lit*2] = (byte)(dist>>>8); + pending_buf[d_buf+last_lit*2+1] = (byte)dist; + + pending_buf[l_buf+last_lit] = (byte)lc; last_lit++; + + if (dist == 0) { + // lc is the unmatched char + dyn_ltree[lc*2]++; + } + else { + matches++; + // Here, lc is the match length - MIN_MATCH + dist--; // dist = match distance - 1 + dyn_ltree[(Tree._length_code[lc]+LITERALS+1)*2]++; + dyn_dtree[Tree.d_code(dist)*2]++; + } + + if ((last_lit & 0x1fff) == 0 && level > 2) { + // Compute an upper bound for the compressed length + int out_length = last_lit*8; + int in_length = strstart - block_start; + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (int)dyn_dtree[dcode*2] * + (5L+Tree.extra_dbits[dcode]); + } + out_length >>>= 3; + if ((matches < (last_lit/2)) && out_length < in_length/2) return true; + } + + return (last_lit == lit_bufsize-1); + // We avoid equality with lit_bufsize because of wraparound at 64K + // on 16 bit machines and because stored blocks are restricted to + // 64K-1 bytes. + } + + // Send the block data compressed using the given Huffman trees + void compress_block(short[] ltree, short[] dtree){ + int dist; // distance of matched string + int lc; // match length or unmatched char (if dist == 0) + int lx = 0; // running index in l_buf + int code; // the code to send + int extra; // number of extra bits to send + + if (last_lit != 0){ + do{ + dist=((pending_buf[d_buf+lx*2]<<8)&0xff00)| + (pending_buf[d_buf+lx*2+1]&0xff); + lc=(pending_buf[l_buf+lx])&0xff; lx++; + + if(dist == 0){ + send_code(lc, ltree); // send a literal byte + } + else{ + // Here, lc is the match length - MIN_MATCH + code = Tree._length_code[lc]; + + send_code(code+LITERALS+1, ltree); // send the length code + extra = Tree.extra_lbits[code]; + if(extra != 0){ + lc -= Tree.base_length[code]; + send_bits(lc, extra); // send the extra length bits + } + dist--; // dist is now the match distance - 1 + code = Tree.d_code(dist); + + send_code(code, dtree); // send the distance code + extra = Tree.extra_dbits[code]; + if (extra != 0) { + dist -= Tree.base_dist[code]; + send_bits(dist, extra); // send the extra distance bits + } + } // literal or match pair ? + + // Check that the overlay between pending_buf and d_buf+l_buf is ok: + } + while (lx < last_lit); + } + + send_code(END_BLOCK, ltree); + last_eob_len = ltree[END_BLOCK*2+1]; + } + + // Set the data type to ASCII or BINARY, using a crude approximation: + // binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. + // IN assertion: the fields freq of dyn_ltree are set and the total of all + // frequencies does not exceed 64K (to fit in an int on 16 bit machines). + void set_data_type(){ + int n = 0; + int ascii_freq = 0; + int bin_freq = 0; + while(n<7){ bin_freq += dyn_ltree[n*2]; n++;} + while(n<128){ ascii_freq += dyn_ltree[n*2]; n++;} + while(n<LITERALS){ bin_freq += dyn_ltree[n*2]; n++;} + data_type=(byte)(bin_freq > (ascii_freq >>> 2) ? Z_BINARY : Z_ASCII); + } + + // Flush the bit buffer, keeping at most 7 bits in it. + void bi_flush(){ + if (bi_valid == 16) { + put_short(bi_buf); + bi_buf=0; + bi_valid=0; + } + else if (bi_valid >= 8) { + put_byte((byte)bi_buf); + bi_buf>>>=8; + bi_valid-=8; + } + } + + // Flush the bit buffer and align the output on a byte boundary + void bi_windup(){ + if (bi_valid > 8) { + put_short(bi_buf); + } else if (bi_valid > 0) { + put_byte((byte)bi_buf); + } + bi_buf = 0; + bi_valid = 0; + } + + // Copy a stored block, storing first the length and its + // one's complement if requested. + void copy_block(int buf, // the input data + int len, // its length + boolean header // true if block header must be written + ){ + int index=0; + bi_windup(); // align on byte boundary + last_eob_len = 8; // enough lookahead for inflate + + if (header) { + put_short((short)len); + put_short((short)~len); + } + + // while(len--!=0) { + // put_byte(window[buf+index]); + // index++; + // } + put_byte(window, buf, len); + } + + void flush_block_only(boolean eof){ + _tr_flush_block(block_start>=0 ? block_start : -1, + strstart-block_start, + eof); + block_start=strstart; + strm.flush_pending(); + } + + // Copy without compression as much as possible from the input stream, return + // the current block state. + // This function does not insert new strings in the dictionary since + // uncompressible data is probably not useful. This function is used + // only for the level=0 compression option. + // NOTE: this function should be optimized to avoid extra copying from + // window to pending_buf. + int deflate_stored(int flush){ + // Stored blocks are limited to 0xffff bytes, pending_buf is limited + // to pending_buf_size, and each stored block has a 5 byte header: + + int max_block_size = 0xffff; + int max_start; + + if(max_block_size > pending_buf_size - 5) { + max_block_size = pending_buf_size - 5; + } + + // Copy as much as possible from input to output: + while(true){ + // Fill the window as much as possible: + if(lookahead<=1){ + fill_window(); + if(lookahead==0 && flush==Z_NO_FLUSH) return NeedMore; + if(lookahead==0) break; // flush the current block + } + + strstart+=lookahead; + lookahead=0; + + // Emit a stored block if pending_buf will be full: + max_start=block_start+max_block_size; + if(strstart==0|| strstart>=max_start) { + // strstart == 0 is possible when wraparound on 16-bit machine + lookahead = (int)(strstart-max_start); + strstart = (int)max_start; + + flush_block_only(false); + if(strm.avail_out==0) return NeedMore; + + } + + // Flush if we may have to slide, otherwise block_start may become + // negative and the data will be gone: + if(strstart-block_start >= w_size-MIN_LOOKAHEAD) { + flush_block_only(false); + if(strm.avail_out==0) return NeedMore; + } + } + + flush_block_only(flush == Z_FINISH); + if(strm.avail_out==0) + return (flush == Z_FINISH) ? FinishStarted : NeedMore; + + return flush == Z_FINISH ? FinishDone : BlockDone; + } + + // Send a stored block + void _tr_stored_block(int buf, // input block + int stored_len, // length of input block + boolean eof // true if this is the last block for a file + ){ + send_bits((STORED_BLOCK<<1)+(eof?1:0), 3); // send block type + copy_block(buf, stored_len, true); // with header + } + + // Determine the best encoding for the current block: dynamic trees, static + // trees or store, and output the encoded block to the zip file. + void _tr_flush_block(int buf, // input block, or NULL if too old + int stored_len, // length of input block + boolean eof // true if this is the last block for a file + ) { + int opt_lenb, static_lenb;// opt_len and static_len in bytes + int max_blindex = 0; // index of last bit length code of non zero freq + + // Build the Huffman trees unless a stored block is forced + if(level > 0) { + // Check if the file is ascii or binary + if(data_type == Z_UNKNOWN) set_data_type(); + + // Construct the literal and distance trees + l_desc.build_tree(this); + + d_desc.build_tree(this); + + // At this point, opt_len and static_len are the total bit lengths of + // the compressed block data, excluding the tree representations. + + // Build the bit length tree for the above two trees, and get the index + // in bl_order of the last bit length code to send. + max_blindex=build_bl_tree(); + + // Determine the best encoding. Compute first the block length in bytes + opt_lenb=(opt_len+3+7)>>>3; + static_lenb=(static_len+3+7)>>>3; + + if(static_lenb<=opt_lenb) opt_lenb=static_lenb; + } + else { + opt_lenb=static_lenb=stored_len+5; // force a stored block + } + + if(stored_len+4<=opt_lenb && buf != -1){ + // 4: two words for the lengths + // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + // Otherwise we can't have processed more than WSIZE input bytes since + // the last block flush, because compression would have been + // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + // transform a block into a stored block. + _tr_stored_block(buf, stored_len, eof); + } + else if(static_lenb == opt_lenb){ + send_bits((STATIC_TREES<<1)+(eof?1:0), 3); + compress_block(StaticTree.static_ltree, StaticTree.static_dtree); + } + else{ + send_bits((DYN_TREES<<1)+(eof?1:0), 3); + send_all_trees(l_desc.max_code+1, d_desc.max_code+1, max_blindex+1); + compress_block(dyn_ltree, dyn_dtree); + } + + // The above check is made mod 2^32, for files larger than 512 MB + // and uLong implemented on 32 bits. + + init_block(); + + if(eof){ + bi_windup(); + } + } + + // Fill the window when the lookahead becomes insufficient. + // Updates strstart and lookahead. + // + // IN assertion: lookahead < MIN_LOOKAHEAD + // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + // At least one byte has been read, or avail_in == 0; reads are + // performed for at least two bytes (required for the zip translate_eol + // option -- not supported here). + void fill_window(){ + int n, m; + int p; + int more; // Amount of free space at the end of the window. + + do{ + more = (window_size-lookahead-strstart); + + // Deal with !@#$% 64K limit: + if(more==0 && strstart==0 && lookahead==0){ + more = w_size; + } + else if(more==-1) { + // Very unlikely, but possible on 16 bit machine if strstart == 0 + // and lookahead == 1 (input done one byte at time) + more--; + + // If the window is almost full and there is insufficient lookahead, + // move the upper half to the lower one to make room in the upper half. + } + else if(strstart >= w_size+ w_size-MIN_LOOKAHEAD) { + System.arraycopy(window, w_size, window, 0, w_size); + match_start-=w_size; + strstart-=w_size; // we now have strstart >= MAX_DIST + block_start-=w_size; + + // Slide the hash table (could be avoided with 32 bit values + // at the expense of memory usage). We slide even when level == 0 + // to keep the hash table consistent if we switch back to level > 0 + // later. (Using level 0 permanently is not an optimal usage of + // zlib, so we don't care about this pathological case.) + + n = hash_size; + p=n; + do { + m = (head[--p]&0xffff); + head[p]=(m>=w_size ? (short)(m-w_size) : 0); + } + while (--n != 0); + + n = w_size; + p = n; + do { + m = (prev[--p]&0xffff); + prev[p] = (m >= w_size ? (short)(m-w_size) : 0); + // If n is not on any hash chain, prev[n] is garbage but + // its value will never be used. + } + while (--n!=0); + more += w_size; + } + + if (strm.avail_in == 0) return; + + // If there was no sliding: + // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + // more == window_size - lookahead - strstart + // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + // => more >= window_size - 2*WSIZE + 2 + // In the BIG_MEM or MMAP case (not yet supported), + // window_size == input_size + MIN_LOOKAHEAD && + // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + // Otherwise, window_size == 2*WSIZE so more >= 2. + // If there was sliding, more >= WSIZE. So in all cases, more >= 2. + + n = strm.read_buf(window, strstart + lookahead, more); + lookahead += n; + + // Initialize the hash value now that we have some input: + if(lookahead >= MIN_MATCH) { + ins_h = window[strstart]&0xff; + ins_h=(((ins_h)<<hash_shift)^(window[strstart+1]&0xff))&hash_mask; + } + // If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + // but this is not important since only literal bytes will be emitted. + } + while (lookahead < MIN_LOOKAHEAD && strm.avail_in != 0); + } + + // Compress as much as possible from the input stream, return the current + // block state. + // This function does not perform lazy evaluation of matches and inserts + // new strings in the dictionary only for unmatched strings or for short + // matches. It is used only for the fast compression options. + int deflate_fast(int flush){ +// short hash_head = 0; // head of the hash chain + int hash_head = 0; // head of the hash chain + boolean bflush; // set if current block must be flushed + + while(true){ + // Make sure that we always have enough lookahead, except + // at the end of the input file. We need MAX_MATCH bytes + // for the next match, plus MIN_MATCH bytes to insert the + // string following the next match. + if(lookahead < MIN_LOOKAHEAD){ + fill_window(); + if(lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH){ + return NeedMore; + } + if(lookahead == 0) break; // flush the current block + } + + // Insert the string window[strstart .. strstart+2] in the + // dictionary, and set hash_head to the head of the hash chain: + if(lookahead >= MIN_MATCH){ + ins_h=(((ins_h)<<hash_shift)^(window[(strstart)+(MIN_MATCH-1)]&0xff))&hash_mask; + +// prev[strstart&w_mask]=hash_head=head[ins_h]; + hash_head=(head[ins_h]&0xffff); + prev[strstart&w_mask]=head[ins_h]; + head[ins_h]=(short)strstart; + } + + // Find the longest match, discarding those <= prev_length. + // At this point we have always match_length < MIN_MATCH + + if(hash_head!=0L && + ((strstart-hash_head)&0xffff) <= w_size-MIN_LOOKAHEAD + ){ + // To simplify the code, we prevent matches with the string + // of window index 0 (in particular we have to avoid a match + // of the string with itself at the start of the input file). + if(strategy != Z_HUFFMAN_ONLY){ + match_length=longest_match (hash_head); + } + // longest_match() sets match_start + } + if(match_length>=MIN_MATCH){ + // check_match(strstart, match_start, match_length); + + bflush=_tr_tally(strstart-match_start, match_length-MIN_MATCH); + + lookahead -= match_length; + + // Insert new strings in the hash table only if the match length + // is not too large. This saves time but degrades compression. + if(match_length <= max_lazy_match && + lookahead >= MIN_MATCH) { + match_length--; // string at strstart already in hash table + do{ + strstart++; + + ins_h=((ins_h<<hash_shift)^(window[(strstart)+(MIN_MATCH-1)]&0xff))&hash_mask; +// prev[strstart&w_mask]=hash_head=head[ins_h]; + hash_head=(head[ins_h]&0xffff); + prev[strstart&w_mask]=head[ins_h]; + head[ins_h]=(short)strstart; + + // strstart never exceeds WSIZE-MAX_MATCH, so there are + // always MIN_MATCH bytes ahead. + } + while (--match_length != 0); + strstart++; + } + else{ + strstart += match_length; + match_length = 0; + ins_h = window[strstart]&0xff; + + ins_h=(((ins_h)<<hash_shift)^(window[strstart+1]&0xff))&hash_mask; + // If lookahead < MIN_MATCH, ins_h is garbage, but it does not + // matter since it will be recomputed at next deflate call. + } + } + else { + // No match, output a literal byte + + bflush=_tr_tally(0, window[strstart]&0xff); + lookahead--; + strstart++; + } + if (bflush){ + + flush_block_only(false); + if(strm.avail_out==0) return NeedMore; + } + } + + flush_block_only(flush == Z_FINISH); + if(strm.avail_out==0){ + if(flush == Z_FINISH) return FinishStarted; + else return NeedMore; + } + return flush==Z_FINISH ? FinishDone : BlockDone; + } + + // Same as above, but achieves better compression. We use a lazy + // evaluation for matches: a match is finally adopted only if there is + // no better match at the next window position. + int deflate_slow(int flush){ +// short hash_head = 0; // head of hash chain + int hash_head = 0; // head of hash chain + boolean bflush; // set if current block must be flushed + + // Process the input block. + while(true){ + // Make sure that we always have enough lookahead, except + // at the end of the input file. We need MAX_MATCH bytes + // for the next match, plus MIN_MATCH bytes to insert the + // string following the next match. + + if (lookahead < MIN_LOOKAHEAD) { + fill_window(); + if(lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return NeedMore; + } + if(lookahead == 0) break; // flush the current block + } + + // Insert the string window[strstart .. strstart+2] in the + // dictionary, and set hash_head to the head of the hash chain: + + if(lookahead >= MIN_MATCH) { + ins_h=(((ins_h)<<hash_shift)^(window[(strstart)+(MIN_MATCH-1)]&0xff)) & hash_mask; +// prev[strstart&w_mask]=hash_head=head[ins_h]; + hash_head=(head[ins_h]&0xffff); + prev[strstart&w_mask]=head[ins_h]; + head[ins_h]=(short)strstart; + } + + // Find the longest match, discarding those <= prev_length. + prev_length = match_length; prev_match = match_start; + match_length = MIN_MATCH-1; + + if (hash_head != 0 && prev_length < max_lazy_match && + ((strstart-hash_head)&0xffff) <= w_size-MIN_LOOKAHEAD + ){ + // To simplify the code, we prevent matches with the string + // of window index 0 (in particular we have to avoid a match + // of the string with itself at the start of the input file). + + if(strategy != Z_HUFFMAN_ONLY) { + match_length = longest_match(hash_head); + } + // longest_match() sets match_start + + if (match_length <= 5 && (strategy == Z_FILTERED || + (match_length == MIN_MATCH && + strstart - match_start > 4096))) { + + // If prev_match is also MIN_MATCH, match_start is garbage + // but we will ignore the current match anyway. + match_length = MIN_MATCH-1; + } + } + + // If there was a match at the previous step and the current + // match is not better, output the previous match: + if(prev_length >= MIN_MATCH && match_length <= prev_length) { + int max_insert = strstart + lookahead - MIN_MATCH; + // Do not insert strings in hash table beyond this. + + // check_match(strstart-1, prev_match, prev_length); + + bflush=_tr_tally(strstart-1-prev_match, prev_length - MIN_MATCH); + + // Insert in hash table all strings up to the end of the match. + // strstart-1 and strstart are already inserted. If there is not + // enough lookahead, the last two strings are not inserted in + // the hash table. + lookahead -= prev_length-1; + prev_length -= 2; + do{ + if(++strstart <= max_insert) { + ins_h=(((ins_h)<<hash_shift)^(window[(strstart)+(MIN_MATCH-1)]&0xff))&hash_mask; + //prev[strstart&w_mask]=hash_head=head[ins_h]; + hash_head=(head[ins_h]&0xffff); + prev[strstart&w_mask]=head[ins_h]; + head[ins_h]=(short)strstart; + } + } + while(--prev_length != 0); + match_available = 0; + match_length = MIN_MATCH-1; + strstart++; + + if (bflush){ + flush_block_only(false); + if(strm.avail_out==0) return NeedMore; + } + } else if (match_available!=0) { + + // If there was no match at the previous position, output a + // single literal. If there was a match but the current match + // is longer, truncate the previous match to a single literal. + + bflush=_tr_tally(0, window[strstart-1]&0xff); + + if (bflush) { + flush_block_only(false); + } + strstart++; + lookahead--; + if(strm.avail_out == 0) return NeedMore; + } else { + // There is no previous match to compare with, wait for + // the next step to decide. + + match_available = 1; + strstart++; + lookahead--; + } + } + + if(match_available!=0) { + bflush=_tr_tally(0, window[strstart-1]&0xff); + match_available = 0; + } + flush_block_only(flush == Z_FINISH); + + if(strm.avail_out==0){ + if(flush == Z_FINISH) return FinishStarted; + else return NeedMore; + } + + return flush == Z_FINISH ? FinishDone : BlockDone; + } + + int longest_match(int cur_match){ + int chain_length = max_chain_length; // max hash chain length + int scan = strstart; // current string + int match; // matched string + int len; // length of current match + int best_len = prev_length; // best match length so far + int limit = strstart>(w_size-MIN_LOOKAHEAD) ? + strstart-(w_size-MIN_LOOKAHEAD) : 0; + int nice_match=this.nice_match; + + // Stop when cur_match becomes <= limit. To simplify the code, + // we prevent matches with the string of window index 0. + + int wmask = w_mask; + + int strend = strstart + MAX_MATCH; + byte scan_end1 = window[scan+best_len-1]; + byte scan_end = window[scan+best_len]; + + // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + // It is easy to get rid of this optimization if necessary. + + // Do not waste too much time if we already have a good match: + if (prev_length >= good_match) { + chain_length >>= 2; + } + + // Do not look for matches beyond the end of the input. This is necessary + // to make deflate deterministic. + if (nice_match > lookahead) nice_match = lookahead; + + do { + match = cur_match; + + // Skip to next match if the match length cannot increase + // or if the match length is less than 2: + if (window[match+best_len] != scan_end || + window[match+best_len-1] != scan_end1 || + window[match] != window[scan] || + window[++match] != window[scan+1]) continue; + + // The check at best_len-1 can be removed because it will be made + // again later. (This heuristic is not always a win.) + // It is not necessary to compare scan[2] and match[2] since they + // are always equal when the other bytes match, given that + // the hash keys are equal and that HASH_BITS >= 8. + scan += 2; match++; + + // We check for insufficient lookahead only every 8th comparison; + // the 256th check will be made at strstart+258. + do { + } while (window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + scan < strend); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + + if(len>best_len) { + match_start = cur_match; + best_len = len; + if (len >= nice_match) break; + scan_end1 = window[scan+best_len-1]; + scan_end = window[scan+best_len]; + } + + } while ((cur_match = (prev[cur_match & wmask]&0xffff)) > limit + && --chain_length != 0); + + if (best_len <= lookahead) return best_len; + return lookahead; + } + + int deflateInit(ZStream strm, int level, int bits){ + return deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY); + } + int deflateInit(ZStream strm, int level){ + return deflateInit(strm, level, MAX_WBITS); + } + int deflateInit2(ZStream strm, int level, int method, int windowBits, + int memLevel, int strategy){ + int noheader = 0; + // byte[] my_version=ZLIB_VERSION; + + // + // if (version == null || version[0] != my_version[0] + // || stream_size != sizeof(z_stream)) { + // return Z_VERSION_ERROR; + // } + + strm.msg = null; + + if (level == Z_DEFAULT_COMPRESSION) level = 6; + + if (windowBits < 0) { // undocumented feature: suppress zlib header + noheader = 1; + windowBits = -windowBits; + } + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || + method != Z_DEFLATED || + windowBits < 9 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_HUFFMAN_ONLY) { + return Z_STREAM_ERROR; + } + + strm.dstate = (Deflate)this; + + this.noheader = noheader; + w_bits = windowBits; + w_size = 1 << w_bits; + w_mask = w_size - 1; + + hash_bits = memLevel + 7; + hash_size = 1 << hash_bits; + hash_mask = hash_size - 1; + hash_shift = ((hash_bits+MIN_MATCH-1)/MIN_MATCH); + + window = new byte[w_size*2]; + prev = new short[w_size]; + head = new short[hash_size]; + + lit_bufsize = 1 << (memLevel + 6); // 16K elements by default + + // We overlay pending_buf and d_buf+l_buf. This works since the average + // output size for (length,distance) codes is <= 24 bits. + pending_buf = new byte[lit_bufsize*4]; + pending_buf_size = lit_bufsize*4; + + d_buf = lit_bufsize/2; + l_buf = (1+2)*lit_bufsize; + + this.level = level; + +//System.out.println("level="+level); + + this.strategy = strategy; + this.method = (byte)method; + + return deflateReset(strm); + } + + int deflateReset(ZStream strm){ + strm.total_in = strm.total_out = 0; + strm.msg = null; // + strm.data_type = Z_UNKNOWN; + + pending = 0; + pending_out = 0; + + if(noheader < 0) { + noheader = 0; // was set to -1 by deflate(..., Z_FINISH); + } + status = (noheader!=0) ? BUSY_STATE : INIT_STATE; + strm.adler=strm._adler.adler32(0, null, 0, 0); + + last_flush = Z_NO_FLUSH; + + tr_init(); + lm_init(); + return Z_OK; + } + + int deflateEnd(){ + if(status!=INIT_STATE && status!=BUSY_STATE && status!=FINISH_STATE){ + return Z_STREAM_ERROR; + } + // Deallocate in reverse order of allocations: + pending_buf=null; + head=null; + prev=null; + window=null; + // free + // dstate=null; + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; + } + + int deflateParams(ZStream strm, int _level, int _strategy){ + int err=Z_OK; + + if(_level == Z_DEFAULT_COMPRESSION){ + _level = 6; + } + if(_level < 0 || _level > 9 || + _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) { + return Z_STREAM_ERROR; + } + + if(config_table[level].func!=config_table[_level].func && + strm.total_in != 0) { + // Flush the last buffer: + err = strm.deflate(Z_PARTIAL_FLUSH); + } + + if(level != _level) { + level = _level; + max_lazy_match = config_table[level].max_lazy; + good_match = config_table[level].good_length; + nice_match = config_table[level].nice_length; + max_chain_length = config_table[level].max_chain; + } + strategy = _strategy; + return err; + } + + int deflateSetDictionary (ZStream strm, byte[] dictionary, int dictLength){ + int length = dictLength; + int index=0; + + if(dictionary == null || status != INIT_STATE) + return Z_STREAM_ERROR; + + strm.adler=strm._adler.adler32(strm.adler, dictionary, 0, dictLength); + + if(length < MIN_MATCH) return Z_OK; + if(length > w_size-MIN_LOOKAHEAD){ + length = w_size-MIN_LOOKAHEAD; + index=dictLength-length; // use the tail of the dictionary + } + System.arraycopy(dictionary, index, window, 0, length); + strstart = length; + block_start = length; + + // Insert all strings in the hash table (except for the last two bytes). + // s->lookahead stays null, so s->ins_h will be recomputed at the next + // call of fill_window. + + ins_h = window[0]&0xff; + ins_h=(((ins_h)<<hash_shift)^(window[1]&0xff))&hash_mask; + + for(int n=0; n<=length-MIN_MATCH; n++){ + ins_h=(((ins_h)<<hash_shift)^(window[(n)+(MIN_MATCH-1)]&0xff))&hash_mask; + prev[n&w_mask]=head[ins_h]; + head[ins_h]=(short)n; + } + return Z_OK; + } + + int deflate(ZStream strm, int flush){ + int old_flush; + + if(flush>Z_FINISH || flush<0){ + return Z_STREAM_ERROR; + } + + if(strm.next_out == null || + (strm.next_in == null && strm.avail_in != 0) || + (status == FINISH_STATE && flush != Z_FINISH)) { + strm.msg=z_errmsg[Z_NEED_DICT-(Z_STREAM_ERROR)]; + return Z_STREAM_ERROR; + } + if(strm.avail_out == 0){ + strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)]; + return Z_BUF_ERROR; + } + + this.strm = strm; // just in case + old_flush = last_flush; + last_flush = flush; + + // Write the zlib header + if(status == INIT_STATE) { + int header = (Z_DEFLATED+((w_bits-8)<<4))<<8; + int level_flags=((level-1)&0xff)>>1; + + if(level_flags>3) level_flags=3; + header |= (level_flags<<6); + if(strstart!=0) header |= PRESET_DICT; + header+=31-(header % 31); + + status=BUSY_STATE; + putShortMSB(header); + + + // Save the adler32 of the preset dictionary: + if(strstart!=0){ + putShortMSB((int)(strm.adler>>>16)); + putShortMSB((int)(strm.adler&0xffff)); + } + strm.adler=strm._adler.adler32(0, null, 0, 0); + } + + // Flush as much pending output as possible + if(pending != 0) { + strm.flush_pending(); + if(strm.avail_out == 0) { + //System.out.println(" avail_out==0"); + // Since avail_out is 0, deflate will be called again with + // more output space, but possibly with both pending and + // avail_in equal to zero. There won't be anything to do, + // but this is not an error situation so make sure we + // return OK instead of BUF_ERROR at next call of deflate: + last_flush = -1; + return Z_OK; + } + + // Make sure there is something to do and avoid duplicate consecutive + // flushes. For repeated and useless calls with Z_FINISH, we keep + // returning Z_STREAM_END instead of Z_BUFF_ERROR. + } + else if(strm.avail_in==0 && flush <= old_flush && + flush != Z_FINISH) { + strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)]; + return Z_BUF_ERROR; + } + + // User must not provide more input after the first FINISH: + if(status == FINISH_STATE && strm.avail_in != 0) { + strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)]; + return Z_BUF_ERROR; + } + + // Start a new block or continue the current one. + if(strm.avail_in!=0 || lookahead!=0 || + (flush != Z_NO_FLUSH && status != FINISH_STATE)) { + int bstate=-1; + switch(config_table[level].func){ + case STORED: + bstate = deflate_stored(flush); + break; + case FAST: + bstate = deflate_fast(flush); + break; + case SLOW: + bstate = deflate_slow(flush); + break; + default: + } + + if (bstate==FinishStarted || bstate==FinishDone) { + status = FINISH_STATE; + } + if (bstate==NeedMore || bstate==FinishStarted) { + if(strm.avail_out == 0) { + last_flush = -1; // avoid BUF_ERROR next call, see above + } + return Z_OK; + // If flush != Z_NO_FLUSH && avail_out == 0, the next call + // of deflate should use the same flush parameter to make sure + // that the flush is complete. So we don't have to output an + // empty block here, this will be done at next call. This also + // ensures that for a very small output buffer, we emit at most + // one empty block. + } + + if (bstate==BlockDone) { + if(flush == Z_PARTIAL_FLUSH) { + _tr_align(); + } + else { // FULL_FLUSH or SYNC_FLUSH + _tr_stored_block(0, 0, false); + // For a full flush, this empty block will be recognized + // as a special marker by inflate_sync(). + if(flush == Z_FULL_FLUSH) { + //state.head[s.hash_size-1]=0; + for(int i=0; i<hash_size/*-1*/; i++) // forget history + head[i]=0; + } + } + strm.flush_pending(); + if(strm.avail_out == 0) { + last_flush = -1; // avoid BUF_ERROR at next call, see above + return Z_OK; + } + } + } + + if(flush!=Z_FINISH) return Z_OK; + if(noheader!=0) return Z_STREAM_END; + + // Write the zlib trailer (adler32) + putShortMSB((int)(strm.adler>>>16)); + putShortMSB((int)(strm.adler&0xffff)); + strm.flush_pending(); + + // If avail_out is zero, the application will call deflate again + // to flush the rest. + noheader = -1; // write the trailer only once! + return pending != 0 ? Z_OK : Z_STREAM_END; + } +} diff --git a/lib/jzlib/com/jcraft/jzlib/InfBlocks.java b/lib/jzlib/com/jcraft/jzlib/InfBlocks.java new file mode 100644 index 0000000..f6997fc --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/InfBlocks.java @@ -0,0 +1,614 @@ +/* -*-mode:java; c-basic-offset:2; -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +final class InfBlocks{ + static final private int MANY=1440; + + // And'ing with mask[n] masks the lower n bits + static final private int[] inflate_mask = { + 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, + 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, + 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, + 0x00007fff, 0x0000ffff + }; + + // Table for deflate from PKZIP's appnote.txt. + static final int[] border = { // Order of the bit length code lengths + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 + }; + + static final private int Z_OK=0; + static final private int Z_STREAM_END=1; + static final private int Z_NEED_DICT=2; + static final private int Z_ERRNO=-1; + static final private int Z_STREAM_ERROR=-2; + static final private int Z_DATA_ERROR=-3; + static final private int Z_MEM_ERROR=-4; + static final private int Z_BUF_ERROR=-5; + static final private int Z_VERSION_ERROR=-6; + + static final private int TYPE=0; // get type bits (3, including end bit) + static final private int LENS=1; // get lengths for stored + static final private int STORED=2;// processing stored block + static final private int TABLE=3; // get table lengths + static final private int BTREE=4; // get bit lengths tree for a dynamic block + static final private int DTREE=5; // get length, distance trees for a dynamic block + static final private int CODES=6; // processing fixed or dynamic block + static final private int DRY=7; // output remaining window bytes + static final private int DONE=8; // finished last block, done + static final private int BAD=9; // ot a data error--stuck here + + int mode; // current inflate_block mode + + int left; // if STORED, bytes left to copy + + int table; // table lengths (14 bits) + int index; // index into blens (or border) + int[] blens; // bit lengths of codes + int[] bb=new int[1]; // bit length tree depth + int[] tb=new int[1]; // bit length decoding tree + + InfCodes codes=new InfCodes(); // if CODES, current state + + int last; // true if this block is the last block + + // mode independent information + int bitk; // bits in bit buffer + int bitb; // bit buffer + int[] hufts; // single malloc for tree space + byte[] window; // sliding window + int end; // one byte after sliding window + int read; // window read pointer + int write; // window write pointer + Object checkfn; // check function + long check; // check on output + + InfTree inftree=new InfTree(); + + InfBlocks(ZStream z, Object checkfn, int w){ + hufts=new int[MANY*3]; + window=new byte[w]; + end=w; + this.checkfn = checkfn; + mode = TYPE; + reset(z, null); + } + + void reset(ZStream z, long[] c){ + if(c!=null) c[0]=check; + if(mode==BTREE || mode==DTREE){ + } + if(mode==CODES){ + codes.free(z); + } + mode=TYPE; + bitk=0; + bitb=0; + read=write=0; + + if(checkfn != null) + z.adler=check=z._adler.adler32(0L, null, 0, 0); + } + + int proc(ZStream z, int r){ + int t; // temporary storage + int b; // bit buffer + int k; // bits in bit buffer + int p; // input data pointer + int n; // bytes available there + int q; // output window write pointer + int m; // bytes to end of window or read pointer + + // copy input/output information to locals (UPDATE macro restores) + {p=z.next_in_index;n=z.avail_in;b=bitb;k=bitk;} + {q=write;m=(int)(q<read?read-q-1:end-q);} + + // process input based on current state + while(true){ + switch (mode){ + case TYPE: + + while(k<(3)){ + if(n!=0){ + r=Z_OK; + } + else{ + bitb=b; bitk=k; + z.avail_in=n; + z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + }; + n--; + b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + t = (int)(b & 7); + last = t & 1; + + switch (t >>> 1){ + case 0: // stored + {b>>>=(3);k-=(3);} + t = k & 7; // go to byte boundary + + {b>>>=(t);k-=(t);} + mode = LENS; // get length of stored block + break; + case 1: // fixed + { + int[] bl=new int[1]; + int[] bd=new int[1]; + int[][] tl=new int[1][]; + int[][] td=new int[1][]; + + InfTree.inflate_trees_fixed(bl, bd, tl, td, z); + codes.init(bl[0], bd[0], tl[0], 0, td[0], 0, z); + } + + {b>>>=(3);k-=(3);} + + mode = CODES; + break; + case 2: // dynamic + + {b>>>=(3);k-=(3);} + + mode = TABLE; + break; + case 3: // illegal + + {b>>>=(3);k-=(3);} + mode = BAD; + z.msg = "invalid block type"; + r = Z_DATA_ERROR; + + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + } + break; + case LENS: + + while(k<(32)){ + if(n!=0){ + r=Z_OK; + } + else{ + bitb=b; bitk=k; + z.avail_in=n; + z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + }; + n--; + b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + + if ((((~b) >>> 16) & 0xffff) != (b & 0xffff)){ + mode = BAD; + z.msg = "invalid stored block lengths"; + r = Z_DATA_ERROR; + + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + } + left = (b & 0xffff); + b = k = 0; // dump bits + mode = left!=0 ? STORED : (last!=0 ? DRY : TYPE); + break; + case STORED: + if (n == 0){ + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + } + + if(m==0){ + if(q==end&&read!=0){ + q=0; m=(int)(q<read?read-q-1:end-q); + } + if(m==0){ + write=q; + r=inflate_flush(z,r); + q=write;m=(int)(q<read?read-q-1:end-q); + if(q==end&&read!=0){ + q=0; m=(int)(q<read?read-q-1:end-q); + } + if(m==0){ + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + } + } + } + r=Z_OK; + + t = left; + if(t>n) t = n; + if(t>m) t = m; + System.arraycopy(z.next_in, p, window, q, t); + p += t; n -= t; + q += t; m -= t; + if ((left -= t) != 0) + break; + mode = last!=0 ? DRY : TYPE; + break; + case TABLE: + + while(k<(14)){ + if(n!=0){ + r=Z_OK; + } + else{ + bitb=b; bitk=k; + z.avail_in=n; + z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + }; + n--; + b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + + table = t = (b & 0x3fff); + if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) + { + mode = BAD; + z.msg = "too many length or distance symbols"; + r = Z_DATA_ERROR; + + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + } + t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); + if(blens==null || blens.length<t){ + blens=new int[t]; + } + else{ + for(int i=0; i<t; i++){blens[i]=0;} + } + + {b>>>=(14);k-=(14);} + + index = 0; + mode = BTREE; + case BTREE: + while (index < 4 + (table >>> 10)){ + while(k<(3)){ + if(n!=0){ + r=Z_OK; + } + else{ + bitb=b; bitk=k; + z.avail_in=n; + z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + }; + n--; + b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + + blens[border[index++]] = b&7; + + {b>>>=(3);k-=(3);} + } + + while(index < 19){ + blens[border[index++]] = 0; + } + + bb[0] = 7; + t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z); + if (t != Z_OK){ + r = t; + if (r == Z_DATA_ERROR){ + blens=null; + mode = BAD; + } + + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + } + + index = 0; + mode = DTREE; + case DTREE: + while (true){ + t = table; + if(!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))){ + break; + } + + int[] h; + int i, j, c; + + t = bb[0]; + + while(k<(t)){ + if(n!=0){ + r=Z_OK; + } + else{ + bitb=b; bitk=k; + z.avail_in=n; + z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + }; + n--; + b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + + if(tb[0]==-1){ + //System.err.println("null..."); + } + + t=hufts[(tb[0]+(b&inflate_mask[t]))*3+1]; + c=hufts[(tb[0]+(b&inflate_mask[t]))*3+2]; + + if (c < 16){ + b>>>=(t);k-=(t); + blens[index++] = c; + } + else { // c == 16..18 + i = c == 18 ? 7 : c - 14; + j = c == 18 ? 11 : 3; + + while(k<(t+i)){ + if(n!=0){ + r=Z_OK; + } + else{ + bitb=b; bitk=k; + z.avail_in=n; + z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + }; + n--; + b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + + b>>>=(t);k-=(t); + + j += (b & inflate_mask[i]); + + b>>>=(i);k-=(i); + + i = index; + t = table; + if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || + (c == 16 && i < 1)){ + blens=null; + mode = BAD; + z.msg = "invalid bit length repeat"; + r = Z_DATA_ERROR; + + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + } + + c = c == 16 ? blens[i-1] : 0; + do{ + blens[i++] = c; + } + while (--j!=0); + index = i; + } + } + + tb[0]=-1; + { + int[] bl=new int[1]; + int[] bd=new int[1]; + int[] tl=new int[1]; + int[] td=new int[1]; + bl[0] = 9; // must be <= 9 for lookahead assumptions + bd[0] = 6; // must be <= 9 for lookahead assumptions + + t = table; + t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), + 1 + ((t >> 5) & 0x1f), + blens, bl, bd, tl, td, hufts, z); + + if (t != Z_OK){ + if (t == Z_DATA_ERROR){ + blens=null; + mode = BAD; + } + r = t; + + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z,r); + } + codes.init(bl[0], bd[0], hufts, tl[0], hufts, td[0], z); + } + mode = CODES; + case CODES: + bitb=b; bitk=k; + z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + + if ((r = codes.proc(this, z, r)) != Z_STREAM_END){ + return inflate_flush(z, r); + } + r = Z_OK; + codes.free(z); + + p=z.next_in_index; n=z.avail_in;b=bitb;k=bitk; + q=write;m=(int)(q<read?read-q-1:end-q); + + if (last==0){ + mode = TYPE; + break; + } + mode = DRY; + case DRY: + write=q; + r=inflate_flush(z, r); + q=write; m=(int)(q<read?read-q-1:end-q); + if (read != write){ + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z, r); + } + mode = DONE; + case DONE: + r = Z_STREAM_END; + + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z, r); + case BAD: + r = Z_DATA_ERROR; + + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z, r); + + default: + r = Z_STREAM_ERROR; + + bitb=b; bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + write=q; + return inflate_flush(z, r); + } + } + } + + void free(ZStream z){ + reset(z, null); + window=null; + hufts=null; + //ZFREE(z, s); + } + + void set_dictionary(byte[] d, int start, int n){ + System.arraycopy(d, start, window, 0, n); + read = write = n; + } + + // Returns true if inflate is currently at the end of a block generated + // by Z_SYNC_FLUSH or Z_FULL_FLUSH. + int sync_point(){ + return mode == LENS ? 1 : 0; + } + + // copy as much as possible from the sliding window to the output area + int inflate_flush(ZStream z, int r){ + int n; + int p; + int q; + + // local copies of source and destination pointers + p = z.next_out_index; + q = read; + + // compute number of bytes to copy as far as end of window + n = (int)((q <= write ? write : end) - q); + if (n > z.avail_out) n = z.avail_out; + if (n!=0 && r == Z_BUF_ERROR) r = Z_OK; + + // update counters + z.avail_out -= n; + z.total_out += n; + + // update check information + if(checkfn != null) + z.adler=check=z._adler.adler32(check, window, q, n); + + // copy as far as end of window + System.arraycopy(window, q, z.next_out, p, n); + p += n; + q += n; + + // see if more to copy at beginning of window + if (q == end){ + // wrap pointers + q = 0; + if (write == end) + write = 0; + + // compute bytes to copy + n = write - q; + if (n > z.avail_out) n = z.avail_out; + if (n!=0 && r == Z_BUF_ERROR) r = Z_OK; + + // update counters + z.avail_out -= n; + z.total_out += n; + + // update check information + if(checkfn != null) + z.adler=check=z._adler.adler32(check, window, q, n); + + // copy + System.arraycopy(window, q, z.next_out, p, n); + p += n; + q += n; + } + + // update pointers + z.next_out_index = p; + read = q; + + // done + return r; + } +} diff --git a/lib/jzlib/com/jcraft/jzlib/InfCodes.java b/lib/jzlib/com/jcraft/jzlib/InfCodes.java new file mode 100644 index 0000000..c768fb1 --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/InfCodes.java @@ -0,0 +1,605 @@ +/* -*-mode:java; c-basic-offset:2; -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +final class InfCodes{ + + static final private int[] inflate_mask = { + 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, + 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, + 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, + 0x00007fff, 0x0000ffff + }; + + static final private int Z_OK=0; + static final private int Z_STREAM_END=1; + static final private int Z_NEED_DICT=2; + static final private int Z_ERRNO=-1; + static final private int Z_STREAM_ERROR=-2; + static final private int Z_DATA_ERROR=-3; + static final private int Z_MEM_ERROR=-4; + static final private int Z_BUF_ERROR=-5; + static final private int Z_VERSION_ERROR=-6; + + // waiting for "i:"=input, + // "o:"=output, + // "x:"=nothing + static final private int START=0; // x: set up for LEN + static final private int LEN=1; // i: get length/literal/eob next + static final private int LENEXT=2; // i: getting length extra (have base) + static final private int DIST=3; // i: get distance next + static final private int DISTEXT=4;// i: getting distance extra + static final private int COPY=5; // o: copying bytes in window, waiting for space + static final private int LIT=6; // o: got literal, waiting for output space + static final private int WASH=7; // o: got eob, possibly still output waiting + static final private int END=8; // x: got eob and all data flushed + static final private int BADCODE=9;// x: got error + + int mode; // current inflate_codes mode + + // mode dependent information + int len; + + int[] tree; // pointer into tree + int tree_index=0; + int need; // bits needed + + int lit; + + // if EXT or COPY, where and how much + int get; // bits to get for extra + int dist; // distance back to copy from + + byte lbits; // ltree bits decoded per branch + byte dbits; // dtree bits decoder per branch + int[] ltree; // literal/length/eob tree + int ltree_index; // literal/length/eob tree + int[] dtree; // distance tree + int dtree_index; // distance tree + + InfCodes(){ + } + void init(int bl, int bd, + int[] tl, int tl_index, + int[] td, int td_index, ZStream z){ + mode=START; + lbits=(byte)bl; + dbits=(byte)bd; + ltree=tl; + ltree_index=tl_index; + dtree = td; + dtree_index=td_index; + tree=null; + } + + int proc(InfBlocks s, ZStream z, int r){ + int j; // temporary storage + int[] t; // temporary pointer + int tindex; // temporary pointer + int e; // extra bits or operation + int b=0; // bit buffer + int k=0; // bits in bit buffer + int p=0; // input data pointer + int n; // bytes available there + int q; // output window write pointer + int m; // bytes to end of window or read pointer + int f; // pointer to copy strings from + + // copy input/output information to locals (UPDATE macro restores) + p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk; + q=s.write;m=q<s.read?s.read-q-1:s.end-q; + + // process input and output based on current state + while (true){ + switch (mode){ + // waiting for "i:"=input, "o:"=output, "x:"=nothing + case START: // x: set up for LEN + if (m >= 258 && n >= 10){ + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + r = inflate_fast(lbits, dbits, + ltree, ltree_index, + dtree, dtree_index, + s, z); + + p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk; + q=s.write;m=q<s.read?s.read-q-1:s.end-q; + + if (r != Z_OK){ + mode = r == Z_STREAM_END ? WASH : BADCODE; + break; + } + } + need = lbits; + tree = ltree; + tree_index=ltree_index; + + mode = LEN; + case LEN: // i: get length/literal/eob next + j = need; + + while(k<(j)){ + if(n!=0)r=Z_OK; + else{ + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + } + n--; + b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + + tindex=(tree_index+(b&inflate_mask[j]))*3; + + b>>>=(tree[tindex+1]); + k-=(tree[tindex+1]); + + e=tree[tindex]; + + if(e == 0){ // literal + lit = tree[tindex+2]; + mode = LIT; + break; + } + if((e & 16)!=0 ){ // length + get = e & 15; + len = tree[tindex+2]; + mode = LENEXT; + break; + } + if ((e & 64) == 0){ // next table + need = e; + tree_index = tindex/3+tree[tindex+2]; + break; + } + if ((e & 32)!=0){ // end of block + mode = WASH; + break; + } + mode = BADCODE; // invalid code + z.msg = "invalid literal/length code"; + r = Z_DATA_ERROR; + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + + case LENEXT: // i: getting length extra (have base) + j = get; + + while(k<(j)){ + if(n!=0)r=Z_OK; + else{ + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + } + n--; b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + + len += (b & inflate_mask[j]); + + b>>=j; + k-=j; + + need = dbits; + tree = dtree; + tree_index=dtree_index; + mode = DIST; + case DIST: // i: get distance next + j = need; + + while(k<(j)){ + if(n!=0)r=Z_OK; + else{ + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + } + n--; b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + + tindex=(tree_index+(b & inflate_mask[j]))*3; + + b>>=tree[tindex+1]; + k-=tree[tindex+1]; + + e = (tree[tindex]); + if((e & 16)!=0){ // distance + get = e & 15; + dist = tree[tindex+2]; + mode = DISTEXT; + break; + } + if ((e & 64) == 0){ // next table + need = e; + tree_index = tindex/3 + tree[tindex+2]; + break; + } + mode = BADCODE; // invalid code + z.msg = "invalid distance code"; + r = Z_DATA_ERROR; + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + + case DISTEXT: // i: getting distance extra + j = get; + + while(k<(j)){ + if(n!=0)r=Z_OK; + else{ + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + } + n--; b|=(z.next_in[p++]&0xff)<<k; + k+=8; + } + + dist += (b & inflate_mask[j]); + + b>>=j; + k-=j; + + mode = COPY; + case COPY: // o: copying bytes in window, waiting for space + f = q - dist; + while(f < 0){ // modulo window size-"while" instead + f += s.end; // of "if" handles invalid distances + } + while (len!=0){ + + if(m==0){ + if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;} + if(m==0){ + s.write=q; r=s.inflate_flush(z,r); + q=s.write;m=q<s.read?s.read-q-1:s.end-q; + + if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;} + + if(m==0){ + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + } + } + } + + s.window[q++]=s.window[f++]; m--; + + if (f == s.end) + f = 0; + len--; + } + mode = START; + break; + case LIT: // o: got literal, waiting for output space + if(m==0){ + if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;} + if(m==0){ + s.write=q; r=s.inflate_flush(z,r); + q=s.write;m=q<s.read?s.read-q-1:s.end-q; + + if(q==s.end&&s.read!=0){q=0;m=q<s.read?s.read-q-1:s.end-q;} + if(m==0){ + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + } + } + } + r=Z_OK; + + s.window[q++]=(byte)lit; m--; + + mode = START; + break; + case WASH: // o: got eob, possibly more output + if (k > 7){ // return unused byte, if any + k -= 8; + n++; + p--; // can always return one + } + + s.write=q; r=s.inflate_flush(z,r); + q=s.write;m=q<s.read?s.read-q-1:s.end-q; + + if (s.read != s.write){ + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + } + mode = END; + case END: + r = Z_STREAM_END; + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + + case BADCODE: // x: got error + + r = Z_DATA_ERROR; + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + + default: + r = Z_STREAM_ERROR; + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + return s.inflate_flush(z,r); + } + } + } + + void free(ZStream z){ + // ZFREE(z, c); + } + + // Called with number of bytes left to write in window at least 258 + // (the maximum string length) and number of input bytes available + // at least ten. The ten bytes are six bytes for the longest length/ + // distance pair plus four bytes for overloading the bit buffer. + + int inflate_fast(int bl, int bd, + int[] tl, int tl_index, + int[] td, int td_index, + InfBlocks s, ZStream z){ + int t; // temporary pointer + int[] tp; // temporary pointer + int tp_index; // temporary pointer + int e; // extra bits or operation + int b; // bit buffer + int k; // bits in bit buffer + int p; // input data pointer + int n; // bytes available there + int q; // output window write pointer + int m; // bytes to end of window or read pointer + int ml; // mask for literal/length tree + int md; // mask for distance tree + int c; // bytes to copy + int d; // distance back to copy from + int r; // copy source pointer + + int tp_index_t_3; // (tp_index+t)*3 + + // load input, output, bit values + p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk; + q=s.write;m=q<s.read?s.read-q-1:s.end-q; + + // initialize masks + ml = inflate_mask[bl]; + md = inflate_mask[bd]; + + // do until not enough input or output space for fast loop + do { // assume called with m >= 258 && n >= 10 + // get literal/length code + while(k<(20)){ // max bits for literal/length code + n--; + b|=(z.next_in[p++]&0xff)<<k;k+=8; + } + + t= b&ml; + tp=tl; + tp_index=tl_index; + tp_index_t_3=(tp_index+t)*3; + if ((e = tp[tp_index_t_3]) == 0){ + b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]); + + s.window[q++] = (byte)tp[tp_index_t_3+2]; + m--; + continue; + } + do { + + b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]); + + if((e&16)!=0){ + e &= 15; + c = tp[tp_index_t_3+2] + ((int)b & inflate_mask[e]); + + b>>=e; k-=e; + + // decode distance base of block to copy + while(k<(15)){ // max bits for distance code + n--; + b|=(z.next_in[p++]&0xff)<<k;k+=8; + } + + t= b&md; + tp=td; + tp_index=td_index; + tp_index_t_3=(tp_index+t)*3; + e = tp[tp_index_t_3]; + + do { + + b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]); + + if((e&16)!=0){ + // get extra bits to add to distance base + e &= 15; + while(k<(e)){ // get extra bits (up to 13) + n--; + b|=(z.next_in[p++]&0xff)<<k;k+=8; + } + + d = tp[tp_index_t_3+2] + (b&inflate_mask[e]); + + b>>=(e); k-=(e); + + // do the copy + m -= c; + if (q >= d){ // offset before dest + // just copy + r=q-d; + if(q-r>0 && 2>(q-r)){ + s.window[q++]=s.window[r++]; // minimum count is three, + s.window[q++]=s.window[r++]; // so unroll loop a little + c-=2; + } + else{ + System.arraycopy(s.window, r, s.window, q, 2); + q+=2; r+=2; c-=2; + } + } + else{ // else offset after destination + r=q-d; + do{ + r+=s.end; // force pointer in window + }while(r<0); // covers invalid distances + e=s.end-r; + if(c>e){ // if source crosses, + c-=e; // wrapped copy + if(q-r>0 && e>(q-r)){ + do{s.window[q++] = s.window[r++];} + while(--e!=0); + } + else{ + System.arraycopy(s.window, r, s.window, q, e); + q+=e; r+=e; e=0; + } + r = 0; // copy rest from start of window + } + + } + + // copy all or what's left + if(q-r>0 && c>(q-r)){ + do{s.window[q++] = s.window[r++];} + while(--c!=0); + } + else{ + System.arraycopy(s.window, r, s.window, q, c); + q+=c; r+=c; c=0; + } + break; + } + else if((e&64)==0){ + t+=tp[tp_index_t_3+2]; + t+=(b&inflate_mask[e]); + tp_index_t_3=(tp_index+t)*3; + e=tp[tp_index_t_3]; + } + else{ + z.msg = "invalid distance code"; + + c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3; + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + + return Z_DATA_ERROR; + } + } + while(true); + break; + } + + if((e&64)==0){ + t+=tp[tp_index_t_3+2]; + t+=(b&inflate_mask[e]); + tp_index_t_3=(tp_index+t)*3; + if((e=tp[tp_index_t_3])==0){ + + b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]); + + s.window[q++]=(byte)tp[tp_index_t_3+2]; + m--; + break; + } + } + else if((e&32)!=0){ + + c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3; + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + + return Z_STREAM_END; + } + else{ + z.msg="invalid literal/length code"; + + c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3; + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + + return Z_DATA_ERROR; + } + } + while(true); + } + while(m>=258 && n>= 10); + + // not enough input or output--restore pointers and return + c=z.avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3; + + s.bitb=b;s.bitk=k; + z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p; + s.write=q; + + return Z_OK; + } +} diff --git a/lib/jzlib/com/jcraft/jzlib/InfTree.java b/lib/jzlib/com/jcraft/jzlib/InfTree.java new file mode 100644 index 0000000..cbca436 --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/InfTree.java @@ -0,0 +1,520 @@ +/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +final class InfTree{ + + static final private int MANY=1440; + + static final private int Z_OK=0; + static final private int Z_STREAM_END=1; + static final private int Z_NEED_DICT=2; + static final private int Z_ERRNO=-1; + static final private int Z_STREAM_ERROR=-2; + static final private int Z_DATA_ERROR=-3; + static final private int Z_MEM_ERROR=-4; + static final private int Z_BUF_ERROR=-5; + static final private int Z_VERSION_ERROR=-6; + + static final int fixed_bl = 9; + static final int fixed_bd = 5; + + static final int[] fixed_tl = { + 96,7,256, 0,8,80, 0,8,16, 84,8,115, + 82,7,31, 0,8,112, 0,8,48, 0,9,192, + 80,7,10, 0,8,96, 0,8,32, 0,9,160, + 0,8,0, 0,8,128, 0,8,64, 0,9,224, + 80,7,6, 0,8,88, 0,8,24, 0,9,144, + 83,7,59, 0,8,120, 0,8,56, 0,9,208, + 81,7,17, 0,8,104, 0,8,40, 0,9,176, + 0,8,8, 0,8,136, 0,8,72, 0,9,240, + 80,7,4, 0,8,84, 0,8,20, 85,8,227, + 83,7,43, 0,8,116, 0,8,52, 0,9,200, + 81,7,13, 0,8,100, 0,8,36, 0,9,168, + 0,8,4, 0,8,132, 0,8,68, 0,9,232, + 80,7,8, 0,8,92, 0,8,28, 0,9,152, + 84,7,83, 0,8,124, 0,8,60, 0,9,216, + 82,7,23, 0,8,108, 0,8,44, 0,9,184, + 0,8,12, 0,8,140, 0,8,76, 0,9,248, + 80,7,3, 0,8,82, 0,8,18, 85,8,163, + 83,7,35, 0,8,114, 0,8,50, 0,9,196, + 81,7,11, 0,8,98, 0,8,34, 0,9,164, + 0,8,2, 0,8,130, 0,8,66, 0,9,228, + 80,7,7, 0,8,90, 0,8,26, 0,9,148, + 84,7,67, 0,8,122, 0,8,58, 0,9,212, + 82,7,19, 0,8,106, 0,8,42, 0,9,180, + 0,8,10, 0,8,138, 0,8,74, 0,9,244, + 80,7,5, 0,8,86, 0,8,22, 192,8,0, + 83,7,51, 0,8,118, 0,8,54, 0,9,204, + 81,7,15, 0,8,102, 0,8,38, 0,9,172, + 0,8,6, 0,8,134, 0,8,70, 0,9,236, + 80,7,9, 0,8,94, 0,8,30, 0,9,156, + 84,7,99, 0,8,126, 0,8,62, 0,9,220, + 82,7,27, 0,8,110, 0,8,46, 0,9,188, + 0,8,14, 0,8,142, 0,8,78, 0,9,252, + 96,7,256, 0,8,81, 0,8,17, 85,8,131, + 82,7,31, 0,8,113, 0,8,49, 0,9,194, + 80,7,10, 0,8,97, 0,8,33, 0,9,162, + 0,8,1, 0,8,129, 0,8,65, 0,9,226, + 80,7,6, 0,8,89, 0,8,25, 0,9,146, + 83,7,59, 0,8,121, 0,8,57, 0,9,210, + 81,7,17, 0,8,105, 0,8,41, 0,9,178, + 0,8,9, 0,8,137, 0,8,73, 0,9,242, + 80,7,4, 0,8,85, 0,8,21, 80,8,258, + 83,7,43, 0,8,117, 0,8,53, 0,9,202, + 81,7,13, 0,8,101, 0,8,37, 0,9,170, + 0,8,5, 0,8,133, 0,8,69, 0,9,234, + 80,7,8, 0,8,93, 0,8,29, 0,9,154, + 84,7,83, 0,8,125, 0,8,61, 0,9,218, + 82,7,23, 0,8,109, 0,8,45, 0,9,186, + 0,8,13, 0,8,141, 0,8,77, 0,9,250, + 80,7,3, 0,8,83, 0,8,19, 85,8,195, + 83,7,35, 0,8,115, 0,8,51, 0,9,198, + 81,7,11, 0,8,99, 0,8,35, 0,9,166, + 0,8,3, 0,8,131, 0,8,67, 0,9,230, + 80,7,7, 0,8,91, 0,8,27, 0,9,150, + 84,7,67, 0,8,123, 0,8,59, 0,9,214, + 82,7,19, 0,8,107, 0,8,43, 0,9,182, + 0,8,11, 0,8,139, 0,8,75, 0,9,246, + 80,7,5, 0,8,87, 0,8,23, 192,8,0, + 83,7,51, 0,8,119, 0,8,55, 0,9,206, + 81,7,15, 0,8,103, 0,8,39, 0,9,174, + 0,8,7, 0,8,135, 0,8,71, 0,9,238, + 80,7,9, 0,8,95, 0,8,31, 0,9,158, + 84,7,99, 0,8,127, 0,8,63, 0,9,222, + 82,7,27, 0,8,111, 0,8,47, 0,9,190, + 0,8,15, 0,8,143, 0,8,79, 0,9,254, + 96,7,256, 0,8,80, 0,8,16, 84,8,115, + 82,7,31, 0,8,112, 0,8,48, 0,9,193, + + 80,7,10, 0,8,96, 0,8,32, 0,9,161, + 0,8,0, 0,8,128, 0,8,64, 0,9,225, + 80,7,6, 0,8,88, 0,8,24, 0,9,145, + 83,7,59, 0,8,120, 0,8,56, 0,9,209, + 81,7,17, 0,8,104, 0,8,40, 0,9,177, + 0,8,8, 0,8,136, 0,8,72, 0,9,241, + 80,7,4, 0,8,84, 0,8,20, 85,8,227, + 83,7,43, 0,8,116, 0,8,52, 0,9,201, + 81,7,13, 0,8,100, 0,8,36, 0,9,169, + 0,8,4, 0,8,132, 0,8,68, 0,9,233, + 80,7,8, 0,8,92, 0,8,28, 0,9,153, + 84,7,83, 0,8,124, 0,8,60, 0,9,217, + 82,7,23, 0,8,108, 0,8,44, 0,9,185, + 0,8,12, 0,8,140, 0,8,76, 0,9,249, + 80,7,3, 0,8,82, 0,8,18, 85,8,163, + 83,7,35, 0,8,114, 0,8,50, 0,9,197, + 81,7,11, 0,8,98, 0,8,34, 0,9,165, + 0,8,2, 0,8,130, 0,8,66, 0,9,229, + 80,7,7, 0,8,90, 0,8,26, 0,9,149, + 84,7,67, 0,8,122, 0,8,58, 0,9,213, + 82,7,19, 0,8,106, 0,8,42, 0,9,181, + 0,8,10, 0,8,138, 0,8,74, 0,9,245, + 80,7,5, 0,8,86, 0,8,22, 192,8,0, + 83,7,51, 0,8,118, 0,8,54, 0,9,205, + 81,7,15, 0,8,102, 0,8,38, 0,9,173, + 0,8,6, 0,8,134, 0,8,70, 0,9,237, + 80,7,9, 0,8,94, 0,8,30, 0,9,157, + 84,7,99, 0,8,126, 0,8,62, 0,9,221, + 82,7,27, 0,8,110, 0,8,46, 0,9,189, + 0,8,14, 0,8,142, 0,8,78, 0,9,253, + 96,7,256, 0,8,81, 0,8,17, 85,8,131, + 82,7,31, 0,8,113, 0,8,49, 0,9,195, + 80,7,10, 0,8,97, 0,8,33, 0,9,163, + 0,8,1, 0,8,129, 0,8,65, 0,9,227, + 80,7,6, 0,8,89, 0,8,25, 0,9,147, + 83,7,59, 0,8,121, 0,8,57, 0,9,211, + 81,7,17, 0,8,105, 0,8,41, 0,9,179, + 0,8,9, 0,8,137, 0,8,73, 0,9,243, + 80,7,4, 0,8,85, 0,8,21, 80,8,258, + 83,7,43, 0,8,117, 0,8,53, 0,9,203, + 81,7,13, 0,8,101, 0,8,37, 0,9,171, + 0,8,5, 0,8,133, 0,8,69, 0,9,235, + 80,7,8, 0,8,93, 0,8,29, 0,9,155, + 84,7,83, 0,8,125, 0,8,61, 0,9,219, + 82,7,23, 0,8,109, 0,8,45, 0,9,187, + 0,8,13, 0,8,141, 0,8,77, 0,9,251, + 80,7,3, 0,8,83, 0,8,19, 85,8,195, + 83,7,35, 0,8,115, 0,8,51, 0,9,199, + 81,7,11, 0,8,99, 0,8,35, 0,9,167, + 0,8,3, 0,8,131, 0,8,67, 0,9,231, + 80,7,7, 0,8,91, 0,8,27, 0,9,151, + 84,7,67, 0,8,123, 0,8,59, 0,9,215, + 82,7,19, 0,8,107, 0,8,43, 0,9,183, + 0,8,11, 0,8,139, 0,8,75, 0,9,247, + 80,7,5, 0,8,87, 0,8,23, 192,8,0, + 83,7,51, 0,8,119, 0,8,55, 0,9,207, + 81,7,15, 0,8,103, 0,8,39, 0,9,175, + 0,8,7, 0,8,135, 0,8,71, 0,9,239, + 80,7,9, 0,8,95, 0,8,31, 0,9,159, + 84,7,99, 0,8,127, 0,8,63, 0,9,223, + 82,7,27, 0,8,111, 0,8,47, 0,9,191, + 0,8,15, 0,8,143, 0,8,79, 0,9,255 + }; + static final int[] fixed_td = { + 80,5,1, 87,5,257, 83,5,17, 91,5,4097, + 81,5,5, 89,5,1025, 85,5,65, 93,5,16385, + 80,5,3, 88,5,513, 84,5,33, 92,5,8193, + 82,5,9, 90,5,2049, 86,5,129, 192,5,24577, + 80,5,2, 87,5,385, 83,5,25, 91,5,6145, + 81,5,7, 89,5,1537, 85,5,97, 93,5,24577, + 80,5,4, 88,5,769, 84,5,49, 92,5,12289, + 82,5,13, 90,5,3073, 86,5,193, 192,5,24577 + }; + + // Tables for deflate from PKZIP's appnote.txt. + static final int[] cplens = { // Copy lengths for literal codes 257..285 + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 + }; + + // see note #13 above about 258 + static final int[] cplext = { // Extra bits for literal codes 257..285 + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid + }; + + static final int[] cpdist = { // Copy offsets for distance codes 0..29 + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577 + }; + + static final int[] cpdext = { // Extra bits for distance codes + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, + 12, 12, 13, 13}; + + // If BMAX needs to be larger than 16, then h and x[] should be uLong. + static final int BMAX=15; // maximum bit length of any code + + int[] hn = null; // hufts used in space + int[] v = null; // work area for huft_build + int[] c = null; // bit length count table + int[] r = null; // table entry for structure assignment + int[] u = null; // table stack + int[] x = null; // bit offsets, then code stack + + private int huft_build(int[] b, // code lengths in bits (all assumed <= BMAX) + int bindex, + int n, // number of codes (assumed <= 288) + int s, // number of simple-valued codes (0..s-1) + int[] d, // list of base values for non-simple codes + int[] e, // list of extra bits for non-simple codes + int[] t, // result: starting table + int[] m, // maximum lookup bits, returns actual + int[] hp,// space for trees + int[] hn,// hufts used in space + int[] v // working area: values in order of bit length + ){ + // Given a list of code lengths and a maximum table size, make a set of + // tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR + // if the given code set is incomplete (the tables are still built in this + // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of + // lengths), or Z_MEM_ERROR if not enough memory. + + int a; // counter for codes of length k + int f; // i repeats in table every f entries + int g; // maximum code length + int h; // table level + int i; // counter, current code + int j; // counter + int k; // number of bits in current code + int l; // bits per table (returned in m) + int mask; // (1 << w) - 1, to avoid cc -O bug on HP + int p; // pointer into c[], b[], or v[] + int q; // points to current table + int w; // bits before this table == (l * h) + int xp; // pointer into x + int y; // number of dummy codes added + int z; // number of entries in current table + + // Generate counts for each bit length + + p = 0; i = n; + do { + c[b[bindex+p]]++; p++; i--; // assume all entries <= BMAX + }while(i!=0); + + if(c[0] == n){ // null input--all zero length codes + t[0] = -1; + m[0] = 0; + return Z_OK; + } + + // Find minimum and maximum length, bound *m by those + l = m[0]; + for (j = 1; j <= BMAX; j++) + if(c[j]!=0) break; + k = j; // minimum code length + if(l < j){ + l = j; + } + for (i = BMAX; i!=0; i--){ + if(c[i]!=0) break; + } + g = i; // maximum code length + if(l > i){ + l = i; + } + m[0] = l; + + // Adjust last length count to fill out codes, if needed + for (y = 1 << j; j < i; j++, y <<= 1){ + if ((y -= c[j]) < 0){ + return Z_DATA_ERROR; + } + } + if ((y -= c[i]) < 0){ + return Z_DATA_ERROR; + } + c[i] += y; + + // Generate starting offsets into the value table for each length + x[1] = j = 0; + p = 1; xp = 2; + while (--i!=0) { // note that i == g from above + x[xp] = (j += c[p]); + xp++; + p++; + } + + // Make a table of values in order of bit lengths + i = 0; p = 0; + do { + if ((j = b[bindex+p]) != 0){ + v[x[j]++] = i; + } + p++; + } + while (++i < n); + n = x[g]; // set n to length of v + + // Generate the Huffman codes and for each, make the table entries + x[0] = i = 0; // first Huffman code is zero + p = 0; // grab values in bit order + h = -1; // no tables yet--level -1 + w = -l; // bits decoded == (l * h) + u[0] = 0; // just to keep compilers happy + q = 0; // ditto + z = 0; // ditto + + // go through the bit lengths (k already is bits in shortest code) + for (; k <= g; k++){ + a = c[k]; + while (a--!=0){ + // here i is the Huffman code of length k bits for value *p + // make tables up to required level + while (k > w + l){ + h++; + w += l; // previous table always l bits + // compute minimum size table less than or equal to l bits + z = g - w; + z = (z > l) ? l : z; // table size upper limit + if((f=1<<(j=k-w))>a+1){ // try a k-w bit table + // too few codes for k-w bit table + f -= a + 1; // deduct codes from patterns left + xp = k; + if(j < z){ + while (++j < z){ // try smaller tables up to z bits + if((f <<= 1) <= c[++xp]) + break; // enough codes to use up j bits + f -= c[xp]; // else deduct codes from patterns + } + } + } + z = 1 << j; // table entries for j-bit table + + // allocate new table + if (hn[0] + z > MANY){ // (note: doesn't matter for fixed) + return Z_DATA_ERROR; // overflow of MANY + } + u[h] = q = /*hp+*/ hn[0]; // DEBUG + hn[0] += z; + + // connect to last table, if there is one + if(h!=0){ + x[h]=i; // save pattern for backing up + r[0]=(byte)j; // bits in this table + r[1]=(byte)l; // bits to dump before this table + j=i>>>(w - l); + r[2] = (int)(q - u[h-1] - j); // offset to this table + System.arraycopy(r, 0, hp, (u[h-1]+j)*3, 3); // connect to last table + } + else{ + t[0] = q; // first table is returned result + } + } + + // set up table entry in r + r[1] = (byte)(k - w); + if (p >= n){ + r[0] = 128 + 64; // out of values--invalid code + } + else if (v[p] < s){ + r[0] = (byte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block + r[2] = v[p++]; // simple code is just the value + } + else{ + r[0]=(byte)(e[v[p]-s]+16+64); // non-simple--look up in lists + r[2]=d[v[p++] - s]; + } + + // fill code-like entries with r + f=1<<(k-w); + for (j=i>>>w;j<z;j+=f){ + System.arraycopy(r, 0, hp, (q+j)*3, 3); + } + + // backwards increment the k-bit code i + for (j = 1 << (k - 1); (i & j)!=0; j >>>= 1){ + i ^= j; + } + i ^= j; + + // backup over finished tables + mask = (1 << w) - 1; // needed on HP, cc -O bug + while ((i & mask) != x[h]){ + h--; // don't need to update q + w -= l; + mask = (1 << w) - 1; + } + } + } + // Return Z_BUF_ERROR if we were given an incomplete table + return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; + } + + int inflate_trees_bits(int[] c, // 19 code lengths + int[] bb, // bits tree desired/actual depth + int[] tb, // bits tree result + int[] hp, // space for trees + ZStream z // for messages + ){ + int result; + initWorkArea(19); + hn[0]=0; + result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v); + + if(result == Z_DATA_ERROR){ + z.msg = "oversubscribed dynamic bit lengths tree"; + } + else if(result == Z_BUF_ERROR || bb[0] == 0){ + z.msg = "incomplete dynamic bit lengths tree"; + result = Z_DATA_ERROR; + } + return result; + } + + int inflate_trees_dynamic(int nl, // number of literal/length codes + int nd, // number of distance codes + int[] c, // that many (total) code lengths + int[] bl, // literal desired/actual bit depth + int[] bd, // distance desired/actual bit depth + int[] tl, // literal/length tree result + int[] td, // distance tree result + int[] hp, // space for trees + ZStream z // for messages + ){ + int result; + + // build literal/length tree + initWorkArea(288); + hn[0]=0; + result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v); + if (result != Z_OK || bl[0] == 0){ + if(result == Z_DATA_ERROR){ + z.msg = "oversubscribed literal/length tree"; + } + else if (result != Z_MEM_ERROR){ + z.msg = "incomplete literal/length tree"; + result = Z_DATA_ERROR; + } + return result; + } + + // build distance tree + initWorkArea(288); + result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v); + + if (result != Z_OK || (bd[0] == 0 && nl > 257)){ + if (result == Z_DATA_ERROR){ + z.msg = "oversubscribed distance tree"; + } + else if (result == Z_BUF_ERROR) { + z.msg = "incomplete distance tree"; + result = Z_DATA_ERROR; + } + else if (result != Z_MEM_ERROR){ + z.msg = "empty distance tree with lengths"; + result = Z_DATA_ERROR; + } + return result; + } + + return Z_OK; + } + + static int inflate_trees_fixed(int[] bl, //literal desired/actual bit depth + int[] bd, //distance desired/actual bit depth + int[][] tl,//literal/length tree result + int[][] td,//distance tree result + ZStream z //for memory allocation + ){ + bl[0]=fixed_bl; + bd[0]=fixed_bd; + tl[0]=fixed_tl; + td[0]=fixed_td; + return Z_OK; + } + + private void initWorkArea(int vsize){ + if(hn==null){ + hn=new int[1]; + v=new int[vsize]; + c=new int[BMAX+1]; + r=new int[3]; + u=new int[BMAX]; + x=new int[BMAX+1]; + } + if(v.length<vsize){ v=new int[vsize]; } + for(int i=0; i<vsize; i++){v[i]=0;} + for(int i=0; i<BMAX+1; i++){c[i]=0;} + for(int i=0; i<3; i++){r[i]=0;} +// for(int i=0; i<BMAX; i++){u[i]=0;} + System.arraycopy(c, 0, u, 0, BMAX); +// for(int i=0; i<BMAX+1; i++){x[i]=0;} + System.arraycopy(c, 0, x, 0, BMAX+1); + } +} diff --git a/lib/jzlib/com/jcraft/jzlib/Inflate.java b/lib/jzlib/com/jcraft/jzlib/Inflate.java new file mode 100644 index 0000000..30310f6 --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/Inflate.java @@ -0,0 +1,374 @@ +/* -*-mode:java; c-basic-offset:2; -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +final class Inflate{ + + static final private int MAX_WBITS=15; // 32K LZ77 window + + // preset dictionary flag in zlib header + static final private int PRESET_DICT=0x20; + + static final int Z_NO_FLUSH=0; + static final int Z_PARTIAL_FLUSH=1; + static final int Z_SYNC_FLUSH=2; + static final int Z_FULL_FLUSH=3; + static final int Z_FINISH=4; + + static final private int Z_DEFLATED=8; + + static final private int Z_OK=0; + static final private int Z_STREAM_END=1; + static final private int Z_NEED_DICT=2; + static final private int Z_ERRNO=-1; + static final private int Z_STREAM_ERROR=-2; + static final private int Z_DATA_ERROR=-3; + static final private int Z_MEM_ERROR=-4; + static final private int Z_BUF_ERROR=-5; + static final private int Z_VERSION_ERROR=-6; + + static final private int METHOD=0; // waiting for method byte + static final private int FLAG=1; // waiting for flag byte + static final private int DICT4=2; // four dictionary check bytes to go + static final private int DICT3=3; // three dictionary check bytes to go + static final private int DICT2=4; // two dictionary check bytes to go + static final private int DICT1=5; // one dictionary check byte to go + static final private int DICT0=6; // waiting for inflateSetDictionary + static final private int BLOCKS=7; // decompressing blocks + static final private int CHECK4=8; // four check bytes to go + static final private int CHECK3=9; // three check bytes to go + static final private int CHECK2=10; // two check bytes to go + static final private int CHECK1=11; // one check byte to go + static final private int DONE=12; // finished check, done + static final private int BAD=13; // got an error--stay here + + int mode; // current inflate mode + + // mode dependent information + int method; // if FLAGS, method byte + + // if CHECK, check values to compare + long[] was=new long[1] ; // computed check value + long need; // stream check value + + // if BAD, inflateSync's marker bytes count + int marker; + + // mode independent information + int nowrap; // flag for no wrapper + int wbits; // log2(window size) (8..15, defaults to 15) + + InfBlocks blocks; // current inflate_blocks state + + int inflateReset(ZStream z){ + if(z == null || z.istate == null) return Z_STREAM_ERROR; + + z.total_in = z.total_out = 0; + z.msg = null; + z.istate.mode = z.istate.nowrap!=0 ? BLOCKS : METHOD; + z.istate.blocks.reset(z, null); + return Z_OK; + } + + int inflateEnd(ZStream z){ + if(blocks != null) + blocks.free(z); + blocks=null; + // ZFREE(z, z->state); + return Z_OK; + } + + int inflateInit(ZStream z, int w){ + z.msg = null; + blocks = null; + + // handle undocumented nowrap option (no zlib header or check) + nowrap = 0; + if(w < 0){ + w = - w; + nowrap = 1; + } + + // set window size + if(w<8 ||w>15){ + inflateEnd(z); + return Z_STREAM_ERROR; + } + wbits=w; + + z.istate.blocks=new InfBlocks(z, + z.istate.nowrap!=0 ? null : this, + 1<<w); + + // reset state + inflateReset(z); + return Z_OK; + } + + int inflate(ZStream z, int f){ + int r; + int b; + + if(z == null || z.istate == null || z.next_in == null) + return Z_STREAM_ERROR; + f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK; + r = Z_BUF_ERROR; + while (true){ +//System.out.println("mode: "+z.istate.mode); + switch (z.istate.mode){ + case METHOD: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + if(((z.istate.method = z.next_in[z.next_in_index++])&0xf)!=Z_DEFLATED){ + z.istate.mode = BAD; + z.msg="unknown compression method"; + z.istate.marker = 5; // can't try inflateSync + break; + } + if((z.istate.method>>4)+8>z.istate.wbits){ + z.istate.mode = BAD; + z.msg="invalid window size"; + z.istate.marker = 5; // can't try inflateSync + break; + } + z.istate.mode=FLAG; + case FLAG: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + b = (z.next_in[z.next_in_index++])&0xff; + + if((((z.istate.method << 8)+b) % 31)!=0){ + z.istate.mode = BAD; + z.msg = "incorrect header check"; + z.istate.marker = 5; // can't try inflateSync + break; + } + + if((b&PRESET_DICT)==0){ + z.istate.mode = BLOCKS; + break; + } + z.istate.mode = DICT4; + case DICT4: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L; + z.istate.mode=DICT3; + case DICT3: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L; + z.istate.mode=DICT2; + case DICT2: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L; + z.istate.mode=DICT1; + case DICT1: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + z.istate.need += (z.next_in[z.next_in_index++]&0xffL); + z.adler = z.istate.need; + z.istate.mode = DICT0; + return Z_NEED_DICT; + case DICT0: + z.istate.mode = BAD; + z.msg = "need dictionary"; + z.istate.marker = 0; // can try inflateSync + return Z_STREAM_ERROR; + case BLOCKS: + + r = z.istate.blocks.proc(z, r); + if(r == Z_DATA_ERROR){ + z.istate.mode = BAD; + z.istate.marker = 0; // can try inflateSync + break; + } + if(r == Z_OK){ + r = f; + } + if(r != Z_STREAM_END){ + return r; + } + r = f; + z.istate.blocks.reset(z, z.istate.was); + if(z.istate.nowrap!=0){ + z.istate.mode=DONE; + break; + } + z.istate.mode=CHECK4; + case CHECK4: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L; + z.istate.mode=CHECK3; + case CHECK3: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L; + z.istate.mode = CHECK2; + case CHECK2: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L; + z.istate.mode = CHECK1; + case CHECK1: + + if(z.avail_in==0)return r;r=f; + + z.avail_in--; z.total_in++; + z.istate.need+=(z.next_in[z.next_in_index++]&0xffL); + + if(((int)(z.istate.was[0])) != ((int)(z.istate.need))){ + z.istate.mode = BAD; + z.msg = "incorrect data check"; + z.istate.marker = 5; // can't try inflateSync + break; + } + + z.istate.mode = DONE; + case DONE: + return Z_STREAM_END; + case BAD: + return Z_DATA_ERROR; + default: + return Z_STREAM_ERROR; + } + } + } + + + int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength){ + int index=0; + int length = dictLength; + if(z==null || z.istate == null|| z.istate.mode != DICT0) + return Z_STREAM_ERROR; + + if(z._adler.adler32(1L, dictionary, 0, dictLength)!=z.adler){ + return Z_DATA_ERROR; + } + + z.adler = z._adler.adler32(0, null, 0, 0); + + if(length >= (1<<z.istate.wbits)){ + length = (1<<z.istate.wbits)-1; + index=dictLength - length; + } + z.istate.blocks.set_dictionary(dictionary, index, length); + z.istate.mode = BLOCKS; + return Z_OK; + } + + static private byte[] mark = {(byte)0, (byte)0, (byte)0xff, (byte)0xff}; + + int inflateSync(ZStream z){ + int n; // number of bytes to look at + int p; // pointer to bytes + int m; // number of marker bytes found in a row + long r, w; // temporaries to save total_in and total_out + + // set up + if(z == null || z.istate == null) + return Z_STREAM_ERROR; + if(z.istate.mode != BAD){ + z.istate.mode = BAD; + z.istate.marker = 0; + } + if((n=z.avail_in)==0) + return Z_BUF_ERROR; + p=z.next_in_index; + m=z.istate.marker; + + // search + while (n!=0 && m < 4){ + if(z.next_in[p] == mark[m]){ + m++; + } + else if(z.next_in[p]!=0){ + m = 0; + } + else{ + m = 4 - m; + } + p++; n--; + } + + // restore + z.total_in += p-z.next_in_index; + z.next_in_index = p; + z.avail_in = n; + z.istate.marker = m; + + // return no joy or set up to restart on a new block + if(m != 4){ + return Z_DATA_ERROR; + } + r=z.total_in; w=z.total_out; + inflateReset(z); + z.total_in=r; z.total_out = w; + z.istate.mode = BLOCKS; + return Z_OK; + } + + // Returns true if inflate is currently at the end of a block generated + // by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + // implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH + // but removes the length bytes of the resulting empty stored block. When + // decompressing, PPP checks that at the end of input packet, inflate is + // waiting for these length bytes. + int inflateSyncPoint(ZStream z){ + if(z == null || z.istate == null || z.istate.blocks == null) + return Z_STREAM_ERROR; + return z.istate.blocks.sync_point(); + } +} diff --git a/lib/jzlib/com/jcraft/jzlib/JZlib.java b/lib/jzlib/com/jcraft/jzlib/JZlib.java new file mode 100644 index 0000000..b84d7a1 --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/JZlib.java @@ -0,0 +1,67 @@ +/* -*-mode:java; c-basic-offset:2; -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +final public class JZlib{ + private static final String version="1.0.2"; + public static String version(){return version;} + + // compression levels + static final public int Z_NO_COMPRESSION=0; + static final public int Z_BEST_SPEED=1; + static final public int Z_BEST_COMPRESSION=9; + static final public int Z_DEFAULT_COMPRESSION=(-1); + + // compression strategy + static final public int Z_FILTERED=1; + static final public int Z_HUFFMAN_ONLY=2; + static final public int Z_DEFAULT_STRATEGY=0; + + static final public int Z_NO_FLUSH=0; + static final public int Z_PARTIAL_FLUSH=1; + static final public int Z_SYNC_FLUSH=2; + static final public int Z_FULL_FLUSH=3; + static final public int Z_FINISH=4; + + static final public int Z_OK=0; + static final public int Z_STREAM_END=1; + static final public int Z_NEED_DICT=2; + static final public int Z_ERRNO=-1; + static final public int Z_STREAM_ERROR=-2; + static final public int Z_DATA_ERROR=-3; + static final public int Z_MEM_ERROR=-4; + static final public int Z_BUF_ERROR=-5; + static final public int Z_VERSION_ERROR=-6; +} diff --git a/lib/jzlib/com/jcraft/jzlib/StaticTree.java b/lib/jzlib/com/jcraft/jzlib/StaticTree.java new file mode 100644 index 0000000..0f7f577 --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/StaticTree.java @@ -0,0 +1,149 @@ +/* -*-mode:java; c-basic-offset:2; -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +final class StaticTree{ + static final private int MAX_BITS=15; + + static final private int BL_CODES=19; + static final private int D_CODES=30; + static final private int LITERALS=256; + static final private int LENGTH_CODES=29; + static final private int L_CODES=(LITERALS+1+LENGTH_CODES); + + // Bit length codes must not exceed MAX_BL_BITS bits + static final int MAX_BL_BITS=7; + + static final short[] static_ltree = { + 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, + 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, + 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, + 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, + 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, + 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, + 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, + 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, + 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, + 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, + 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, + 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, + 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, + 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, + 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, + 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, + 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, + 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, + 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, + 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, + 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, + 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, + 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, + 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, + 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, + 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, + 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, + 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, + 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, + 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, + 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, + 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, + 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, + 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, + 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, + 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, + 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, + 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, + 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, + 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, + 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, + 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, + 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, + 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, + 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, + 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, + 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, + 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, + 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, + 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, + 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, + 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, + 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, + 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, + 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, + 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, + 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, + 163, 8, 99, 8, 227, 8 + }; + + static final short[] static_dtree = { + 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, + 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, + 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, + 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, + 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, + 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 + }; + + static StaticTree static_l_desc = + new StaticTree(static_ltree, Tree.extra_lbits, + LITERALS+1, L_CODES, MAX_BITS); + + static StaticTree static_d_desc = + new StaticTree(static_dtree, Tree.extra_dbits, + 0, D_CODES, MAX_BITS); + + static StaticTree static_bl_desc = + new StaticTree(null, Tree.extra_blbits, + 0, BL_CODES, MAX_BL_BITS); + + short[] static_tree; // static tree or null + int[] extra_bits; // extra bits for each code or null + int extra_base; // base index for extra_bits + int elems; // max number of elements in the tree + int max_length; // max bit length for the codes + + StaticTree(short[] static_tree, + int[] extra_bits, + int extra_base, + int elems, + int max_length + ){ + this.static_tree=static_tree; + this.extra_bits=extra_bits; + this.extra_base=extra_base; + this.elems=elems; + this.max_length=max_length; + } +} diff --git a/lib/jzlib/com/jcraft/jzlib/Tree.java b/lib/jzlib/com/jcraft/jzlib/Tree.java new file mode 100644 index 0000000..8103897 --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/Tree.java @@ -0,0 +1,365 @@ +/* -*-mode:java; c-basic-offset:2; -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +final class Tree{ + static final private int MAX_BITS=15; + static final private int BL_CODES=19; + static final private int D_CODES=30; + static final private int LITERALS=256; + static final private int LENGTH_CODES=29; + static final private int L_CODES=(LITERALS+1+LENGTH_CODES); + static final private int HEAP_SIZE=(2*L_CODES+1); + + // Bit length codes must not exceed MAX_BL_BITS bits + static final int MAX_BL_BITS=7; + + // end of block literal code + static final int END_BLOCK=256; + + // repeat previous bit length 3-6 times (2 bits of repeat count) + static final int REP_3_6=16; + + // repeat a zero length 3-10 times (3 bits of repeat count) + static final int REPZ_3_10=17; + + // repeat a zero length 11-138 times (7 bits of repeat count) + static final int REPZ_11_138=18; + + // extra bits for each length code + static final int[] extra_lbits={ + 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0 + }; + + // extra bits for each distance code + static final int[] extra_dbits={ + 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 + }; + + // extra bits for each bit length code + static final int[] extra_blbits={ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7 + }; + + static final byte[] bl_order={ + 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; + + + // The lengths of the bit length codes are sent in order of decreasing + // probability, to avoid transmitting the lengths for unused bit + // length codes. + + static final int Buf_size=8*2; + + // see definition of array dist_code below + static final int DIST_CODE_LEN=512; + + static final byte[] _dist_code = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, + 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, + 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, + 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, + 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 + }; + + static final byte[] _length_code={ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, + 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, + 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, + 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, + 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 + }; + + static final int[] base_length = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, + 64, 80, 96, 112, 128, 160, 192, 224, 0 + }; + + static final int[] base_dist = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 + }; + + // Mapping from a distance to a distance code. dist is the distance - 1 and + // must not have side effects. _dist_code[256] and _dist_code[257] are never + // used. + static int d_code(int dist){ + return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]); + } + + short[] dyn_tree; // the dynamic tree + int max_code; // largest code with non zero frequency + StaticTree stat_desc; // the corresponding static tree + + // Compute the optimal bit lengths for a tree and update the total bit length + // for the current block. + // IN assertion: the fields freq and dad are set, heap[heap_max] and + // above are the tree nodes sorted by increasing frequency. + // OUT assertions: the field len is set to the optimal bit length, the + // array bl_count contains the frequencies for each bit length. + // The length opt_len is updated; static_len is also updated if stree is + // not null. + void gen_bitlen(Deflate s){ + short[] tree = dyn_tree; + short[] stree = stat_desc.static_tree; + int[] extra = stat_desc.extra_bits; + int base = stat_desc.extra_base; + int max_length = stat_desc.max_length; + int h; // heap index + int n, m; // iterate over the tree elements + int bits; // bit length + int xbits; // extra bits + short f; // frequency + int overflow = 0; // number of elements with bit length too large + + for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0; + + // In a first pass, compute the optimal bit lengths (which may + // overflow in the case of the bit length tree). + tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap + + for(h=s.heap_max+1; h<HEAP_SIZE; h++){ + n = s.heap[h]; + bits = tree[tree[n*2+1]*2+1] + 1; + if (bits > max_length){ bits = max_length; overflow++; } + tree[n*2+1] = (short)bits; + // We overwrite tree[n*2+1] which is no longer needed + + if (n > max_code) continue; // not a leaf node + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n*2]; + s.opt_len += f * (bits + xbits); + if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits); + } + if (overflow == 0) return; + + // This happens for example on obj2 and pic of the Calgary corpus + // Find the first bit length which could increase: + do { + bits = max_length-1; + while(s.bl_count[bits]==0) bits--; + s.bl_count[bits]--; // move one leaf down the tree + s.bl_count[bits+1]+=2; // move one overflow item as its brother + s.bl_count[max_length]--; + // The brother of the overflow item also moves one step up, + // but this does not affect bl_count[max_length] + overflow -= 2; + } + while (overflow > 0); + + for (bits = max_length; bits != 0; bits--) { + n = s.bl_count[bits]; + while (n != 0) { + m = s.heap[--h]; + if (m > max_code) continue; + if (tree[m*2+1] != bits) { + s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2]; + tree[m*2+1] = (short)bits; + } + n--; + } + } + } + + // Construct one Huffman tree and assigns the code bit strings and lengths. + // Update the total bit length for the current block. + // IN assertion: the field freq is set for all tree elements. + // OUT assertions: the fields len and code are set to the optimal bit length + // and corresponding code. The length opt_len is updated; static_len is + // also updated if stree is not null. The field max_code is set. + void build_tree(Deflate s){ + short[] tree=dyn_tree; + short[] stree=stat_desc.static_tree; + int elems=stat_desc.elems; + int n, m; // iterate over heap elements + int max_code=-1; // largest code with non zero frequency + int node; // new node being created + + // Construct the initial heap, with least frequent element in + // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + // heap[0] is not used. + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for(n=0; n<elems; n++) { + if(tree[n*2] != 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + } + else{ + tree[n*2+1] = 0; + } + } + + // The pkzip format requires that at least one distance code exists, + // and that at least one bit should be sent even if there is only one + // possible code. So to avoid special checks later on we force at least + // two codes of non zero frequency. + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node*2] = 1; + s.depth[node] = 0; + s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1]; + // node is 0 or 1 so it does not have extra bits + } + this.max_code = max_code; + + // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + // establish sub-heaps of increasing lengths: + + for(n=s.heap_len/2;n>=1; n--) + s.pqdownheap(tree, n); + + // Construct the Huffman tree by repeatedly combining the least two + // frequent nodes. + + node=elems; // next internal node of the tree + do{ + // n = node of least frequency + n=s.heap[1]; + s.heap[1]=s.heap[s.heap_len--]; + s.pqdownheap(tree, 1); + m=s.heap[1]; // m = node of next least frequency + + s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency + s.heap[--s.heap_max] = m; + + // Create a new node father of n and m + tree[node*2] = (short)(tree[n*2] + tree[m*2]); + s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1); + tree[n*2+1] = tree[m*2+1] = (short)node; + + // and insert the new node in the heap + s.heap[1] = node++; + s.pqdownheap(tree, 1); + } + while(s.heap_len>=2); + + s.heap[--s.heap_max] = s.heap[1]; + + // At this point, the fields freq and dad are set. We can now + // generate the bit lengths. + + gen_bitlen(s); + + // The field len is now set, we can generate the bit codes + gen_codes(tree, max_code, s.bl_count); + } + + // Generate the codes for a given tree and bit counts (which need not be + // optimal). + // IN assertion: the array bl_count contains the bit length statistics for + // the given tree and the field len is set for all tree elements. + // OUT assertion: the field code is set for all tree elements of non + // zero code length. + static void gen_codes(short[] tree, // the tree to decorate + int max_code, // largest code with non zero frequency + short[] bl_count // number of codes at each bit length + ){ + short[] next_code=new short[MAX_BITS+1]; // next code value for each bit length + short code = 0; // running code value + int bits; // bit index + int n; // code index + + // The distribution counts are first used to generate the code values + // without bit reversal. + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1); + } + + // Check that the bit counts in bl_count are consistent. The last code + // must be all ones. + //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, + // "inconsistent bit counts"); + //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); + + for (n = 0; n <= max_code; n++) { + int len = tree[n*2+1]; + if (len == 0) continue; + // Now reverse the bits + tree[n*2] = (short)(bi_reverse(next_code[len]++, len)); + } + } + + // Reverse the first len bits of a code, using straightforward code (a faster + // method would use a table) + // IN assertion: 1 <= len <= 15 + static int bi_reverse(int code, // the value to invert + int len // its bit length + ){ + int res = 0; + do{ + res|=code&1; + code>>>=1; + res<<=1; + } + while(--len>0); + return res>>>1; + } +} + diff --git a/lib/jzlib/com/jcraft/jzlib/ZInputStream.java b/lib/jzlib/com/jcraft/jzlib/ZInputStream.java new file mode 100644 index 0000000..3f97c44 --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/ZInputStream.java @@ -0,0 +1,149 @@ +/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ +/* +Copyright (c) 2001 Lapo Luchini. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS +OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; +import java.io.*; + +public class ZInputStream extends FilterInputStream { + + protected ZStream z=new ZStream(); + protected int bufsize=512; + protected int flush=JZlib.Z_NO_FLUSH; + protected byte[] buf=new byte[bufsize], + buf1=new byte[1]; + protected boolean compress; + + protected InputStream in=null; + + public ZInputStream(InputStream in) { + this(in, false); + } + public ZInputStream(InputStream in, boolean nowrap) { + super(in); + this.in=in; + z.inflateInit(nowrap); + compress=false; + z.next_in=buf; + z.next_in_index=0; + z.avail_in=0; + } + + public ZInputStream(InputStream in, int level) { + super(in); + this.in=in; + z.deflateInit(level); + compress=true; + z.next_in=buf; + z.next_in_index=0; + z.avail_in=0; + } + + /*public int available() throws IOException { + return inf.finished() ? 0 : 1; + }*/ + + public int read() throws IOException { + if(read(buf1, 0, 1)==-1) + return(-1); + return(buf1[0]&0xFF); + } + + private boolean nomoreinput=false; + + public int read(byte[] b, int off, int len) throws IOException { + if(len==0) + return(0); + int err; + z.next_out=b; + z.next_out_index=off; + z.avail_out=len; + do { + if((z.avail_in==0)&&(!nomoreinput)) { // if buffer is empty and more input is avaiable, refill it + z.next_in_index=0; + z.avail_in=in.read(buf, 0, bufsize);//(bufsize<z.avail_out ? bufsize : z.avail_out)); + if(z.avail_in==-1) { + z.avail_in=0; + nomoreinput=true; + } + } + if(compress) + err=z.deflate(flush); + else + err=z.inflate(flush); + if(nomoreinput&&(err==JZlib.Z_BUF_ERROR)) + return(-1); + if(err!=JZlib.Z_OK && err!=JZlib.Z_STREAM_END) + throw new ZStreamException((compress ? "de" : "in")+"flating: "+z.msg); + if((nomoreinput||err==JZlib.Z_STREAM_END)&&(z.avail_out==len)) + return(-1); + } + while(z.avail_out==len&&err==JZlib.Z_OK); + //System.err.print("("+(len-z.avail_out)+")"); + return(len-z.avail_out); + } + + public long skip(long n) throws IOException { + int len=512; + if(n<len) + len=(int)n; + byte[] tmp=new byte[len]; + return((long)read(tmp)); + } + + public int getFlushMode() { + return(flush); + } + + public void setFlushMode(int flush) { + this.flush=flush; + } + + /** + * Returns the total number of bytes input so far. + */ + public long getTotalIn() { + return z.total_in; + } + + /** + * Returns the total number of bytes output so far. + */ + public long getTotalOut() { + return z.total_out; + } + + public void close() throws IOException{ + in.close(); + } +} diff --git a/lib/jzlib/com/jcraft/jzlib/ZOutputStream.java b/lib/jzlib/com/jcraft/jzlib/ZOutputStream.java new file mode 100644 index 0000000..afee65b --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/ZOutputStream.java @@ -0,0 +1,156 @@ +/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ +/* +Copyright (c) 2001 Lapo Luchini. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS +OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; +import java.io.*; + +public class ZOutputStream extends OutputStream { + + protected ZStream z=new ZStream(); + protected int bufsize=512; + protected int flush=JZlib.Z_NO_FLUSH; + protected byte[] buf=new byte[bufsize], + buf1=new byte[1]; + protected boolean compress; + + protected OutputStream out; + + public ZOutputStream(OutputStream out) { + super(); + this.out=out; + z.inflateInit(); + compress=false; + } + + public ZOutputStream(OutputStream out, int level) { + this(out, level, false); + } + public ZOutputStream(OutputStream out, int level, boolean nowrap) { + super(); + this.out=out; + z.deflateInit(level, nowrap); + compress=true; + } + + public void write(int b) throws IOException { + buf1[0]=(byte)b; + write(buf1, 0, 1); + } + + public void write(byte b[], int off, int len) throws IOException { + if(len==0) + return; + int err; + z.next_in=b; + z.next_in_index=off; + z.avail_in=len; + do{ + z.next_out=buf; + z.next_out_index=0; + z.avail_out=bufsize; + if(compress) + err=z.deflate(flush); + else + err=z.inflate(flush); + if(err!=JZlib.Z_OK) + throw new ZStreamException((compress?"de":"in")+"flating: "+z.msg); + out.write(buf, 0, bufsize-z.avail_out); + } + while(z.avail_in>0 || z.avail_out==0); + } + + public int getFlushMode() { + return(flush); + } + + public void setFlushMode(int flush) { + this.flush=flush; + } + + public void finish() throws IOException { + int err; + do{ + z.next_out=buf; + z.next_out_index=0; + z.avail_out=bufsize; + if(compress){ err=z.deflate(JZlib.Z_FINISH); } + else{ err=z.inflate(JZlib.Z_FINISH); } + if(err!=JZlib.Z_STREAM_END && err != JZlib.Z_OK) + throw new ZStreamException((compress?"de":"in")+"flating: "+z.msg); + if(bufsize-z.avail_out>0){ + out.write(buf, 0, bufsize-z.avail_out); + } + } + while(z.avail_in>0 || z.avail_out==0); + flush(); + } + public void end() { + if(z==null) + return; + if(compress){ z.deflateEnd(); } + else{ z.inflateEnd(); } + z.free(); + z=null; + } + public void close() throws IOException { + try{ + try{finish();} + catch (IOException ignored) {} + } + finally{ + end(); + out.close(); + out=null; + } + } + + /** + * Returns the total number of bytes input so far. + */ + public long getTotalIn() { + return z.total_in; + } + + /** + * Returns the total number of bytes output so far. + */ + public long getTotalOut() { + return z.total_out; + } + + public void flush() throws IOException { + out.flush(); + } + +} diff --git a/lib/jzlib/com/jcraft/jzlib/ZStream.java b/lib/jzlib/com/jcraft/jzlib/ZStream.java new file mode 100644 index 0000000..334475e --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/ZStream.java @@ -0,0 +1,211 @@ +/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +final public class ZStream{ + + static final private int MAX_WBITS=15; // 32K LZ77 window + static final private int DEF_WBITS=MAX_WBITS; + + static final private int Z_NO_FLUSH=0; + static final private int Z_PARTIAL_FLUSH=1; + static final private int Z_SYNC_FLUSH=2; + static final private int Z_FULL_FLUSH=3; + static final private int Z_FINISH=4; + + static final private int MAX_MEM_LEVEL=9; + + static final private int Z_OK=0; + static final private int Z_STREAM_END=1; + static final private int Z_NEED_DICT=2; + static final private int Z_ERRNO=-1; + static final private int Z_STREAM_ERROR=-2; + static final private int Z_DATA_ERROR=-3; + static final private int Z_MEM_ERROR=-4; + static final private int Z_BUF_ERROR=-5; + static final private int Z_VERSION_ERROR=-6; + + public byte[] next_in; // next input byte + public int next_in_index; + public int avail_in; // number of bytes available at next_in + public long total_in; // total nb of input bytes read so far + + public byte[] next_out; // next output byte should be put there + public int next_out_index; + public int avail_out; // remaining free space at next_out + public long total_out; // total nb of bytes output so far + + public String msg; + + Deflate dstate; + Inflate istate; + + int data_type; // best guess about the data type: ascii or binary + + public long adler; + Adler32 _adler=new Adler32(); + + public int inflateInit(){ + return inflateInit(DEF_WBITS); + } + public int inflateInit(boolean nowrap){ + return inflateInit(DEF_WBITS, nowrap); + } + public int inflateInit(int w){ + return inflateInit(w, false); + } + + public int inflateInit(int w, boolean nowrap){ + istate=new Inflate(); + return istate.inflateInit(this, nowrap?-w:w); + } + + public int inflate(int f){ + if(istate==null) return Z_STREAM_ERROR; + return istate.inflate(this, f); + } + public int inflateEnd(){ + if(istate==null) return Z_STREAM_ERROR; + int ret=istate.inflateEnd(this); + istate = null; + return ret; + } + public int inflateSync(){ + if(istate == null) + return Z_STREAM_ERROR; + return istate.inflateSync(this); + } + public int inflateSetDictionary(byte[] dictionary, int dictLength){ + if(istate == null) + return Z_STREAM_ERROR; + return istate.inflateSetDictionary(this, dictionary, dictLength); + } + + public int deflateInit(int level){ + return deflateInit(level, MAX_WBITS); + } + public int deflateInit(int level, boolean nowrap){ + return deflateInit(level, MAX_WBITS, nowrap); + } + public int deflateInit(int level, int bits){ + return deflateInit(level, bits, false); + } + public int deflateInit(int level, int bits, boolean nowrap){ + dstate=new Deflate(); + return dstate.deflateInit(this, level, nowrap?-bits:bits); + } + public int deflate(int flush){ + if(dstate==null){ + return Z_STREAM_ERROR; + } + return dstate.deflate(this, flush); + } + public int deflateEnd(){ + if(dstate==null) return Z_STREAM_ERROR; + int ret=dstate.deflateEnd(); + dstate=null; + return ret; + } + public int deflateParams(int level, int strategy){ + if(dstate==null) return Z_STREAM_ERROR; + return dstate.deflateParams(this, level, strategy); + } + public int deflateSetDictionary (byte[] dictionary, int dictLength){ + if(dstate == null) + return Z_STREAM_ERROR; + return dstate.deflateSetDictionary(this, dictionary, dictLength); + } + + // Flush as much pending output as possible. All deflate() output goes + // through this function so some applications may wish to modify it + // to avoid allocating a large strm->next_out buffer and copying into it. + // (See also read_buf()). + void flush_pending(){ + int len=dstate.pending; + + if(len>avail_out) len=avail_out; + if(len==0) return; + + if(dstate.pending_buf.length<=dstate.pending_out || + next_out.length<=next_out_index || + dstate.pending_buf.length<(dstate.pending_out+len) || + next_out.length<(next_out_index+len)){ + System.out.println(dstate.pending_buf.length+", "+dstate.pending_out+ + ", "+next_out.length+", "+next_out_index+", "+len); + System.out.println("avail_out="+avail_out); + } + + System.arraycopy(dstate.pending_buf, dstate.pending_out, + next_out, next_out_index, len); + + next_out_index+=len; + dstate.pending_out+=len; + total_out+=len; + avail_out-=len; + dstate.pending-=len; + if(dstate.pending==0){ + dstate.pending_out=0; + } + } + + // Read a new buffer from the current input stream, update the adler32 + // and total number of bytes read. All deflate() input goes through + // this function so some applications may wish to modify it to avoid + // allocating a large strm->next_in buffer and copying from it. + // (See also flush_pending()). + int read_buf(byte[] buf, int start, int size) { + int len=avail_in; + + if(len>size) len=size; + if(len==0) return 0; + + avail_in-=len; + + if(dstate.noheader==0) { + adler=_adler.adler32(adler, next_in, next_in_index, len); + } + System.arraycopy(next_in, next_in_index, buf, start, len); + next_in_index += len; + total_in += len; + return len; + } + + public void free(){ + next_in=null; + next_out=null; + msg=null; + _adler=null; + } +} diff --git a/lib/jzlib/com/jcraft/jzlib/ZStreamException.java b/lib/jzlib/com/jcraft/jzlib/ZStreamException.java new file mode 100644 index 0000000..424b74b --- /dev/null +++ b/lib/jzlib/com/jcraft/jzlib/ZStreamException.java @@ -0,0 +1,44 @@ +/* -*-mode:java; c-basic-offset:2; -*- */ +/* +Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * This program is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) + * and contributors of zlib. + */ + +package com.jcraft.jzlib; + +public class ZStreamException extends java.io.IOException { + public ZStreamException() { + super(); + } + public ZStreamException(String s) { + super(s); + } +}
saces/SchwachkopfEinsteck
a9ccb4071114fce3c63b5433c7c655062962f247
add submodules 'ernie' (incubation stuff for fred) and jgit
diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..58eedcc --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "lib/ernie"] + path = lib/ernie + url = git://github.com/saces/ernie.git +[submodule "lib/jgit"] + path = lib/jgit + url = git://github.com/saces/jgit.git diff --git a/lib/ernie b/lib/ernie new file mode 160000 index 0000000..d6d4fca --- /dev/null +++ b/lib/ernie @@ -0,0 +1 @@ +Subproject commit d6d4fcab4f89e2cf2711b42a45e23fb8db6cb43f diff --git a/lib/jgit b/lib/jgit new file mode 160000 index 0000000..c799578 --- /dev/null +++ b/lib/jgit @@ -0,0 +1 @@ +Subproject commit c7995781d6003996d5990bc9b8bce72952a4ace6
saces/SchwachkopfEinsteck
66d151dacae37c9d8f0d62ddc88fb236f842cbe5
add gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ababea5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/build +/build-test +/dist
Boldewyn/view-source
f425605366b9f5a52e6a71632785d6e4543c705e
changes in source markup, styled element names
diff --git a/library.xsl b/library.xsl index 02380d4..6f352b8 100644 --- a/library.xsl +++ b/library.xsl @@ -1,211 +1,211 @@ <?xml version="1.0" ?> <t:stylesheet version="1.0" xmlns:t="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> <t:variable name="ns" xmlns=""> <empty></empty> <xml>http://www.w3.org/XML/1998/namespace</xml> <xmlns>http://www.w3.org/2000/xmlns/</xmlns> <xhtml>http://www.w3.org/1999/xhtml</xhtml> <svg>http://www.w3.org/2000/svg</svg> <mathml>http://www.w3.org/1998/Math/MathML</mathml> <xslt>http://www.w3.org/1999/XSL/Transform</xslt> <fo>http://www.w3.org/1999/XSL/Format</fo> <smil>http://www.w3.org/2005/SMIL21/Language</smil> <xlink>http://www.w3.org/1999/xlink</xlink> <xsd>http://www.w3.org/2001/XMLSchema</xsd> <xsd-inst>http://www.w3.org/2001/XMLSchema-instance</xsd-inst> <xforms>http://www.w3.org/2001/xforms</xforms> <xinclude>http://www.w3.org/2001/XInclude</xinclude> <xul>http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul</xul> <rdf>http://www.w3.org/1999/02/22-rdf-syntax-ns#</rdf> </t:variable> <!-- format text, so that newlines get indented correctly --> <t:template name="format-text"> <t:param name="text" select="." /> <t:param name="indent" /> <t:choose> <t:when test="contains($text, '&#xA;')"> <t:value-of select="normalize-space(substring-before($text, '&#xA;'))" /> <t:text>&#xA;</t:text> <t:value-of select="$indent" /> <t:call-template name="format-text"> <t:with-param name="text" select="substring-after($text, '&#xA;')" /> <t:with-param name="indent" select="$indent " /> </t:call-template> </t:when> <t:otherwise> <t:value-of select="normalize-space($text)" /> </t:otherwise> </t:choose> </t:template> <!-- HTML entity quote stuff --> <t:template name="quote"> <t:param name="text" /> <t:call-template name="replace"> <t:with-param name="text"> <t:call-template name="replace"> <t:with-param name="text"> <t:call-template name="replace"> <t:with-param name="text"> <t:call-template name="replace"> <t:with-param name="text"> <t:call-template name="replace"> <t:with-param name="text"> <t:value-of select="$text" /> </t:with-param> <t:with-param name="from" select="'&amp;'" /> <t:with-param name="to" select="'&amp;amp;'" /> </t:call-template> </t:with-param> <t:with-param name="from" select='"&apos;"' /> <t:with-param name="to" select="'&amp;apos;'" /> </t:call-template> </t:with-param> <t:with-param name="from" select="'&quot;'" /> <t:with-param name="to" select="'&amp;quot;'" /> </t:call-template> </t:with-param> <t:with-param name="from" select="'&gt;'" /> <t:with-param name="to" select="'&amp;gt;'" /> </t:call-template> </t:with-param> <t:with-param name="from" select="'&lt;'" /> <t:with-param name="to" select="'&amp;lt;'" /> </t:call-template> </t:template> <!-- replace a string with another --> <t:template name="replace"> <t:param name="text" /> <t:param name="from" /> <t:param name="to" /> <t:choose> <t:when test="not($from)"> <t:value-of select="$text" /> </t:when> <t:when test="contains($text, $from)"> <t:value-of select="substring-before($text, $from)" /> <t:value-of select="$to" /> <t:call-template name="replace"> <t:with-param name="text" select="substring-after($text, $from)" /> <t:with-param name="from" select="$from" /> <t:with-param name="to" select="$to" /> </t:call-template> </t:when> <t:otherwise> <t:value-of select="$text" /> </t:otherwise> </t:choose> </t:template> <!-- parse the value of an attribute (find links and make them clickable) --> <t:template name="parse-attval"> <t:param name="att" select="." /> <t:choose> <!-- FIXME: element{xhtml} / @attr{obscure-ns} 'href' gets linkified --> <t:when test="(namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/xml/text() and ( local-name($att) = 'base' )) or (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/xhtml/text() and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/svg/text() and ( local-name($att) = 'src' )) or (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/xslt/text() and ( local-name($att) = 'href' )) or (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/smil/text() and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att) = document('')//t:variable[@name = 'ns']/xlink/text() and ( local-name($att) = 'href' or local-name($att) = 'role' )) or contains(substring($att, 1, 7), 'http://') or contains(substring($att, 1, 8), 'https://') or contains(substring($att, 1, 7), 'file://') or contains(substring($att, 1, 7), 'mailto:') or contains(substring($att, 1, 6), 'ftp://') or contains(substring($att, 1, 7), 'ftps://') or contains(substring($att, 1, 5), 'news:') or contains(substring($att, 1, 4), 'urn:') or contains(substring($att, 1, 5), 'ldap:') or contains(substring($att, 1, 5), 'data:')"> <a> <t:attribute name="href"> <t:value-of select="$att" /> </t:attribute> <t:call-template name="quote"> <t:with-param name="text" select="$att" /> </t:call-template> </a> </t:when> <t:otherwise> <t:call-template name="quote"> <t:with-param name="text" select="$att" /> </t:call-template> </t:otherwise> </t:choose> </t:template> <!-- print the name of a node plus the namespace URI in a title attribute --> <t:template name="print-name"> <t:param name="node" select="." /> <span class="label"> <t:if test="namespace-uri($node)"> <t:attribute name="title"> <t:value-of select="namespace-uri($node)" /> </t:attribute> </t:if> <t:choose> <t:when test="name($node) != local-name($node)"> <span class="nsprefix"> <t:value-of select="substring-before(name($node), ':')" /> </span> - <span class="nscolon"> + <span class="nscolon syntax"> <t:text>:</t:text> </span> <span class="local-name"> <t:value-of select="local-name($node)" /> </span> </t:when> <t:otherwise> <t:value-of select="name($node)" /> </t:otherwise> </t:choose> </span> </t:template> <!-- check the used language against a list of known ones --> <t:template name="detect-lang"> <t:param name="node" select="." /> <t:if test="namespace-uri($node) = $highlight-namespace"> <t:text>highlight </t:text> </t:if> <t:value-of select="local-name(document('')//t:variable[@name = 'ns']/*[text() = namespace-uri($node)])" /> </t:template> <t:key name="kElemByNSURI" match="*[namespace::*[not(. = ../../namespace::*)]]" use="namespace::*[not(. = ../../namespace::*)]" /> <!-- get a list of all namespaces used in the document --> <t:template name="get-namespace-nodes"> <script type="text/javascript"> var namespaces = [ <t:for-each select="//namespace::*[not(. = ../../namespace::*)] [count(..|key('kElemByNSURI',.)[1])=1]"> <t:value-of select="concat('&quot;',.,'&quot;,')"/> </t:for-each> 'DUMMY' ]; </script> </t:template> </t:stylesheet> diff --git a/minimal.css b/minimal.css index 4da2d2d..cb63ed6 100644 --- a/minimal.css +++ b/minimal.css @@ -1,13 +1,15 @@ <css> * { margin: 0; padding: 0; } body { font: 100.01% monospace; } pre { font-family: monospace; } .element { color: #070; } .xhtml .tag { color: #044; } +.tag .label { font-weight: bold; } +.attribute .label { font-weight: normal; } .attribute { color: #700; } .text { color: #007; } .attribute-value { color: #404; } .comment { color: #333; font-style: italic; } .processing-instruction { color: #044; } </css>
Boldewyn/view-source
e40ac55b14c788b86aae807967d0a0e9e03c89b4
fixed stupid indent="yes"
diff --git a/view-source.xsl b/view-source.xsl index 3d92407..f2f4fea 100644 --- a/view-source.xsl +++ b/view-source.xsl @@ -1,70 +1,73 @@ <?xml version="1.0" ?> <?xslt-param name="format" select="false()" ?> <?xml-stylesheet type="text/xsl" href="view-source.xsl" filename="view-source.xsl" ?> <t:stylesheet version="1.0" xmlns:t="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> <t:param name="base-indent" select="' '" /> <t:param name="format" select="true()" /> <t:param name="style" select="'minimal'" /> <t:param name="add-behaviour" select="true()" /> <t:param name="highlight-namespace" select="''" /> <t:param name="filename" /> <t:variable name="version" select="'0.9'" /> <t:include href="formatted.xsl" /> <t:include href="original.xsl" /> <t:include href="library.xsl" /> - <t:output method="xml" indent="yes" + <t:output method="xml" indent="no" omit-xml-declaration="yes" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" /> <!-- master template: Decide between formatted or original rendering --> <t:template match="/"> <html xml:lang="en"> <head> <title> - XML Source - <t:if test="$filename">of <t:value-of select="$filename" /></t:if> + <t:text>XML Source</t:text> + <t:if test="$filename"> + <t:text> of </t:text> + <t:value-of select="$filename" /> + </t:if> </title> <meta name="generator" content="view-source {$version}; http://boldewyn.github.com/view-source" /> <style type="text/css"> <t:value-of select="document(concat($style, '.css'))/css" /> </style> </head> <body> <pre id="source"> <t:choose> <t:when test="$format"> <t:apply-templates mode="formatted" /> </t:when> <t:otherwise> <t:apply-templates mode="original" /> </t:otherwise> </t:choose> </pre> <t:if test="$add-behaviour"> <t:call-template name="get-namespace-nodes" /> <script type="text/javascript"> <t:value-of select="document('behaviour.js')/js" /> </script> </t:if> </body> </html> </t:template> </t:stylesheet>
Boldewyn/view-source
9ad6a669d8936db23cc6c19bf90255f567dd2a05
re-enabled title, added filename parameter, again
diff --git a/library.xsl b/library.xsl index 9242252..02380d4 100644 --- a/library.xsl +++ b/library.xsl @@ -1,211 +1,211 @@ <?xml version="1.0" ?> <t:stylesheet version="1.0" xmlns:t="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> - <t:variable select="''" name="ns.empty" /> <t:variable name="ns" xmlns=""> <empty></empty> <xml>http://www.w3.org/XML/1998/namespace</xml> <xmlns>http://www.w3.org/2000/xmlns/</xmlns> - <xslt>http://www.w3.org/1999/XSL/Transform</xslt> <xhtml>http://www.w3.org/1999/xhtml</xhtml> <svg>http://www.w3.org/2000/svg</svg> <mathml>http://www.w3.org/1998/Math/MathML</mathml> - <smil>http://www.w3.org/2005/SMIL21/Language</smil> + <xslt>http://www.w3.org/1999/XSL/Transform</xslt> <fo>http://www.w3.org/1999/XSL/Format</fo> + <smil>http://www.w3.org/2005/SMIL21/Language</smil> <xlink>http://www.w3.org/1999/xlink</xlink> <xsd>http://www.w3.org/2001/XMLSchema</xsd> <xsd-inst>http://www.w3.org/2001/XMLSchema-instance</xsd-inst> <xforms>http://www.w3.org/2001/xforms</xforms> <xinclude>http://www.w3.org/2001/XInclude</xinclude> <xul>http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul</xul> <rdf>http://www.w3.org/1999/02/22-rdf-syntax-ns#</rdf> </t:variable> <!-- format text, so that newlines get indented correctly --> <t:template name="format-text"> <t:param name="text" select="." /> <t:param name="indent" /> <t:choose> <t:when test="contains($text, '&#xA;')"> <t:value-of select="normalize-space(substring-before($text, '&#xA;'))" /> <t:text>&#xA;</t:text> <t:value-of select="$indent" /> <t:call-template name="format-text"> <t:with-param name="text" select="substring-after($text, '&#xA;')" /> <t:with-param name="indent" select="$indent " /> </t:call-template> </t:when> <t:otherwise> <t:value-of select="normalize-space($text)" /> </t:otherwise> </t:choose> </t:template> <!-- HTML entity quote stuff --> <t:template name="quote"> <t:param name="text" /> <t:call-template name="replace"> <t:with-param name="text"> <t:call-template name="replace"> <t:with-param name="text"> <t:call-template name="replace"> <t:with-param name="text"> <t:call-template name="replace"> <t:with-param name="text"> <t:call-template name="replace"> <t:with-param name="text"> <t:value-of select="$text" /> </t:with-param> <t:with-param name="from" select="'&amp;'" /> <t:with-param name="to" select="'&amp;amp;'" /> </t:call-template> </t:with-param> <t:with-param name="from" select='"&apos;"' /> <t:with-param name="to" select="'&amp;apos;'" /> </t:call-template> </t:with-param> <t:with-param name="from" select="'&quot;'" /> <t:with-param name="to" select="'&amp;quot;'" /> </t:call-template> </t:with-param> <t:with-param name="from" select="'&gt;'" /> <t:with-param name="to" select="'&amp;gt;'" /> </t:call-template> </t:with-param> <t:with-param name="from" select="'&lt;'" /> <t:with-param name="to" select="'&amp;lt;'" /> </t:call-template> </t:template> <!-- replace a string with another --> <t:template name="replace"> <t:param name="text" /> <t:param name="from" /> <t:param name="to" /> <t:choose> <t:when test="not($from)"> <t:value-of select="$text" /> </t:when> <t:when test="contains($text, $from)"> <t:value-of select="substring-before($text, $from)" /> <t:value-of select="$to" /> <t:call-template name="replace"> <t:with-param name="text" select="substring-after($text, $from)" /> <t:with-param name="from" select="$from" /> <t:with-param name="to" select="$to" /> </t:call-template> </t:when> <t:otherwise> <t:value-of select="$text" /> </t:otherwise> </t:choose> </t:template> <!-- parse the value of an attribute (find links and make them clickable) --> <t:template name="parse-attval"> <t:param name="att" select="." /> <t:choose> + <!-- FIXME: element{xhtml} / @attr{obscure-ns} 'href' gets linkified --> <t:when test="(namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/xml/text() and ( local-name($att) = 'base' )) or (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/xhtml/text() and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/svg/text() and ( local-name($att) = 'src' )) or (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/xslt/text() and ( local-name($att) = 'href' )) or (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/smil/text() and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att) = document('')//t:variable[@name = 'ns']/xlink/text() and ( local-name($att) = 'href' or local-name($att) = 'role' )) or contains(substring($att, 1, 7), 'http://') or contains(substring($att, 1, 8), 'https://') or contains(substring($att, 1, 7), 'file://') or contains(substring($att, 1, 7), 'mailto:') or contains(substring($att, 1, 6), 'ftp://') or contains(substring($att, 1, 7), 'ftps://') or contains(substring($att, 1, 5), 'news:') or contains(substring($att, 1, 4), 'urn:') or contains(substring($att, 1, 5), 'ldap:') or contains(substring($att, 1, 5), 'data:')"> <a> <t:attribute name="href"> <t:value-of select="$att" /> </t:attribute> <t:call-template name="quote"> <t:with-param name="text" select="$att" /> </t:call-template> </a> </t:when> <t:otherwise> <t:call-template name="quote"> <t:with-param name="text" select="$att" /> </t:call-template> </t:otherwise> </t:choose> </t:template> <!-- print the name of a node plus the namespace URI in a title attribute --> <t:template name="print-name"> <t:param name="node" select="." /> <span class="label"> - <t:if test="namespace-uri($node) != document('')//t:variable[@name = 'ns']/empty/text()"> + <t:if test="namespace-uri($node)"> <t:attribute name="title"> <t:value-of select="namespace-uri($node)" /> </t:attribute> </t:if> <t:choose> <t:when test="name($node) != local-name($node)"> <span class="nsprefix"> <t:value-of select="substring-before(name($node), ':')" /> </span> <span class="nscolon"> <t:text>:</t:text> </span> <span class="local-name"> <t:value-of select="local-name($node)" /> </span> </t:when> <t:otherwise> <t:value-of select="name($node)" /> </t:otherwise> </t:choose> </span> </t:template> <!-- check the used language against a list of known ones --> <t:template name="detect-lang"> <t:param name="node" select="." /> <t:if test="namespace-uri($node) = $highlight-namespace"> <t:text>highlight </t:text> </t:if> <t:value-of select="local-name(document('')//t:variable[@name = 'ns']/*[text() = namespace-uri($node)])" /> </t:template> <t:key name="kElemByNSURI" match="*[namespace::*[not(. = ../../namespace::*)]]" use="namespace::*[not(. = ../../namespace::*)]" /> <!-- get a list of all namespaces used in the document --> <t:template name="get-namespace-nodes"> <script type="text/javascript"> var namespaces = [ <t:for-each select="//namespace::*[not(. = ../../namespace::*)] [count(..|key('kElemByNSURI',.)[1])=1]"> <t:value-of select="concat('&quot;',.,'&quot;,')"/> </t:for-each> 'DUMMY' ]; </script> </t:template> </t:stylesheet> diff --git a/minimal.css b/minimal.css index 6b6ee40..4da2d2d 100644 --- a/minimal.css +++ b/minimal.css @@ -1,11 +1,13 @@ <css> * { margin: 0; padding: 0; } body { font: 100.01% monospace; } pre { font-family: monospace; } .element { color: #070; } +.xhtml .tag { color: #044; } + .attribute { color: #700; } .text { color: #007; } .attribute-value { color: #404; } .comment { color: #333; font-style: italic; } .processing-instruction { color: #044; } </css> diff --git a/view-source.xsl b/view-source.xsl index 434310c..3d92407 100644 --- a/view-source.xsl +++ b/view-source.xsl @@ -1,59 +1,70 @@ <?xml version="1.0" ?> <?xslt-param name="format" select="false()" ?> <?xml-stylesheet type="text/xsl" href="view-source.xsl" filename="view-source.xsl" ?> <t:stylesheet version="1.0" xmlns:t="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> <t:param name="base-indent" select="' '" /> <t:param name="format" select="true()" /> <t:param name="style" select="'minimal'" /> <t:param name="add-behaviour" select="true()" /> <t:param name="highlight-namespace" select="''" /> + <t:param name="filename" /> + + <t:variable name="version" select="'0.9'" /> + <t:include href="formatted.xsl" /> <t:include href="original.xsl" /> <t:include href="library.xsl" /> <t:output method="xml" indent="yes" omit-xml-declaration="yes" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" /> + <!-- + master template: Decide between formatted or original rendering + --> <t:template match="/"> - <html> + <html xml:lang="en"> <head> - <title>XML Source</title> + <title> + XML Source + <t:if test="$filename">of <t:value-of select="$filename" /></t:if> + </title> + <meta name="generator" content="view-source {$version}; http://boldewyn.github.com/view-source" /> <style type="text/css"> <t:value-of select="document(concat($style, '.css'))/css" /> </style> </head> <body> <pre id="source"> <t:choose> <t:when test="$format"> <t:apply-templates mode="formatted" /> </t:when> <t:otherwise> <t:apply-templates mode="original" /> </t:otherwise> </t:choose> </pre> <t:if test="$add-behaviour"> <t:call-template name="get-namespace-nodes" /> <script type="text/javascript"> <t:value-of select="document('behaviour.js')/js" /> </script> </t:if> </body> </html> </t:template> </t:stylesheet>
Boldewyn/view-source
3d5e8e8dfea98f6e2e25d9110c9fec2002d423dd
unfortunately a whole bulk of changes: Renamed namespaces, incorporated SO tip about listing namespaces (thanks SO user Alejandro), restructured checking for known languages, added the namespace of a node as title attribute
diff --git a/formatted.xsl b/formatted.xsl index 19dbf91..6878080 100644 --- a/formatted.xsl +++ b/formatted.xsl @@ -1,115 +1,115 @@ <?xml version="1.0" ?> -<stylesheet version="1.0" - xmlns="http://www.w3.org/1999/XSL/Transform" - xmlns:h="http://www.w3.org/1999/xhtml"> +<t:stylesheet version="1.0" + xmlns:t="http://www.w3.org/1999/XSL/Transform" + xmlns="http://www.w3.org/1999/xhtml"> <!-- Elements (formatted) --> - <template match="*" mode="formatted"> - <param name="indent" /> - <variable name="lang"> - <call-template name="detect-lang" /> - </variable> - <value-of select="$indent" /> - <choose> - <when test="node()"> - <h:span class="{$lang} element"> - <h:span class="tag start"> - <text>&lt;</text> - <value-of select="name(.)" /> - <for-each select="@*"> - <apply-templates select="." mode="formatted" /> - </for-each> - <text>&gt;</text> - </h:span> - <text>&#x0A;</text> - <apply-templates mode="formatted"> - <with-param name="indent" select="concat($indent, $base-indent)" /> - </apply-templates> - <value-of select="$indent" /> - <h:span class="tag end"> - <text>&lt;/</text> - <value-of select="name(.)"/> - <text>&gt;</text> - </h:span> - </h:span> - </when> - <otherwise> - <h:span class="{$lang} element empty"> - <h:span class="tag empty"> - <text>&lt;</text> - <value-of select="name(.)" /> - <for-each select="@*"> - <apply-templates select="." mode="formatted" /> - </for-each> - <text> /&gt;</text> - </h:span> - </h:span> - </otherwise> - </choose> - <text>&#xA;</text> - </template> + <t:template match="*" mode="formatted"> + <t:param name="indent" /> + <t:variable name="lang"> + <t:call-template name="detect-lang" /> + </t:variable> + <t:value-of select="$indent" /> + <t:choose> + <t:when test="node()"> + <span class="{$lang} element"> + <span class="tag start"> + <t:text>&lt;</t:text> + <t:call-template name="print-name" /> + <t:for-each select="@*"> + <t:apply-templates select="." mode="formatted" /> + </t:for-each> + <t:text>&gt;</t:text> + </span> + <t:text>&#x0A;</t:text> + <t:apply-templates mode="formatted"> + <t:with-param name="indent" select="concat($indent, $base-indent)" /> + </t:apply-templates> + <t:value-of select="$indent" /> + <span class="tag end"> + <t:text>&lt;/</t:text> + <t:value-of select="name(.)"/> + <t:text>&gt;</t:text> + </span> + </span> + </t:when> + <t:otherwise> + <span class="{$lang} element empty"> + <span class="tag empty"> + <t:text>&lt;</t:text> + <t:call-template name="print-name" /> + <t:for-each select="@*"> + <t:apply-templates select="." mode="formatted" /> + </t:for-each> + <t:text> /&gt;</t:text> + </span> + </span> + </t:otherwise> + </t:choose> + <t:text>&#xA;</t:text> + </t:template> <!-- Attributes (formatted) --> - <template match="@*" mode="formatted"> - <variable name="lang"> - <call-template name="detect-lang" /> - </variable> - <text> </text> - <h:span class="{$lang} attribute"> - <value-of select="name()" /> - <text>="</text> - <h:span class="attribute-value"> - <call-template name="parse-attval" /> - </h:span> - <text>"</text> - </h:span> - </template> + <t:template match="@*" mode="formatted"> + <t:variable name="lang"> + <t:call-template name="detect-lang" /> + </t:variable> + <t:text> </t:text> + <span class="{$lang} attribute"> + <t:call-template name="print-name" /> + <t:text>="</t:text> + <span class="attribute-value"> + <t:call-template name="parse-attval" /> + </span> + <t:text>"</t:text> + </span> + </t:template> <!-- Processing Instructions (formatted) --> - <template match="processing-instruction()" mode="formatted"> - <param name="indent" /> - <value-of select="$indent" /> - <h:span class="processing-instruction"> - <text>&lt;?</text> - <value-of select="name(.)" /> - <text> </text> - <call-template name="format-text"> - <with-param name="text" select="." /> - <with-param name="indent" select="$indent" /> - </call-template> - <text>?&gt;</text> - </h:span> - <text>&#xA;</text> - </template> + <t:template match="processing-instruction()" mode="formatted"> + <t:param name="indent" /> + <t:value-of select="$indent" /> + <span class="processing-instruction"> + <t:text>&lt;?</t:text> + <t:value-of select="name(.)" /> + <t:text> </t:text> + <t:call-template name="format-text"> + <t:with-param name="text" select="." /> + <t:with-param name="indent" select="$indent" /> + </t:call-template> + <t:text>?&gt;</t:text> + </span> + <t:text>&#xA;</t:text> + </t:template> <!-- Comments (formatted) --> - <template match="comment()" mode="formatted"> - <param name="indent" /> - <value-of select="$indent" /> - <h:span class="comment"> - <text>&lt;!--</text> - <call-template name="format-text"> - <with-param name="text" select="." /> - <with-param name="indent" select="$indent" /> - </call-template> - <text>--></text> - </h:span> - <text>&#xA;</text> - </template> + <t:template match="comment()" mode="formatted"> + <t:param name="indent" /> + <t:value-of select="$indent" /> + <span class="comment"> + <t:text>&lt;!--</t:text> + <t:call-template name="format-text"> + <t:with-param name="text" select="." /> + <t:with-param name="indent" select="$indent" /> + </t:call-template> + <t:text>--></t:text> + </span> + <t:text>&#xA;</t:text> + </t:template> <!-- Text (formatted) --> - <template match="text()" mode="formatted"> - <param name="indent" /> - <if test="normalize-space()"> - <value-of select="$indent" /> - <h:span class="text"> - <call-template name="format-text"> - <with-param name="text" select="." /> - <with-param name="indent" select="$indent" /> - </call-template> - </h:span> - <text>&#xA;</text> - </if> - </template> + <t:template match="text()" mode="formatted"> + <t:param name="indent" /> + <t:if test="normalize-space()"> + <t:value-of select="$indent" /> + <span class="text"> + <t:call-template name="format-text"> + <t:with-param name="text" select="." /> + <t:with-param name="indent" select="$indent" /> + </t:call-template> + </span> + <t:text>&#xA;</t:text> + </t:if> + </t:template> -</stylesheet> +</t:stylesheet> diff --git a/library.xsl b/library.xsl index f0222b6..9242252 100644 --- a/library.xsl +++ b/library.xsl @@ -1,187 +1,211 @@ <?xml version="1.0" ?> -<stylesheet version="1.0" - xmlns="http://www.w3.org/1999/XSL/Transform" - xmlns:h="http://www.w3.org/1999/xhtml"> +<t:stylesheet version="1.0" + xmlns:t="http://www.w3.org/1999/XSL/Transform" + xmlns="http://www.w3.org/1999/xhtml"> - <variable select="''" name="ns.empty" /> - <variable select="'http://www.w3.org/XML/1998/namespace'" name="ns.xml" /> - <variable select="'http://www.w3.org/2000/xmlns/'" name="ns.xmlns" /> - <variable select="'http://www.w3.org/1999/XSL/Transform'" name="ns.xslt" /> - <variable select="'http://www.w3.org/1999/xhtml'" name="ns.xhtml" /> - <variable select="'http://www.w3.org/2000/svg'" name="ns.svg" /> - <variable select="'http://www.w3.org/1998/Math/MathML'" name="ns.mathml" /> - <variable select="'http://www.w3.org/2005/SMIL21/Language'" name="ns.smil" /> - <variable select="'http://www.w3.org/1999/XSL/Format'" name="ns.fo" /> - <variable select="'http://www.w3.org/1999/xlink'" name="ns.xlink" /> - <variable select="'http://www.w3.org/2001/XMLSchema'" name="ns.xsd" /> - <variable select="'http://www.w3.org/2001/XMLSchema-instance'" name="ns.xsd-inst" /> - <variable select="'http://www.w3.org/2001/xforms'" name="ns.xforms" /> + <t:variable select="''" name="ns.empty" /> + <t:variable name="ns" xmlns=""> + <empty></empty> + <xml>http://www.w3.org/XML/1998/namespace</xml> + <xmlns>http://www.w3.org/2000/xmlns/</xmlns> + <xslt>http://www.w3.org/1999/XSL/Transform</xslt> + <xhtml>http://www.w3.org/1999/xhtml</xhtml> + <svg>http://www.w3.org/2000/svg</svg> + <mathml>http://www.w3.org/1998/Math/MathML</mathml> + <smil>http://www.w3.org/2005/SMIL21/Language</smil> + <fo>http://www.w3.org/1999/XSL/Format</fo> + <xlink>http://www.w3.org/1999/xlink</xlink> + <xsd>http://www.w3.org/2001/XMLSchema</xsd> + <xsd-inst>http://www.w3.org/2001/XMLSchema-instance</xsd-inst> + <xforms>http://www.w3.org/2001/xforms</xforms> + <xinclude>http://www.w3.org/2001/XInclude</xinclude> + <xul>http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul</xul> + <rdf>http://www.w3.org/1999/02/22-rdf-syntax-ns#</rdf> + </t:variable> - <!-- def format-text --> - <template name="format-text"> - <param name="text" select="." /> - <param name="indent" /> - <choose> - <when test="contains($text, '&#xA;')"> - <value-of select="normalize-space(substring-before($text, '&#xA;'))" /> - <text>&#xA;</text> - <value-of select="$indent" /> - <call-template name="format-text"> - <with-param name="text" select="substring-after($text, '&#xA;')" /> - <with-param name="indent" select="$indent " /> - </call-template> - </when> - <otherwise> - <value-of select="normalize-space($text)" /> - </otherwise> - </choose> - </template> + <!-- + format text, so that newlines get indented correctly + --> + <t:template name="format-text"> + <t:param name="text" select="." /> + <t:param name="indent" /> + <t:choose> + <t:when test="contains($text, '&#xA;')"> + <t:value-of select="normalize-space(substring-before($text, '&#xA;'))" /> + <t:text>&#xA;</t:text> + <t:value-of select="$indent" /> + <t:call-template name="format-text"> + <t:with-param name="text" select="substring-after($text, '&#xA;')" /> + <t:with-param name="indent" select="$indent " /> + </t:call-template> + </t:when> + <t:otherwise> + <t:value-of select="normalize-space($text)" /> + </t:otherwise> + </t:choose> + </t:template> - <!-- def quote --> - <template name="quote"> - <param name="text" /> - <call-template name="replace"> - <with-param name="text"> - <call-template name="replace"> - <with-param name="text"> - <call-template name="replace"> - <with-param name="text"> - <call-template name="replace"> - <with-param name="text"> - <call-template name="replace"> - <with-param name="text"> - <value-of select="$text" /> - </with-param> - <with-param name="from" select="'&amp;'" /> - <with-param name="to" select="'&amp;amp;'" /> - </call-template> - </with-param> - <with-param name="from" select='"&apos;"' /> - <with-param name="to" select="'&amp;apos;'" /> - </call-template> - </with-param> - <with-param name="from" select="'&quot;'" /> - <with-param name="to" select="'&amp;quot;'" /> - </call-template> - </with-param> - <with-param name="from" select="'&gt;'" /> - <with-param name="to" select="'&amp;gt;'" /> - </call-template> - </with-param> - <with-param name="from" select="'&lt;'" /> - <with-param name="to" select="'&amp;lt;'" /> - </call-template> - </template> + <!-- + HTML entity quote stuff + --> + <t:template name="quote"> + <t:param name="text" /> + <t:call-template name="replace"> + <t:with-param name="text"> + <t:call-template name="replace"> + <t:with-param name="text"> + <t:call-template name="replace"> + <t:with-param name="text"> + <t:call-template name="replace"> + <t:with-param name="text"> + <t:call-template name="replace"> + <t:with-param name="text"> + <t:value-of select="$text" /> + </t:with-param> + <t:with-param name="from" select="'&amp;'" /> + <t:with-param name="to" select="'&amp;amp;'" /> + </t:call-template> + </t:with-param> + <t:with-param name="from" select='"&apos;"' /> + <t:with-param name="to" select="'&amp;apos;'" /> + </t:call-template> + </t:with-param> + <t:with-param name="from" select="'&quot;'" /> + <t:with-param name="to" select="'&amp;quot;'" /> + </t:call-template> + </t:with-param> + <t:with-param name="from" select="'&gt;'" /> + <t:with-param name="to" select="'&amp;gt;'" /> + </t:call-template> + </t:with-param> + <t:with-param name="from" select="'&lt;'" /> + <t:with-param name="to" select="'&amp;lt;'" /> + </t:call-template> + </t:template> - <!-- def replace --> - <template name="replace"> - <param name="text" /> - <param name="from" /> - <param name="to" /> - <choose> - <when test="not($from)"> - <value-of select="$text" /> - </when> - <when test="contains($text, $from)"> - <value-of select="substring-before($text, $from)" /> - <value-of select="$to" /> - <call-template name="replace"> - <with-param name="text" select="substring-after($text, $from)" /> - <with-param name="from" select="$from" /> - <with-param name="to" select="$to" /> - </call-template> - </when> - <otherwise> - <value-of select="$text" /> - </otherwise> - </choose> - </template> + <!-- + replace a string with another + --> + <t:template name="replace"> + <t:param name="text" /> + <t:param name="from" /> + <t:param name="to" /> + <t:choose> + <t:when test="not($from)"> + <t:value-of select="$text" /> + </t:when> + <t:when test="contains($text, $from)"> + <t:value-of select="substring-before($text, $from)" /> + <t:value-of select="$to" /> + <t:call-template name="replace"> + <t:with-param name="text" select="substring-after($text, $from)" /> + <t:with-param name="from" select="$from" /> + <t:with-param name="to" select="$to" /> + </t:call-template> + </t:when> + <t:otherwise> + <t:value-of select="$text" /> + </t:otherwise> + </t:choose> + </t:template> - <!-- def parse_attval --> - <template name="parse-attval"> - <param name="att" select="." /> - <choose> - <when test="(namespace-uri($att/..) = $ns.xml and ( local-name($att) = 'base' )) or - (namespace-uri($att/..) = $ns.xhtml and ( local-name($att) = 'src' or local-name($att) = 'href' )) or - (namespace-uri($att/..) = $ns.svg and ( local-name($att) = 'src' )) or - (namespace-uri($att/..) = $ns.xslt and ( local-name($att) = 'href' )) or - (namespace-uri($att/..) = $ns.smil and ( local-name($att) = 'src' or local-name($att) = 'href' )) or - (namespace-uri($att) = $ns.xlink and ( local-name($att) = 'href' or local-name($att) = 'role' )) or - contains(substring($att, 1, 7), 'http://') or - contains(substring($att, 1, 8), 'https://') or - contains(substring($att, 1, 7), 'file://') or - contains(substring($att, 1, 7), 'mailto:') or - contains(substring($att, 1, 6), 'ftp://') or - contains(substring($att, 1, 7), 'ftps://') or - contains(substring($att, 1, 5), 'news:') or - contains(substring($att, 1, 4), 'urn:') or - contains(substring($att, 1, 5), 'ldap:') or - contains(substring($att, 1, 5), 'data:')"> - <h:a> - <attribute name="href"> - <value-of select="$att" /> - </attribute> - <call-template name="quote"> - <with-param name="text" select="$att" /> - </call-template> - </h:a> - </when> - <otherwise> - <call-template name="quote"> - <with-param name="text" select="$att" /> - </call-template> - </otherwise> - </choose> - </template> + <!-- + parse the value of an attribute (find links and make them clickable) + --> + <t:template name="parse-attval"> + <t:param name="att" select="." /> + <t:choose> + <t:when test="(namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/xml/text() and ( local-name($att) = 'base' )) or + (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/xhtml/text() and ( local-name($att) = 'src' or local-name($att) = 'href' )) or + (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/svg/text() and ( local-name($att) = 'src' )) or + (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/xslt/text() and ( local-name($att) = 'href' )) or + (namespace-uri($att/..) = document('')//t:variable[@name = 'ns']/smil/text() and ( local-name($att) = 'src' or local-name($att) = 'href' )) or + (namespace-uri($att) = document('')//t:variable[@name = 'ns']/xlink/text() and ( local-name($att) = 'href' or local-name($att) = 'role' )) or + contains(substring($att, 1, 7), 'http://') or + contains(substring($att, 1, 8), 'https://') or + contains(substring($att, 1, 7), 'file://') or + contains(substring($att, 1, 7), 'mailto:') or + contains(substring($att, 1, 6), 'ftp://') or + contains(substring($att, 1, 7), 'ftps://') or + contains(substring($att, 1, 5), 'news:') or + contains(substring($att, 1, 4), 'urn:') or + contains(substring($att, 1, 5), 'ldap:') or + contains(substring($att, 1, 5), 'data:')"> + <a> + <t:attribute name="href"> + <t:value-of select="$att" /> + </t:attribute> + <t:call-template name="quote"> + <t:with-param name="text" select="$att" /> + </t:call-template> + </a> + </t:when> + <t:otherwise> + <t:call-template name="quote"> + <t:with-param name="text" select="$att" /> + </t:call-template> + </t:otherwise> + </t:choose> + </t:template> - <!-- def detect-lang --> - <template name="detect-lang"> - <param name="node" select="." /> - <if test="namespace-uri($node) = $highlight-namespace"> - <text>highlight </text> - </if> - <choose> - <when test="namespace-uri($node) = $ns.empty"> - <text>empty-ns</text> - </when> - <when test="namespace-uri($node) = $ns.xml"> - <text>xml</text> - </when> - <when test="namespace-uri($node) = $ns.xmlns"> - <text>xmlns</text> - </when> - <when test="namespace-uri($node) = $ns.xhtml"> - <text>xhtml</text> - </when> - <when test="namespace-uri($node) = $ns.svg"> - <text>svg</text> - </when> - <when test="namespace-uri($node) = $ns.xlink"> - <text>xlink</text> - </when> - <when test="namespace-uri($node) = $ns.xslt"> - <text>xslt</text> - </when> - <when test="namespace-uri($node) = $ns.fo"> - <text>fo</text> - </when> - <when test="namespace-uri($node) = $ns.mathml"> - <text>mathml</text> - </when> - <when test="namespace-uri($node) = $ns.xsd"> - <text>xsd</text> - </when> - <when test="namespace-uri($node) = $ns.xsd-inst"> - <text>xsd-inst</text> - </when> - <when test="namespace-uri($node) = $ns.smil"> - <text>smil</text> - </when> - <when test="namespace-uri($node) = $ns.xforms"> - <text>xforms</text> - </when> - <otherwise /> - </choose> - </template> + <!-- + print the name of a node plus the namespace URI in a title attribute + --> + <t:template name="print-name"> + <t:param name="node" select="." /> + <span class="label"> + <t:if test="namespace-uri($node) != document('')//t:variable[@name = 'ns']/empty/text()"> + <t:attribute name="title"> + <t:value-of select="namespace-uri($node)" /> + </t:attribute> + </t:if> + <t:choose> + <t:when test="name($node) != local-name($node)"> + <span class="nsprefix"> + <t:value-of select="substring-before(name($node), ':')" /> + </span> + <span class="nscolon"> + <t:text>:</t:text> + </span> + <span class="local-name"> + <t:value-of select="local-name($node)" /> + </span> + </t:when> + <t:otherwise> + <t:value-of select="name($node)" /> + </t:otherwise> + </t:choose> + </span> + </t:template> -</stylesheet> + <!-- + check the used language against a list of known ones + --> + <t:template name="detect-lang"> + <t:param name="node" select="." /> + <t:if test="namespace-uri($node) = $highlight-namespace"> + <t:text>highlight </t:text> + </t:if> + <t:value-of select="local-name(document('')//t:variable[@name = 'ns']/*[text() = namespace-uri($node)])" /> + </t:template> + + <t:key name="kElemByNSURI" + match="*[namespace::*[not(. = ../../namespace::*)]]" + use="namespace::*[not(. = ../../namespace::*)]" /> + + <!-- + get a list of all namespaces used in the document + --> + <t:template name="get-namespace-nodes"> + <script type="text/javascript"> + var namespaces = [ + <t:for-each select="//namespace::*[not(. = ../../namespace::*)] + [count(..|key('kElemByNSURI',.)[1])=1]"> + <t:value-of select="concat('&quot;',.,'&quot;,')"/> + </t:for-each> + 'DUMMY' + ]; + </script> + </t:template> + +</t:stylesheet> diff --git a/minimal.css b/minimal.css index 17034e6..6b6ee40 100644 --- a/minimal.css +++ b/minimal.css @@ -1,9 +1,11 @@ <css> * { margin: 0; padding: 0; } +body { font: 100.01% monospace; } +pre { font-family: monospace; } .element { color: #070; } .attribute { color: #700; } .text { color: #007; } .attribute-value { color: #404; } .comment { color: #333; font-style: italic; } .processing-instruction { color: #044; } </css> diff --git a/original.xsl b/original.xsl index 440aad4..ed6da79 100644 --- a/original.xsl +++ b/original.xsl @@ -1,92 +1,92 @@ <?xml version="1.0" ?> -<stylesheet version="1.0" - xmlns="http://www.w3.org/1999/XSL/Transform" - xmlns:h="http://www.w3.org/1999/xhtml"> +<t:stylesheet version="1.0" + xmlns:t="http://www.w3.org/1999/XSL/Transform" + xmlns="http://www.w3.org/1999/xhtml"> <!-- Elements (original) --> - <template match="*" mode="original"> - <variable name="lang"> - <call-template name="detect-lang" /> - </variable> - <choose> - <when test="node()"> - <h:span class="{$lang} element"> - <h:span class="tag start"> - <text>&lt;</text> - <value-of select="name(.)" /> - <for-each select="@*"> - <apply-templates select="." mode="original" /> - </for-each> - <text>&gt;</text> - </h:span> - <apply-templates mode="original" /> - <h:span class="tag end"> - <text>&lt;/</text> - <value-of select="name(.)"/> - <text>&gt;</text> - </h:span> - </h:span> - </when> - <otherwise> - <h:span class="{$lang} element empty"> - <h:span class="tag empty"> - <text>&lt;</text> - <value-of select="name(.)" /> - <for-each select="@*"> - <apply-templates select="." mode="original" /> - </for-each> - <text> /&gt;</text> - </h:span> - </h:span> - </otherwise> - </choose> - </template> + <t:template match="*" mode="original"> + <t:variable name="lang"> + <t:call-template name="detect-lang" /> + </t:variable> + <t:choose> + <t:when test="node()"> + <span class="{$lang} element"> + <span class="tag start"> + <t:text>&lt;</t:text> + <t:call-template name="print-name" /> + <t:for-each select="@*"> + <t:apply-templates select="." mode="original" /> + </t:for-each> + <t:text>&gt;</t:text> + </span> + <t:apply-templates mode="original" /> + <span class="tag end"> + <t:text>&lt;/</t:text> + <t:value-of select="name(.)"/> + <t:text>&gt;</t:text> + </span> + </span> + </t:when> + <t:otherwise> + <span class="{$lang} element empty"> + <span class="tag empty"> + <t:text>&lt;</t:text> + <t:call-template name="print-name" /> + <t:for-each select="@*"> + <t:apply-templates select="." mode="original" /> + </t:for-each> + <t:text> /&gt;</t:text> + </span> + </span> + </t:otherwise> + </t:choose> + </t:template> <!-- Attributes (original) --> - <template match="@*" mode="original"> - <variable name="lang"> - <call-template name="detect-lang" /> - </variable> - <text> </text> - <h:span class="{$lang} attribute"> - <value-of select="name()" /> - <text>="</text> - <h:span class="attribute-value"> - <call-template name="parse-attval" /> - </h:span> - <text>"</text> - </h:span> - </template> + <t:template match="@*" mode="original"> + <t:variable name="lang"> + <t:call-template name="detect-lang" /> + </t:variable> + <t:text> </t:text> + <span class="{$lang} attribute"> + <t:call-template name="print-name" /> + <t:text>="</t:text> + <span class="attribute-value"> + <t:call-template name="parse-attval" /> + </span> + <t:text>"</t:text> + </span> + </t:template> <!-- Processing Instructions (original) --> - <template match="processing-instruction()" mode="original"> - <h:span class="processing-instruction"> - <text>&lt;?</text> - <value-of select="name(.)" /> - <text> </text> - <value-of select="." /> - <text>?&gt;</text> - </h:span> - </template> + <t:template match="processing-instruction()" mode="original"> + <span class="processing-instruction"> + <t:text>&lt;?</t:text> + <t:value-of select="name(.)" /> + <t:text> </t:text> + <t:value-of select="." /> + <t:text>?&gt;</t:text> + </span> + </t:template> <!-- Comments (original) --> - <template match="comment()" mode="original"> - <h:span class="comment"> - <text>&lt;!--</text> - <call-template name="quote"> - <with-param name="text" select="." /> - </call-template> - <text>--></text> - </h:span> - </template> + <t:template match="comment()" mode="original"> + <span class="comment"> + <t:text>&lt;!--</t:text> + <t:call-template name="quote"> + <t:with-param name="text" select="." /> + </t:call-template> + <t:text>--></t:text> + </span> + </t:template> <!-- Text (original) --> - <template match="text()" mode="original"> - <h:span class="text"> - <call-template name="quote"> - <with-param name="text" select="." /> - </call-template> - </h:span> - </template> + <t:template match="text()" mode="original"> + <span class="text"> + <t:call-template name="quote"> + <t:with-param name="text" select="." /> + </t:call-template> + </span> + </t:template> -</stylesheet> +</t:stylesheet> diff --git a/view-source.xsl b/view-source.xsl index fdedc88..434310c 100644 --- a/view-source.xsl +++ b/view-source.xsl @@ -1,52 +1,59 @@ <?xml version="1.0" ?> <?xslt-param name="format" select="false()" ?> <?xml-stylesheet type="text/xsl" href="view-source.xsl" filename="view-source.xsl" ?> -<stylesheet version="1.0" - xmlns="http://www.w3.org/1999/XSL/Transform" - xmlns:h="http://www.w3.org/1999/xhtml"> - - <param name="base-indent" select="' '" /> - - <param name="format" select="true()" /> - - <param name="style" select="'minimal'" /> - - <param name="add-behaviour" select="true()" /> - - <param name="highlight-namespace" select="$ns.empty" /> - - <include href="formatted.xsl" /> - - <include href="original.xsl" /> - - <include href="library.xsl" /> - - <template match="/"> - <h:html> - <h:head> - <h:title>XML Source</h:title> - <h:style type="text/css"> - <value-of select="document(concat($style, '.css'))/css" /> - </h:style> - </h:head> - <h:body> - <h:pre id="source"> - <choose> - <when test="$format"> - <apply-templates mode="formatted" /> - </when> - <otherwise> - <apply-templates mode="original" /> - </otherwise> - </choose> - </h:pre> - <if test="$add-behaviour"> - <h:script type="text/javascript"> - <value-of select="document('behaviour.js')/js" /> - </h:script> - </if> - </h:body> - </h:html> - </template> - -</stylesheet> +<t:stylesheet version="1.0" + xmlns:t="http://www.w3.org/1999/XSL/Transform" + xmlns="http://www.w3.org/1999/xhtml"> + + <t:param name="base-indent" select="' '" /> + + <t:param name="format" select="true()" /> + + <t:param name="style" select="'minimal'" /> + + <t:param name="add-behaviour" select="true()" /> + + <t:param name="highlight-namespace" select="''" /> + + <t:include href="formatted.xsl" /> + + <t:include href="original.xsl" /> + + <t:include href="library.xsl" /> + + <t:output method="xml" indent="yes" + omit-xml-declaration="yes" + doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" + doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" + /> + + <t:template match="/"> + <html> + <head> + <title>XML Source</title> + <style type="text/css"> + <t:value-of select="document(concat($style, '.css'))/css" /> + </style> + </head> + <body> + <pre id="source"> + <t:choose> + <t:when test="$format"> + <t:apply-templates mode="formatted" /> + </t:when> + <t:otherwise> + <t:apply-templates mode="original" /> + </t:otherwise> + </t:choose> + </pre> + <t:if test="$add-behaviour"> + <t:call-template name="get-namespace-nodes" /> + <script type="text/javascript"> + <t:value-of select="document('behaviour.js')/js" /> + </script> + </t:if> + </body> + </html> + </t:template> + +</t:stylesheet>
Boldewyn/view-source
081d5a78db3ce8f97179a6821d2c498ecb559301
s/mml/mathml/g
diff --git a/library.xsl b/library.xsl index 1d05689..f0222b6 100644 --- a/library.xsl +++ b/library.xsl @@ -1,187 +1,187 @@ <?xml version="1.0" ?> <stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:h="http://www.w3.org/1999/xhtml"> <variable select="''" name="ns.empty" /> <variable select="'http://www.w3.org/XML/1998/namespace'" name="ns.xml" /> <variable select="'http://www.w3.org/2000/xmlns/'" name="ns.xmlns" /> <variable select="'http://www.w3.org/1999/XSL/Transform'" name="ns.xslt" /> <variable select="'http://www.w3.org/1999/xhtml'" name="ns.xhtml" /> <variable select="'http://www.w3.org/2000/svg'" name="ns.svg" /> - <variable select="'http://www.w3.org/1998/Math/MathML'" name="ns.mml" /> + <variable select="'http://www.w3.org/1998/Math/MathML'" name="ns.mathml" /> <variable select="'http://www.w3.org/2005/SMIL21/Language'" name="ns.smil" /> <variable select="'http://www.w3.org/1999/XSL/Format'" name="ns.fo" /> <variable select="'http://www.w3.org/1999/xlink'" name="ns.xlink" /> <variable select="'http://www.w3.org/2001/XMLSchema'" name="ns.xsd" /> <variable select="'http://www.w3.org/2001/XMLSchema-instance'" name="ns.xsd-inst" /> <variable select="'http://www.w3.org/2001/xforms'" name="ns.xforms" /> <!-- def format-text --> <template name="format-text"> <param name="text" select="." /> <param name="indent" /> <choose> <when test="contains($text, '&#xA;')"> <value-of select="normalize-space(substring-before($text, '&#xA;'))" /> <text>&#xA;</text> <value-of select="$indent" /> <call-template name="format-text"> <with-param name="text" select="substring-after($text, '&#xA;')" /> <with-param name="indent" select="$indent " /> </call-template> </when> <otherwise> <value-of select="normalize-space($text)" /> </otherwise> </choose> </template> <!-- def quote --> <template name="quote"> <param name="text" /> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <value-of select="$text" /> </with-param> <with-param name="from" select="'&amp;'" /> <with-param name="to" select="'&amp;amp;'" /> </call-template> </with-param> <with-param name="from" select='"&apos;"' /> <with-param name="to" select="'&amp;apos;'" /> </call-template> </with-param> <with-param name="from" select="'&quot;'" /> <with-param name="to" select="'&amp;quot;'" /> </call-template> </with-param> <with-param name="from" select="'&gt;'" /> <with-param name="to" select="'&amp;gt;'" /> </call-template> </with-param> <with-param name="from" select="'&lt;'" /> <with-param name="to" select="'&amp;lt;'" /> </call-template> </template> <!-- def replace --> <template name="replace"> <param name="text" /> <param name="from" /> <param name="to" /> <choose> <when test="not($from)"> <value-of select="$text" /> </when> <when test="contains($text, $from)"> <value-of select="substring-before($text, $from)" /> <value-of select="$to" /> <call-template name="replace"> <with-param name="text" select="substring-after($text, $from)" /> <with-param name="from" select="$from" /> <with-param name="to" select="$to" /> </call-template> </when> <otherwise> <value-of select="$text" /> </otherwise> </choose> </template> <!-- def parse_attval --> <template name="parse-attval"> <param name="att" select="." /> <choose> <when test="(namespace-uri($att/..) = $ns.xml and ( local-name($att) = 'base' )) or (namespace-uri($att/..) = $ns.xhtml and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att/..) = $ns.svg and ( local-name($att) = 'src' )) or (namespace-uri($att/..) = $ns.xslt and ( local-name($att) = 'href' )) or (namespace-uri($att/..) = $ns.smil and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att) = $ns.xlink and ( local-name($att) = 'href' or local-name($att) = 'role' )) or contains(substring($att, 1, 7), 'http://') or contains(substring($att, 1, 8), 'https://') or contains(substring($att, 1, 7), 'file://') or contains(substring($att, 1, 7), 'mailto:') or contains(substring($att, 1, 6), 'ftp://') or contains(substring($att, 1, 7), 'ftps://') or contains(substring($att, 1, 5), 'news:') or contains(substring($att, 1, 4), 'urn:') or contains(substring($att, 1, 5), 'ldap:') or contains(substring($att, 1, 5), 'data:')"> <h:a> <attribute name="href"> <value-of select="$att" /> </attribute> <call-template name="quote"> <with-param name="text" select="$att" /> </call-template> </h:a> </when> <otherwise> <call-template name="quote"> <with-param name="text" select="$att" /> </call-template> </otherwise> </choose> </template> <!-- def detect-lang --> <template name="detect-lang"> <param name="node" select="." /> <if test="namespace-uri($node) = $highlight-namespace"> <text>highlight </text> </if> <choose> <when test="namespace-uri($node) = $ns.empty"> <text>empty-ns</text> </when> <when test="namespace-uri($node) = $ns.xml"> <text>xml</text> </when> <when test="namespace-uri($node) = $ns.xmlns"> <text>xmlns</text> </when> <when test="namespace-uri($node) = $ns.xhtml"> <text>xhtml</text> </when> <when test="namespace-uri($node) = $ns.svg"> <text>svg</text> </when> <when test="namespace-uri($node) = $ns.xlink"> <text>xlink</text> </when> <when test="namespace-uri($node) = $ns.xslt"> <text>xslt</text> </when> <when test="namespace-uri($node) = $ns.fo"> <text>fo</text> </when> - <when test="namespace-uri($node) = $ns.mml"> + <when test="namespace-uri($node) = $ns.mathml"> <text>mathml</text> </when> <when test="namespace-uri($node) = $ns.xsd"> <text>xsd</text> </when> <when test="namespace-uri($node) = $ns.xsd-inst"> <text>xsd-inst</text> </when> <when test="namespace-uri($node) = $ns.smil"> <text>smil</text> </when> <when test="namespace-uri($node) = $ns.xforms"> <text>xforms</text> </when> <otherwise /> </choose> </template> </stylesheet>
Boldewyn/view-source
84c1dbc158555e623445e04c71b83e53a2493679
made behaviour switchable, moved variables to library.xsl
diff --git a/behaviour.js b/behaviour.js index 4307cdc..8645303 100644 --- a/behaviour.js +++ b/behaviour.js @@ -1,10 +1,8 @@ <js> -window.onload = function () { - var els = []; //document.getElementsByClassNames('element'); - for (var el in els) { - el.onclick = function () { - alert(el.getAttribute('class')); - }; - } -}; +var els = document.getElementsByClassName('element'); +for (var el in els) { + els[el].onclick = (function (a) { return function () { + //alert(a); + }; })(els[el].getAttribute('class')); +} </js> diff --git a/library.xsl b/library.xsl index 393001a..1d05689 100644 --- a/library.xsl +++ b/library.xsl @@ -1,173 +1,187 @@ <?xml version="1.0" ?> <stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:h="http://www.w3.org/1999/xhtml"> + <variable select="''" name="ns.empty" /> + <variable select="'http://www.w3.org/XML/1998/namespace'" name="ns.xml" /> + <variable select="'http://www.w3.org/2000/xmlns/'" name="ns.xmlns" /> + <variable select="'http://www.w3.org/1999/XSL/Transform'" name="ns.xslt" /> + <variable select="'http://www.w3.org/1999/xhtml'" name="ns.xhtml" /> + <variable select="'http://www.w3.org/2000/svg'" name="ns.svg" /> + <variable select="'http://www.w3.org/1998/Math/MathML'" name="ns.mml" /> + <variable select="'http://www.w3.org/2005/SMIL21/Language'" name="ns.smil" /> + <variable select="'http://www.w3.org/1999/XSL/Format'" name="ns.fo" /> + <variable select="'http://www.w3.org/1999/xlink'" name="ns.xlink" /> + <variable select="'http://www.w3.org/2001/XMLSchema'" name="ns.xsd" /> + <variable select="'http://www.w3.org/2001/XMLSchema-instance'" name="ns.xsd-inst" /> + <variable select="'http://www.w3.org/2001/xforms'" name="ns.xforms" /> + <!-- def format-text --> <template name="format-text"> <param name="text" select="." /> <param name="indent" /> <choose> <when test="contains($text, '&#xA;')"> <value-of select="normalize-space(substring-before($text, '&#xA;'))" /> <text>&#xA;</text> <value-of select="$indent" /> <call-template name="format-text"> <with-param name="text" select="substring-after($text, '&#xA;')" /> <with-param name="indent" select="$indent " /> </call-template> </when> <otherwise> <value-of select="normalize-space($text)" /> </otherwise> </choose> </template> <!-- def quote --> <template name="quote"> <param name="text" /> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <value-of select="$text" /> </with-param> <with-param name="from" select="'&amp;'" /> <with-param name="to" select="'&amp;amp;'" /> </call-template> </with-param> <with-param name="from" select='"&apos;"' /> <with-param name="to" select="'&amp;apos;'" /> </call-template> </with-param> <with-param name="from" select="'&quot;'" /> <with-param name="to" select="'&amp;quot;'" /> </call-template> </with-param> <with-param name="from" select="'&gt;'" /> <with-param name="to" select="'&amp;gt;'" /> </call-template> </with-param> <with-param name="from" select="'&lt;'" /> <with-param name="to" select="'&amp;lt;'" /> </call-template> </template> <!-- def replace --> <template name="replace"> <param name="text" /> <param name="from" /> <param name="to" /> <choose> <when test="not($from)"> <value-of select="$text" /> </when> <when test="contains($text, $from)"> <value-of select="substring-before($text, $from)" /> <value-of select="$to" /> <call-template name="replace"> <with-param name="text" select="substring-after($text, $from)" /> <with-param name="from" select="$from" /> <with-param name="to" select="$to" /> </call-template> </when> <otherwise> <value-of select="$text" /> </otherwise> </choose> </template> <!-- def parse_attval --> <template name="parse-attval"> <param name="att" select="." /> <choose> <when test="(namespace-uri($att/..) = $ns.xml and ( local-name($att) = 'base' )) or (namespace-uri($att/..) = $ns.xhtml and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att/..) = $ns.svg and ( local-name($att) = 'src' )) or (namespace-uri($att/..) = $ns.xslt and ( local-name($att) = 'href' )) or (namespace-uri($att/..) = $ns.smil and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att) = $ns.xlink and ( local-name($att) = 'href' or local-name($att) = 'role' )) or contains(substring($att, 1, 7), 'http://') or contains(substring($att, 1, 8), 'https://') or contains(substring($att, 1, 7), 'file://') or contains(substring($att, 1, 7), 'mailto:') or contains(substring($att, 1, 6), 'ftp://') or contains(substring($att, 1, 7), 'ftps://') or contains(substring($att, 1, 5), 'news:') or contains(substring($att, 1, 4), 'urn:') or contains(substring($att, 1, 5), 'ldap:') or contains(substring($att, 1, 5), 'data:')"> <h:a> <attribute name="href"> <value-of select="$att" /> </attribute> <call-template name="quote"> <with-param name="text" select="$att" /> </call-template> </h:a> </when> <otherwise> <call-template name="quote"> <with-param name="text" select="$att" /> </call-template> </otherwise> </choose> </template> <!-- def detect-lang --> <template name="detect-lang"> <param name="node" select="." /> <if test="namespace-uri($node) = $highlight-namespace"> <text>highlight </text> </if> <choose> <when test="namespace-uri($node) = $ns.empty"> <text>empty-ns</text> </when> <when test="namespace-uri($node) = $ns.xml"> <text>xml</text> </when> <when test="namespace-uri($node) = $ns.xmlns"> <text>xmlns</text> </when> <when test="namespace-uri($node) = $ns.xhtml"> <text>xhtml</text> </when> <when test="namespace-uri($node) = $ns.svg"> <text>svg</text> </when> <when test="namespace-uri($node) = $ns.xlink"> <text>xlink</text> </when> <when test="namespace-uri($node) = $ns.xslt"> <text>xslt</text> </when> <when test="namespace-uri($node) = $ns.fo"> <text>fo</text> </when> <when test="namespace-uri($node) = $ns.mml"> <text>mathml</text> </when> <when test="namespace-uri($node) = $ns.xsd"> <text>xsd</text> </when> <when test="namespace-uri($node) = $ns.xsd-inst"> <text>xsd-inst</text> </when> <when test="namespace-uri($node) = $ns.smil"> <text>smil</text> </when> <when test="namespace-uri($node) = $ns.xforms"> <text>xforms</text> </when> <otherwise /> </choose> </template> </stylesheet> diff --git a/view-source.xsl b/view-source.xsl index 2585875..fdedc88 100644 --- a/view-source.xsl +++ b/view-source.xsl @@ -1,62 +1,52 @@ <?xml version="1.0" ?> <?xslt-param name="format" select="false()" ?> <?xml-stylesheet type="text/xsl" href="view-source.xsl" filename="view-source.xsl" ?> <stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:h="http://www.w3.org/1999/xhtml"> <param name="base-indent" select="' '" /> <param name="format" select="true()" /> <param name="style" select="'minimal'" /> + <param name="add-behaviour" select="true()" /> + <param name="highlight-namespace" select="$ns.empty" /> <include href="formatted.xsl" /> <include href="original.xsl" /> <include href="library.xsl" /> - <variable select="''" name="ns.empty" /> - <variable select="'http://www.w3.org/XML/1998/namespace'" name="ns.xml" /> - <variable select="'http://www.w3.org/2000/xmlns/'" name="ns.xmlns" /> - <variable select="'http://www.w3.org/1999/XSL/Transform'" name="ns.xslt" /> - <variable select="'http://www.w3.org/1999/xhtml'" name="ns.xhtml" /> - <variable select="'http://www.w3.org/2000/svg'" name="ns.svg" /> - <variable select="'http://www.w3.org/1998/Math/MathML'" name="ns.mml" /> - <variable select="'http://www.w3.org/2005/SMIL21/Language'" name="ns.smil" /> - <variable select="'http://www.w3.org/1999/XSL/Format'" name="ns.fo" /> - <variable select="'http://www.w3.org/1999/xlink'" name="ns.xlink" /> - <variable select="'http://www.w3.org/2001/XMLSchema'" name="ns.xsd" /> - <variable select="'http://www.w3.org/2001/XMLSchema-instance'" name="ns.xsd-inst" /> - <variable select="'http://www.w3.org/2001/xforms'" name="ns.xforms" /> - <template match="/"> <h:html> <h:head> <h:title>XML Source</h:title> <h:style type="text/css"> <value-of select="document(concat($style, '.css'))/css" /> </h:style> - <h:script type="text/javascript"> - <value-of select="document('behaviour.js')/js" /> - </h:script> </h:head> <h:body> <h:pre id="source"> <choose> <when test="$format"> <apply-templates mode="formatted" /> </when> <otherwise> <apply-templates mode="original" /> </otherwise> </choose> </h:pre> + <if test="$add-behaviour"> + <h:script type="text/javascript"> + <value-of select="document('behaviour.js')/js" /> + </h:script> + </if> </h:body> </h:html> </template> </stylesheet>
Boldewyn/view-source
f40bf4ce1a72b462f68eccf52e7556dd4ccd141a
Changes in the XSLT stylesheets to discriminate nodes from different namespaces.
diff --git a/formatted.xsl b/formatted.xsl index 0e6283c..19dbf91 100644 --- a/formatted.xsl +++ b/formatted.xsl @@ -1,109 +1,115 @@ <?xml version="1.0" ?> <stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:h="http://www.w3.org/1999/xhtml"> <!-- Elements (formatted) --> <template match="*" mode="formatted"> <param name="indent" /> + <variable name="lang"> + <call-template name="detect-lang" /> + </variable> <value-of select="$indent" /> <choose> <when test="node()"> - <h:span class="element"> + <h:span class="{$lang} element"> <h:span class="tag start"> <text>&lt;</text> <value-of select="name(.)" /> <for-each select="@*"> <apply-templates select="." mode="formatted" /> </for-each> <text>&gt;</text> </h:span> <text>&#x0A;</text> <apply-templates mode="formatted"> <with-param name="indent" select="concat($indent, $base-indent)" /> </apply-templates> <value-of select="$indent" /> <h:span class="tag end"> <text>&lt;/</text> <value-of select="name(.)"/> <text>&gt;</text> </h:span> </h:span> </when> <otherwise> - <h:span class="element empty"> + <h:span class="{$lang} element empty"> <h:span class="tag empty"> <text>&lt;</text> <value-of select="name(.)" /> <for-each select="@*"> <apply-templates select="." mode="formatted" /> </for-each> <text> /&gt;</text> </h:span> </h:span> </otherwise> </choose> <text>&#xA;</text> </template> <!-- Attributes (formatted) --> <template match="@*" mode="formatted"> + <variable name="lang"> + <call-template name="detect-lang" /> + </variable> <text> </text> - <h:span class="attribute"> + <h:span class="{$lang} attribute"> <value-of select="name()" /> <text>="</text> <h:span class="attribute-value"> <call-template name="parse-attval" /> </h:span> <text>"</text> </h:span> </template> <!-- Processing Instructions (formatted) --> <template match="processing-instruction()" mode="formatted"> <param name="indent" /> <value-of select="$indent" /> <h:span class="processing-instruction"> <text>&lt;?</text> <value-of select="name(.)" /> <text> </text> <call-template name="format-text"> <with-param name="text" select="." /> <with-param name="indent" select="$indent" /> </call-template> <text>?&gt;</text> </h:span> <text>&#xA;</text> </template> <!-- Comments (formatted) --> <template match="comment()" mode="formatted"> <param name="indent" /> <value-of select="$indent" /> <h:span class="comment"> <text>&lt;!--</text> <call-template name="format-text"> <with-param name="text" select="." /> <with-param name="indent" select="$indent" /> </call-template> <text>--></text> </h:span> <text>&#xA;</text> </template> <!-- Text (formatted) --> <template match="text()" mode="formatted"> <param name="indent" /> <if test="normalize-space()"> <value-of select="$indent" /> <h:span class="text"> <call-template name="format-text"> <with-param name="text" select="." /> <with-param name="indent" select="$indent" /> </call-template> </h:span> <text>&#xA;</text> </if> </template> </stylesheet> diff --git a/library.xsl b/library.xsl index 79f6349..393001a 100644 --- a/library.xsl +++ b/library.xsl @@ -1,123 +1,173 @@ <?xml version="1.0" ?> <stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:h="http://www.w3.org/1999/xhtml"> <!-- def format-text --> <template name="format-text"> <param name="text" select="." /> <param name="indent" /> <choose> <when test="contains($text, '&#xA;')"> <value-of select="normalize-space(substring-before($text, '&#xA;'))" /> <text>&#xA;</text> <value-of select="$indent" /> <call-template name="format-text"> <with-param name="text" select="substring-after($text, '&#xA;')" /> <with-param name="indent" select="$indent " /> </call-template> </when> <otherwise> <value-of select="normalize-space($text)" /> </otherwise> </choose> </template> <!-- def quote --> <template name="quote"> <param name="text" /> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <call-template name="replace"> <with-param name="text"> <value-of select="$text" /> </with-param> <with-param name="from" select="'&amp;'" /> <with-param name="to" select="'&amp;amp;'" /> </call-template> </with-param> <with-param name="from" select='"&apos;"' /> <with-param name="to" select="'&amp;apos;'" /> </call-template> </with-param> <with-param name="from" select="'&quot;'" /> <with-param name="to" select="'&amp;quot;'" /> </call-template> </with-param> <with-param name="from" select="'&gt;'" /> <with-param name="to" select="'&amp;gt;'" /> </call-template> </with-param> <with-param name="from" select="'&lt;'" /> <with-param name="to" select="'&amp;lt;'" /> </call-template> </template> <!-- def replace --> <template name="replace"> <param name="text" /> <param name="from" /> <param name="to" /> <choose> <when test="not($from)"> <value-of select="$text" /> </when> <when test="contains($text, $from)"> <value-of select="substring-before($text, $from)" /> <value-of select="$to" /> <call-template name="replace"> <with-param name="text" select="substring-after($text, $from)" /> <with-param name="from" select="$from" /> <with-param name="to" select="$to" /> </call-template> </when> <otherwise> <value-of select="$text" /> </otherwise> </choose> </template> <!-- def parse_attval --> <template name="parse-attval"> <param name="att" select="." /> <choose> <when test="(namespace-uri($att/..) = $ns.xml and ( local-name($att) = 'base' )) or (namespace-uri($att/..) = $ns.xhtml and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att/..) = $ns.svg and ( local-name($att) = 'src' )) or (namespace-uri($att/..) = $ns.xslt and ( local-name($att) = 'href' )) or (namespace-uri($att/..) = $ns.smil and ( local-name($att) = 'src' or local-name($att) = 'href' )) or (namespace-uri($att) = $ns.xlink and ( local-name($att) = 'href' or local-name($att) = 'role' )) or contains(substring($att, 1, 7), 'http://') or contains(substring($att, 1, 8), 'https://') or contains(substring($att, 1, 7), 'file://') or contains(substring($att, 1, 7), 'mailto:') or contains(substring($att, 1, 6), 'ftp://') or contains(substring($att, 1, 7), 'ftps://') or contains(substring($att, 1, 5), 'news:') or contains(substring($att, 1, 4), 'urn:') or contains(substring($att, 1, 5), 'ldap:') or contains(substring($att, 1, 5), 'data:')"> <h:a> <attribute name="href"> <value-of select="$att" /> </attribute> <call-template name="quote"> <with-param name="text" select="$att" /> </call-template> </h:a> </when> <otherwise> <call-template name="quote"> <with-param name="text" select="$att" /> </call-template> </otherwise> </choose> </template> + <!-- def detect-lang --> + <template name="detect-lang"> + <param name="node" select="." /> + <if test="namespace-uri($node) = $highlight-namespace"> + <text>highlight </text> + </if> + <choose> + <when test="namespace-uri($node) = $ns.empty"> + <text>empty-ns</text> + </when> + <when test="namespace-uri($node) = $ns.xml"> + <text>xml</text> + </when> + <when test="namespace-uri($node) = $ns.xmlns"> + <text>xmlns</text> + </when> + <when test="namespace-uri($node) = $ns.xhtml"> + <text>xhtml</text> + </when> + <when test="namespace-uri($node) = $ns.svg"> + <text>svg</text> + </when> + <when test="namespace-uri($node) = $ns.xlink"> + <text>xlink</text> + </when> + <when test="namespace-uri($node) = $ns.xslt"> + <text>xslt</text> + </when> + <when test="namespace-uri($node) = $ns.fo"> + <text>fo</text> + </when> + <when test="namespace-uri($node) = $ns.mml"> + <text>mathml</text> + </when> + <when test="namespace-uri($node) = $ns.xsd"> + <text>xsd</text> + </when> + <when test="namespace-uri($node) = $ns.xsd-inst"> + <text>xsd-inst</text> + </when> + <when test="namespace-uri($node) = $ns.smil"> + <text>smil</text> + </when> + <when test="namespace-uri($node) = $ns.xforms"> + <text>xforms</text> + </when> + <otherwise /> + </choose> + </template> + </stylesheet> diff --git a/original.xsl b/original.xsl index 7775381..440aad4 100644 --- a/original.xsl +++ b/original.xsl @@ -1,86 +1,92 @@ <?xml version="1.0" ?> <stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:h="http://www.w3.org/1999/xhtml"> <!-- Elements (original) --> <template match="*" mode="original"> + <variable name="lang"> + <call-template name="detect-lang" /> + </variable> <choose> <when test="node()"> - <h:span class="element"> + <h:span class="{$lang} element"> <h:span class="tag start"> <text>&lt;</text> <value-of select="name(.)" /> <for-each select="@*"> <apply-templates select="." mode="original" /> </for-each> <text>&gt;</text> </h:span> <apply-templates mode="original" /> <h:span class="tag end"> <text>&lt;/</text> <value-of select="name(.)"/> <text>&gt;</text> </h:span> </h:span> </when> <otherwise> - <h:span class="element empty"> + <h:span class="{$lang} element empty"> <h:span class="tag empty"> <text>&lt;</text> <value-of select="name(.)" /> <for-each select="@*"> <apply-templates select="." mode="original" /> </for-each> <text> /&gt;</text> </h:span> </h:span> </otherwise> </choose> </template> <!-- Attributes (original) --> <template match="@*" mode="original"> + <variable name="lang"> + <call-template name="detect-lang" /> + </variable> <text> </text> - <h:span class="attribute"> + <h:span class="{$lang} attribute"> <value-of select="name()" /> <text>="</text> <h:span class="attribute-value"> <call-template name="parse-attval" /> </h:span> <text>"</text> </h:span> </template> <!-- Processing Instructions (original) --> <template match="processing-instruction()" mode="original"> <h:span class="processing-instruction"> <text>&lt;?</text> <value-of select="name(.)" /> <text> </text> <value-of select="." /> <text>?&gt;</text> </h:span> </template> <!-- Comments (original) --> <template match="comment()" mode="original"> <h:span class="comment"> <text>&lt;!--</text> <call-template name="quote"> <with-param name="text" select="." /> </call-template> <text>--></text> </h:span> </template> <!-- Text (original) --> <template match="text()" mode="original"> <h:span class="text"> <call-template name="quote"> <with-param name="text" select="." /> </call-template> </h:span> </template> </stylesheet> diff --git a/view-source.xsl b/view-source.xsl index 0effa3b..2585875 100644 --- a/view-source.xsl +++ b/view-source.xsl @@ -1,56 +1,62 @@ <?xml version="1.0" ?> <?xslt-param name="format" select="false()" ?> <?xml-stylesheet type="text/xsl" href="view-source.xsl" filename="view-source.xsl" ?> <stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:h="http://www.w3.org/1999/xhtml"> <param name="base-indent" select="' '" /> <param name="format" select="true()" /> <param name="style" select="'minimal'" /> + <param name="highlight-namespace" select="$ns.empty" /> + <include href="formatted.xsl" /> <include href="original.xsl" /> <include href="library.xsl" /> + <variable select="''" name="ns.empty" /> <variable select="'http://www.w3.org/XML/1998/namespace'" name="ns.xml" /> <variable select="'http://www.w3.org/2000/xmlns/'" name="ns.xmlns" /> <variable select="'http://www.w3.org/1999/XSL/Transform'" name="ns.xslt" /> <variable select="'http://www.w3.org/1999/xhtml'" name="ns.xhtml" /> <variable select="'http://www.w3.org/2000/svg'" name="ns.svg" /> <variable select="'http://www.w3.org/1998/Math/MathML'" name="ns.mml" /> <variable select="'http://www.w3.org/2005/SMIL21/Language'" name="ns.smil" /> <variable select="'http://www.w3.org/1999/XSL/Format'" name="ns.fo" /> <variable select="'http://www.w3.org/1999/xlink'" name="ns.xlink" /> <variable select="'http://www.w3.org/2001/XMLSchema'" name="ns.xsd" /> <variable select="'http://www.w3.org/2001/XMLSchema-instance'" name="ns.xsd-inst" /> <variable select="'http://www.w3.org/2001/xforms'" name="ns.xforms" /> <template match="/"> <h:html> <h:head> <h:title>XML Source</h:title> <h:style type="text/css"> <value-of select="document(concat($style, '.css'))/css" /> </h:style> + <h:script type="text/javascript"> + <value-of select="document('behaviour.js')/js" /> + </h:script> </h:head> <h:body> <h:pre id="source"> <choose> <when test="$format"> <apply-templates mode="formatted" /> </when> <otherwise> <apply-templates mode="original" /> </otherwise> </choose> </h:pre> </h:body> </h:html> </template> </stylesheet>
Boldewyn/view-source
5c49d00803f48af80eace88a0b02ab65d786f12b
Added discrimination of nodes from some popular namespaces
diff --git a/behaviour.js b/behaviour.js new file mode 100644 index 0000000..4307cdc --- /dev/null +++ b/behaviour.js @@ -0,0 +1,10 @@ +<js> +window.onload = function () { + var els = []; //document.getElementsByClassNames('element'); + for (var el in els) { + el.onclick = function () { + alert(el.getAttribute('class')); + }; + } +}; +</js>
neco/twitter.neco.com
29f9a5414093106d5085d127b2868efb1b64c9a7
Add newrelic
diff --git a/.gitignore b/.gitignore index e207a04..61af07a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,9 @@ *.sqlite3 db/schema.rb config/database.yml -config/locomotive.yml -config/mongrel_cluster.yml config/thin.yml tmp/* log/* private/images/* public/cache/* .DS_Store diff --git a/config/deploy.rb b/config/deploy.rb index 468bd85..a2bbabc 100644 --- a/config/deploy.rb +++ b/config/deploy.rb @@ -1,57 +1,61 @@ +require 'new_relic/recipes' + default_run_options[:pty] = true set :application, "twitter.neco.com" set :repository, "[email protected]:binarylogic/twitter.neco.com.git" set :keep_releases, 5 set :scm, :git set :deploy_via, :remote_cache # prevent git from cloning on every deploy set :deploy_to, "/var/www/#{application}" set :branch, "master" set :thin_conf, "#{current_path}/config/thin.yml" # must be set after :deploy_to is set set :user, 'root' set :runner, 'root' set :use_sudo, false role :app, "server2.neco.com" role :web, "server2.neco.com" role :bdrb, "server2.neco.com" role :db, "server2.neco.com", :primary => true +after "deploy:update", "newrelic:notice_deployment" + task :after_update_code do # handle shared files %w{/config/database.yml /config/thin.yml}.each do |file| run "ln -nfs #{shared_path}#{file} #{release_path}#{file}" end deploy.cleanup end namespace :deploy do namespace :thin do [ :stop, :start, :restart ].each do |t| desc "#{t.to_s.capitalize} the thin servers" task t, :roles => :app do #invoke_command checks the use_sudo variable to determine how to run the thin command invoke_command "thin #{t.to_s} -C #{thin_conf}", :via => run_method end end end desc "Custom restart task for thin cluster" task :restart, :roles => :app, :except => { :no_release => true } do deploy.thin.restart end desc "Custom start task for thin cluster" task :start, :roles => :app do deploy.thin.start end desc "Custom stop task for thin cluster" task :stop, :roles => :app do deploy.thin.stop end end \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb index 6029211..aebb9e7 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,78 +1,79 @@ # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present #RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" + config.gem "newrelic_rpm" config.gem "searchlogic" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. config.time_zone = 'Eastern Time (US & Canada)' # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_twitter.neco.com_session', :secret => '62915b30a5d1b1123c3f42f3cde9af8c3d7212c46985d7e7050a710be8d1599132b2882ae19f64fead80f8f789c4b9d4a545a55699951453fb6b75e98e27eca6' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end diff --git a/config/newrelic.yml b/config/newrelic.yml new file mode 100644 index 0000000..802acbc --- /dev/null +++ b/config/newrelic.yml @@ -0,0 +1,138 @@ +# +# This file configures the NewRelic RPM Agent, NewRelic RPM monitors Rails +# applications with deep visibility and low overhead. For more information, +# visit www.newrelic.com. +# +# This configuration file is custom generated for neco +# +# here are the settings that are common to all environments +common: &default_settings + # ============================== LICENSE KEY =============================== + # You must specify the licence key associated with your New Relic account. + # This key binds your Agent's data to your account in the New Relic RPM service. + license_key: '9238c4341057df79d50e30ae3d63134a19d71d2f' + + # Application Name + # Set this to be the name of your application as you'd like it show up in RPM. + # RPM will then auto-map instances of your application into a RPM "application" + # on your home dashboard page. This setting does not prevent you from manually + # defining applications. + app_name: twitter.neco.com + + # the 'enabled' setting is used to turn on the NewRelic Agent. When false, + # your application is not instrumented and the Agent does not start up or + # collect any data; it is a complete shut-off. + # + # when turned on, the agent collects performance data by inserting lightweight + # tracers on key methods inside the rails framework and asynchronously aggregating + # and reporting this performance data to the NewRelic RPM service at NewRelic.com. + # below. + enabled: false + + # The newrelic agent generates its own log file to keep its logging information + # separate from that of your application. Specify its log level here. + log_level: info + + # The newrelic agent communicates with the RPM service via http by default. + # If you want to communicate via https to increase security, then turn on + # SSL by setting this value to true. Note, this will result in increased + # CPU overhead to perform the encryption involved in SSL communication, but this + # work is done asynchronously to the threads that process your application code, so + # it should not impact response times. + ssl: false + + + # Proxy settings for connecting to the RPM server. + # + # If a proxy is used, the host setting is required. Other settings are optional. Default + # port is 8080. + # + # proxy_host: proxy.sample.com + # proxy_port: 8080 + # proxy_user: + # proxy_pass: + + + # Tells transaction tracer and error collector (when enabled) whether or not to capture HTTP params. + # When true, the RoR filter_parameters mechanism is used so that sensitive parameters are not recorded + capture_params: true + + + # Transaction tracer captures deep information about slow + # transactions and sends this to the RPM service once a minute. Included in the + # transaction is the exact call sequence of the transactions including any SQL statements + # issued. + transaction_tracer: + + # Transaction tracer is enabled by default. Set this to false to turn it off. This feature + # is only available at the Silver and above product levels. + enabled: true + + + # When transaction tracer is on, SQL statements can optionally be recorded. The recorder + # has three modes, "off" which sends no SQL, "raw" which sends the SQL statement in its + # original form, and "obfuscated", which strips out numeric and string literals + record_sql: obfuscated + + # Threshold in seconds for when to collect stack trace for a SQL call. In other words, + # when SQL statements exceed this threshold, then capture and send to RPM the current + # stack trace. This is helpful for pinpointing where long SQL calls originate from + stack_trace_threshold: 0.500 + + # Error collector captures information about uncaught exceptions and sends them to RPM for + # viewing + error_collector: + + # Error collector is enabled by default. Set this to false to turn it off. This feature + # is only available at the Silver and above product levels + enabled: true + + # Tells error collector whether or not to capture a source snippet around the place of the + # error when errors are View related. + capture_source: true + + # To stop specific errors from reporting to RPM, set this property to comma separated + # values + # + #ignore_errors: ActionController::RoutingError, ... + + +# override default settings based on your application's environment + +# NOTE if your application has other named environments, you should +# provide newrelic conifguration settings for these enviromnents here. + +development: + <<: *default_settings + # turn off communication to RPM service in development mode. + # NOTE: for initial evaluation purposes, you may want to temporarily turn + # the agent on in development mode. + enabled: false + + # When running in Developer Mode, the New Relic Agent will present + # performance information on the last 100 transactions you have + # executed since starting the mongrel. to view this data, go to + # http://localhost:3000/newrelic + developer: true + +test: + <<: *default_settings + # it almost never makes sense to turn on the agent when running unit, functional or + # integration tests or the like. + enabled: false + +# Turn on the agent in production for 24x7 monitoring. NewRelic testing shows +# an average performance impact of < 5 ms per transaction, you you can leave this on +# all the time without incurring any user-visible performance degredation. +production: + <<: *default_settings + enabled: true + +# many applications have a staging environment which behaves identically to production. +# Support for that environment is provided here. By default, the staging environment has +# the agent turned on. +staging: + <<: *default_settings + enabled: true + license_key: d294b0b2794a74eff2b60bbc3e9926abf31cbe89 + app_name: twitter.neco.com (staging)
neco/twitter.neco.com
b198379d60f0fcab615150d1e195e33d0c890eb0
dont show image when url doesnt exist
diff --git a/app/views/tweets/_tweet.html.haml b/app/views/tweets/_tweet.html.haml index 3fadec9..a2e8484 100644 --- a/app/views/tweets/_tweet.html.haml +++ b/app/views/tweets/_tweet.html.haml @@ -1,7 +1,7 @@ %div{:class => "tweet#{' first' if tweet_counter == 0}"} - = link_to image_tag(tweet.twitter_user.profile_image_url, :class => 'user_image'), profile_path(:screen_name => tweet.twitter_user.screen_name) if tweet.twitter_user + = link_to image_tag(tweet.twitter_user.profile_image_url, :class => 'user_image'), profile_path(:screen_name => tweet.twitter_user.screen_name) if tweet.twitter_user.profile_image_url .content .text= parse_tweet(tweet.tweet_text) .details - = link_to tweet.twitter_user.screen_name, profile_path(:screen_name => tweet.twitter_user.screen_name) if tweet.twitter_user + = link_to tweet.twitter_user.screen_name, profile_path(:screen_name => tweet.twitter_user.screen_name) = tweet.tweeted_at.strftime('%l:%M %p Eastern - %a %D') \ No newline at end of file diff --git a/app/views/twitter_users/show.html.haml b/app/views/twitter_users/show.html.haml index cf2d356..9090785 100644 --- a/app/views/twitter_users/show.html.haml +++ b/app/views/twitter_users/show.html.haml @@ -1,30 +1,30 @@ = link_to '&lt;-- Back to all users', url_for(:controller => 'tweets', :action => 'index') #profile - = image_tag(@twitter_user.profile_image_url, :class => 'user_image') + = image_tag(@twitter_user.profile_image_url, :class => 'user_image') if @twitter_user.profile_image_url %h1= @twitter_user.screen_name #profile-details - if @twitter_user.name && !@twitter_user.name.blank? %br/ %strong Name = @twitter_user.name - if @twitter_user.location && !@twitter_user.location.blank? %br/ %strong Location = @twitter_user.location - if @twitter_user.url && !@twitter_user.url.blank? %br/ %strong Web = link_to @twitter_user.url, @twitter_user.url - if @twitter_user.description && !@twitter_user.description.blank? %br/ %strong Bio = @twitter_user.description #tweet_container{:style => 'clear:both'} = render :partial => 'tweets/profile_tweet', :collection => @twitter_user.tweets, :spacer_template => 'tweets/spacer' \ No newline at end of file
neco/twitter.neco.com
352700e6f0c331ba278efc448847792ab04ed574
quick fix
diff --git a/app/views/tweets/_tweet.html.haml b/app/views/tweets/_tweet.html.haml index dbe1839..3fadec9 100644 --- a/app/views/tweets/_tweet.html.haml +++ b/app/views/tweets/_tweet.html.haml @@ -1,7 +1,7 @@ %div{:class => "tweet#{' first' if tweet_counter == 0}"} - = link_to image_tag(tweet.twitter_user.profile_image_url, :class => 'user_image'), profile_path(:screen_name => tweet.twitter_user.screen_name) + = link_to image_tag(tweet.twitter_user.profile_image_url, :class => 'user_image'), profile_path(:screen_name => tweet.twitter_user.screen_name) if tweet.twitter_user .content .text= parse_tweet(tweet.tweet_text) .details - = link_to tweet.twitter_user.screen_name, profile_path(:screen_name => tweet.twitter_user.screen_name) + = link_to tweet.twitter_user.screen_name, profile_path(:screen_name => tweet.twitter_user.screen_name) if tweet.twitter_user = tweet.tweeted_at.strftime('%l:%M %p Eastern - %a %D') \ No newline at end of file
neco/twitter.neco.com
6874fd5d57df6eb515fffd01555640ae67ba8569
added remember me
diff --git a/app/controllers/tweets_controller.rb b/app/controllers/tweets_controller.rb index 7421710..e95b83b 100644 --- a/app/controllers/tweets_controller.rb +++ b/app/controllers/tweets_controller.rb @@ -1,27 +1,45 @@ class TweetsController < ApplicationController def index search_opts = params[:search] || {} search_opts[:per_page] ||= 100 search_opts[:order_by] = :tweeted_at search_opts[:order_as] = 'DESC' @search = Tweet.new_search(search_opts) @tweets, @tweets_count = @search.all, @search.count end def post end + def forget_me + session[:twitter_username] = nil + session[:twitter_password] = nil + redirect_to :action => 'post' + end + def create_tweet username, password, message = params[:username], params[:password], params[:message] + + if session[:twitter_username] && session[:twitter_password] + username, password = session[:twitter_username], session[:twitter_password] + end + twitter = Twitter.new(username, password) begin twitter.post(message) twitter_user = TwitterUser.find_by_screen_name(username) twitter_user.tweets.create :tweeted_at => Time.now, :tweet_text => message + + # only remember if post was successful + if params[:remember] + session[:twitter_username] = username + session[:twitter_password] = password + end + redirect_to :action => 'index' rescue @error = 'Bad username or password.' render :action => 'post' end end end \ No newline at end of file diff --git a/app/helpers/tweets_helper.rb b/app/helpers/tweets_helper.rb index 939d412..1b78544 100644 --- a/app/helpers/tweets_helper.rb +++ b/app/helpers/tweets_helper.rb @@ -1,5 +1,9 @@ module TweetsHelper def parse_tweet(txt) txt.gsub(%r((http|https)://[^<>\s]+), %[<a href="\\0" target="_blank">\\0</a>]) end + + def remembered? + session[:twitter_username] && session[:twitter_password] + end end \ No newline at end of file diff --git a/app/views/tweets/post.html.haml b/app/views/tweets/post.html.haml index cc5edd6..79cb72b 100644 --- a/app/views/tweets/post.html.haml +++ b/app/views/tweets/post.html.haml @@ -1,18 +1,26 @@ %h1 Post a message to Twitter - if @error .error= @error = form_tag url_for(:action => 'create_tweet') -Username -%br/ -%input{:type => :text, :name => :username}/ -.spacer -Password -%br/ -%input{:type => :password, :name => :password}/ +- if remembered? + Logged in as + = session[:twitter_username] + == (#{link_to 'forget me', url_for(:action => 'forget_me')}) +- else + Username + %br/ + %input{:type => :text, :name => :username}/ + .spacer + Password + %br/ + %input{:type => :password, :name => :password}/ + .spacer + %input{:type => :checkbox, :name => :remember}/ + Remember me .spacer Message %br/ %input{:type => :text, :style => 'width:80%', :maxlength => 140, :name => :message}/ .spacer %input{:type => :submit, :value => 'Post!'}/ .spacer \ No newline at end of file
neco/twitter.neco.com
90e594e62409a9944037cf8e37d90a6173f48d5a
pushing out post changes
diff --git a/app/controllers/tweets_controller.rb b/app/controllers/tweets_controller.rb index 4fe9e45..7421710 100644 --- a/app/controllers/tweets_controller.rb +++ b/app/controllers/tweets_controller.rb @@ -1,10 +1,27 @@ class TweetsController < ApplicationController def index search_opts = params[:search] || {} search_opts[:per_page] ||= 100 search_opts[:order_by] = :tweeted_at search_opts[:order_as] = 'DESC' @search = Tweet.new_search(search_opts) @tweets, @tweets_count = @search.all, @search.count end + + def post + end + + def create_tweet + username, password, message = params[:username], params[:password], params[:message] + twitter = Twitter.new(username, password) + begin + twitter.post(message) + twitter_user = TwitterUser.find_by_screen_name(username) + twitter_user.tweets.create :tweeted_at => Time.now, :tweet_text => message + redirect_to :action => 'index' + rescue + @error = 'Bad username or password.' + render :action => 'post' + end + end end \ No newline at end of file diff --git a/app/models/tweet.rb b/app/models/tweet.rb index 12dd4aa..8a6e010 100644 --- a/app/models/tweet.rb +++ b/app/models/tweet.rb @@ -1,3 +1,5 @@ class Tweet < ActiveRecord::Base belongs_to :twitter_user + named_scope :from_twitter, :conditions => 'tweet_id IS NOT NULL' + named_scope :from_local, :conditions => 'tweet_id IS NULL' end diff --git a/app/views/tweets/post.html.haml b/app/views/tweets/post.html.haml new file mode 100644 index 0000000..cc5edd6 --- /dev/null +++ b/app/views/tweets/post.html.haml @@ -0,0 +1,18 @@ +%h1 Post a message to Twitter +- if @error + .error= @error += form_tag url_for(:action => 'create_tweet') +Username +%br/ +%input{:type => :text, :name => :username}/ +.spacer +Password +%br/ +%input{:type => :password, :name => :password}/ +.spacer +Message +%br/ +%input{:type => :text, :style => 'width:80%', :maxlength => 140, :name => :message}/ +.spacer +%input{:type => :submit, :value => 'Post!'}/ +.spacer \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 4a96350..33d2e45 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,46 +1,47 @@ ActionController::Routing::Routes.draw do |map| map.resources :twitter_users # 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 with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # 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 => "tweets" map.profile 'user/:screen_name', :controller => 'twitter_users', :action => 'show' + map.post_tweet 'post', :controller => 'tweets', :action => 'post' # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/lib/tasks/twitter_tasks.rake b/lib/tasks/twitter_tasks.rake index ee9b0df..f05321c 100644 --- a/lib/tasks/twitter_tasks.rake +++ b/lib/tasks/twitter_tasks.rake @@ -1,36 +1,39 @@ namespace :twitter do desc 'Fetch updates for all our twitter users' task :update => :environment do TwitterUser.all.each do |user| twitter = Twitter.new query = {:id => user.screen_name} query[:count] = 200 # this is the maximum allowed - query[:since_id] = user.tweets.first.tweet_id unless user.tweets.empty? + query[:since_id] = user.tweets.from_twitter.first.tweet_id unless user.tweets.empty? new_tweets = twitter.timeline(:user, :query => query) # update user information if new_tweets.size > 0 user_info = new_tweets.first['user'] %w[name location profile_image_url url followers_count description screen_name].each do |field| user.send("#{field}=", user_info[field]) end user.twitter_id = user_info['id'] user.save end + # we have the new tweets now, so let them replace the tweets we manually inserted + user.tweets.from_local.each {|tweet| tweet.destroy } + new_tweets.each do |tweet| user.tweets.create({ :tweeted_at => tweet['created_at'], :tweet_text => tweet['text'], :tweet_id => tweet['id'], :in_reply_to_screen_name => tweet['in_reply_to_screen_name'] }) end puts "Created #{new_tweets.size} tweets for #{user.screen_name}" end end end \ No newline at end of file diff --git a/lib/twitter.rb b/lib/twitter.rb index 9677044..fa02cf8 100644 --- a/lib/twitter.rb +++ b/lib/twitter.rb @@ -1,18 +1,23 @@ require 'httparty' class Twitter include HTTParty base_uri 'twitter.com' def initialize(u=nil, p=nil) @auth = {:username => u, :password => p} unless u.nil? || p.nil? end # which can be :friends, :user or :public # options[:query] can be things like since, since_id, count, etc. def timeline(which=:friends, options={}) options.merge!({:basic_auth => @auth}) if @auth self.class.get("/statuses/#{which}_timeline.json", options) end + def post(text) + self.class.basic_auth @auth[:username], @auth[:password] + self.class.post('/statuses/update.json', :query => {:status => text}) + end + end \ No newline at end of file diff --git a/public/stylesheets/twitter.css b/public/stylesheets/twitter.css index 427ccdb..c55e9fd 100644 --- a/public/stylesheets/twitter.css +++ b/public/stylesheets/twitter.css @@ -1,82 +1,93 @@ .tweet_spacer { height: 20px; clear: left; } +.spacer { + height: 12px; +} + +.error { + border: 2px solid red; + margin: 10px 0; + padding: 10px; + width: 40%; +} + #profile { margin-top: 20px; } #profile .user_image { float:left; } #profile h1 { float: left; padding-left: 20px; margin-top: 0; } #profile-details { float: left; padding-left: 30px; margin-top: -20px; } #tweet_container { padding: 15px 0 15px 0; } #neco_content { padding-left: 15px; } p.notice { color: red; } .tweet img.user_image { border: 1px solid #aaa; float: left; } .tweet .content { margin-left: 5px; float: left; } .tweet .text { padding: 8px; border: 1px solid #aaa; background-color: #fff; display: block; } .tweet .details { margin-left: 10px; margin-top: 3px; display: block; } div.pages { clear: both; padding-top: 20px; font-weight: bold; } a.page, span.page { padding: 4px 6px; } a.page { margin: 0 3px; border: 1px solid #ddd; text-decoration: none; color: #0063dc; } a.page:hover { border: 1px solid #003366; background-color: #0063dc; color: #fff; } span.disabled_page { color: #b1aab1; } span.current_page { color: #ff0084; } \ No newline at end of file
neco/twitter.neco.com
fb2511c3936ea67e0e82bb9736056dd4fe525f41
quick update
diff --git a/app/views/twitter_users/show.html.haml b/app/views/twitter_users/show.html.haml index 69dab29..cf2d356 100644 --- a/app/views/twitter_users/show.html.haml +++ b/app/views/twitter_users/show.html.haml @@ -1,30 +1,30 @@ = link_to '&lt;-- Back to all users', url_for(:controller => 'tweets', :action => 'index') #profile = image_tag(@twitter_user.profile_image_url, :class => 'user_image') %h1= @twitter_user.screen_name #profile-details - - if @twitter_user.name + - if @twitter_user.name && !@twitter_user.name.blank? %br/ %strong Name = @twitter_user.name - - if @twitter_user.location + - if @twitter_user.location && !@twitter_user.location.blank? %br/ %strong Location = @twitter_user.location - - if @twitter_user.url + - if @twitter_user.url && !@twitter_user.url.blank? %br/ %strong Web = link_to @twitter_user.url, @twitter_user.url - - if @twitter_user.description + - if @twitter_user.description && !@twitter_user.description.blank? %br/ %strong Bio = @twitter_user.description #tweet_container{:style => 'clear:both'} = render :partial => 'tweets/profile_tweet', :collection => @twitter_user.tweets, :spacer_template => 'tweets/spacer' \ No newline at end of file
neco/twitter.neco.com
4c7143bf905680fd0eac735da11c65bcc39494cc
added show twitter user page
diff --git a/app/controllers/twitter_users_controller.rb b/app/controllers/twitter_users_controller.rb index 315f7d2..cff4cfa 100644 --- a/app/controllers/twitter_users_controller.rb +++ b/app/controllers/twitter_users_controller.rb @@ -1,85 +1,79 @@ class TwitterUsersController < ApplicationController # GET /twitter_users # GET /twitter_users.xml def index @twitter_users = TwitterUser.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @twitter_users } end end - # GET /twitter_users/1 - # GET /twitter_users/1.xml def show - @twitter_user = TwitterUser.find(params[:id]) - - respond_to do |format| - format.html # show.html.erb - format.xml { render :xml => @twitter_user } - end + @twitter_user = TwitterUser.find_by_screen_name(params[:screen_name]) + render :action => :show, :layout => 'application' end # GET /twitter_users/new # GET /twitter_users/new.xml def new @twitter_user = TwitterUser.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @twitter_user } end end # GET /twitter_users/1/edit def edit @twitter_user = TwitterUser.find(params[:id]) end # POST /twitter_users # POST /twitter_users.xml def create @twitter_user = TwitterUser.new(params[:twitter_user]) respond_to do |format| if @twitter_user.save flash[:notice] = 'TwitterUser was successfully created.' - format.html { redirect_to(@twitter_user) } + format.html { redirect_to(:twitter_users) } format.xml { render :xml => @twitter_user, :status => :created, :location => @twitter_user } else format.html { render :action => "new" } format.xml { render :xml => @twitter_user.errors, :status => :unprocessable_entity } end end end # PUT /twitter_users/1 # PUT /twitter_users/1.xml def update @twitter_user = TwitterUser.find(params[:id]) respond_to do |format| if @twitter_user.update_attributes(params[:twitter_user]) flash[:notice] = 'TwitterUser was successfully updated.' format.html { redirect_to(@twitter_user) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @twitter_user.errors, :status => :unprocessable_entity } end end end # DELETE /twitter_users/1 # DELETE /twitter_users/1.xml def destroy @twitter_user = TwitterUser.find(params[:id]) @twitter_user.destroy respond_to do |format| format.html { redirect_to(twitter_users_url) } format.xml { head :ok } end end end diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index ad104f9..4b79b3a 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,121 +1,121 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content="The funniest and most entertaining reality twitter show available online. Ever wonder what goes on in the office of a ticket broker. Tune in to twitter.neco.com to keep up with the characters that make up this secondary ticket market leader." /> <meta http-equiv="refresh" content="600" /> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> <title>The Reality Twitter Show at National Event Company - Ticket Brokers - Rated R</title> -<link href="stylesheets/base.css" rel="stylesheet" type="text/css" /> -<link href="stylesheets/twitter.css" rel="stylesheet" type="text/css" /> +<link href="/stylesheets/base.css" rel="stylesheet" type="text/css" /> +<link href="/stylesheets/twitter.css" rel="stylesheet" type="text/css" /> <!--[if IE]> <link href="stylesheets/base_ie.css" rel="stylesheet" type="text/css" /> <![endif]--> </head> <body class="fixed blue"> <div id="bg"> <div id="container"> <div id="header"> <a title="Home" id="home" href="http://www.neco.com/"></a> <div id="top_right_container"> <div id="top_right"> <a href="http://www.neco.com/orders">Order Status</a>  |  <a href="http://www.neco.com/register">Register</a>  |  <a href="http://www.neco.com/password_resets/new">Forgot password?</a>  |  <a href="http://www.neco.com/help">Help</a>  |   <div class="spacer1"></div> </div> </div> <table cellspacing="0" cellpadding="0" id="top_nav"> <tbody><tr> <td><a href="http://www.neco.com/"><span class="left"><span class="right">Tickets</span></span></a></td> <td><a href="http://www.neco.com/event_packages"><span class="left"><span class="right">Event Packages</span></span></a></td> <td><a href="http://blog.neco.com"><span class="left"><span class="right">Blog</span></span></a></td> <td><a class="hover" href="http://twitter.neco.com"><span class="left"><span class="right">Twitter</span></span></a></td> </tr> </tbody></table> <div id="phone_number"><img src="http://assets1.neco.com/images/phone_icon.jpg" alt="Phone_icon"/>866-NECO-TIX (632-6849)</div> </div> <div id="content_top"> <div id="content_right"> <div id="content_bottom"> <div id="content_left"> <div id="content_top_left"> <div id="content_top_right"> <div id="content_bottom_right"> <div id="content_bottom_left"> <table cellspacing="0" cellpadding="0" id="content_middle"> <tbody><tr> <td id="content_middle_cell"> <div id="neco_content"> <%= yield %> </div> </td> </tr> </tbody></table> </div> </div> </div> </div> </div> </div> </div> </div> <div id="footer"> <div id="jargon"> <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://greenleaf.neco.com">Hip Hop Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://twitter.neco.com">Twitter</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> <div class="spacer2"></div> <a href="http://www.neco.com/contact">Contact Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/about">About Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/why">Why Us?</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/employment">Employment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/affiliate_groups/new">Affiliates</a> <div class="spacer3"></div></div> <div id="contact_info">866-NECO-TIX (632-6849)&nbsp;&nbsp;|&nbsp;&nbsp;1430 Broadway, 7th Floor, New York, NY 10018</div> <div id="legal"> Copyright &copy; 2008, National Event Company II LLC, All Rights Reserved<br /> <a href="http://www.neco.com/terms">Terms &amp; Conditions</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/privacy_policy">Privacy Policy</a> </div> </div> <div id="seals"> <a href="http://www.bbbonline.org/cks.asp?id=1080620144110&amp;popup=true" onclick="window.open(this.href,'bbb','bbb');return false;" style="position: relative; bottom: 7px;"><img alt="BBB Seal" src="http://assets2.neco.com/images/bbbseal.gif?1227893291" /></a> <a href="https://seal.godaddy.com/verifySeal?sealID=2082029625050c04df7127112c49aa7e517fcb04658573943778635413&amp;popup=true" onclick="window.open(this.href,'godaddy_ssl','height=620,width=536');return false;"><img alt="Godaddy_ssl" src="http://assets2.neco.com/images/godaddy_ssl.jpg?1227893291" /></a> <img alt="Credit_card_logos" src="http://assets2.neco.com/images/credit_card_logos.jpg?1227893291" /> <a href="https://www.paypal.com/us/verified/pal=paypal%40neco%2ecom?popup=true" onclick="window.open(this.href,'paypal_verified','paypal_verified');return false;"><img alt="Paypal_verified" src="http://assets2.neco.com/images/paypal_verified.jpg?1227893291" /></a> <a href="http://www.facebook.com/pages/National-Event-Company-Necocom/25632242064?popup=true" onclick="window.open(this.href);return false;" style="position: relative; bottom: 5px;"><img alt="Facebook_logo" src="http://assets0.neco.com/images/facebook_logo.jpg?1227893291" /></a> </div> </div> </div> </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"> try { var pageTracker = _gat._getTracker("UA-3488694-6"); pageTracker._trackPageview(); } catch(err) {}</script> </body> </html> diff --git a/app/views/tweets/_profile_tweet.html.haml b/app/views/tweets/_profile_tweet.html.haml new file mode 100644 index 0000000..ff744f9 --- /dev/null +++ b/app/views/tweets/_profile_tweet.html.haml @@ -0,0 +1,5 @@ +%div{:class => "tweet#{' first' if profile_tweet_counter == 0}"} + .content + .text= parse_tweet(profile_tweet.tweet_text) + .details + = profile_tweet.tweeted_at.strftime('%l:%M %p Eastern - %a %D') \ No newline at end of file diff --git a/app/views/tweets/_tweet.html.haml b/app/views/tweets/_tweet.html.haml index a724cfd..dbe1839 100644 --- a/app/views/tweets/_tweet.html.haml +++ b/app/views/tweets/_tweet.html.haml @@ -1,7 +1,7 @@ %div{:class => "tweet#{' first' if tweet_counter == 0}"} - = image_tag(tweet.twitter_user.profile_image_url, :class => 'user_image') + = link_to image_tag(tweet.twitter_user.profile_image_url, :class => 'user_image'), profile_path(:screen_name => tweet.twitter_user.screen_name) .content .text= parse_tweet(tweet.tweet_text) .details - = link_to tweet.twitter_user.screen_name, "http://twitter.com/#{tweet.twitter_user.screen_name}" + = link_to tweet.twitter_user.screen_name, profile_path(:screen_name => tweet.twitter_user.screen_name) = tweet.tweeted_at.strftime('%l:%M %p Eastern - %a %D') \ No newline at end of file diff --git a/app/views/twitter_users/index.html.erb b/app/views/twitter_users/index.html.erb index 7841886..feec338 100644 --- a/app/views/twitter_users/index.html.erb +++ b/app/views/twitter_users/index.html.erb @@ -1,34 +1,33 @@ <h1>Listing twitter_users</h1> <table> <tr> <th>Name</th> <th>Location</th> <th>Profile image url</th> <th>Url</th> <th>Twitter</th> <th>Followers count</th> <th>Description</th> <th>Screen name</th> </tr> <% for twitter_user in @twitter_users %> <tr> <td><%=h twitter_user.name %></td> <td><%=h twitter_user.location %></td> <td><%=h twitter_user.profile_image_url %></td> <td><%=h twitter_user.url %></td> <td><%=h twitter_user.twitter_id %></td> <td><%=h twitter_user.followers_count %></td> <td><%=h twitter_user.description %></td> <td><%=h twitter_user.screen_name %></td> - <td><%= link_to 'Show', twitter_user %></td> <td><%= link_to 'Edit', edit_twitter_user_path(twitter_user) %></td> <td><%= link_to 'Destroy', twitter_user, :confirm => 'Are you sure?', :method => :delete %></td> </tr> <% end %> </table> <br /> <%= link_to 'New twitter_user', new_twitter_user_path %> diff --git a/app/views/twitter_users/show.html.erb b/app/views/twitter_users/show.html.erb deleted file mode 100644 index 4bb538d..0000000 --- a/app/views/twitter_users/show.html.erb +++ /dev/null @@ -1,43 +0,0 @@ -<p> - <b>Name:</b> - <%=h @twitter_user.name %> -</p> - -<p> - <b>Location:</b> - <%=h @twitter_user.location %> -</p> - -<p> - <b>Profile image url:</b> - <%=h @twitter_user.profile_image_url %> -</p> - -<p> - <b>Url:</b> - <%=h @twitter_user.url %> -</p> - -<p> - <b>Twitter:</b> - <%=h @twitter_user.twitter_id %> -</p> - -<p> - <b>Followers count:</b> - <%=h @twitter_user.followers_count %> -</p> - -<p> - <b>Description:</b> - <%=h @twitter_user.description %> -</p> - -<p> - <b>Screen name:</b> - <%=h @twitter_user.screen_name %> -</p> - - -<%= link_to 'Edit', edit_twitter_user_path(@twitter_user) %> | -<%= link_to 'Back', twitter_users_path %> diff --git a/app/views/twitter_users/show.html.haml b/app/views/twitter_users/show.html.haml new file mode 100644 index 0000000..69dab29 --- /dev/null +++ b/app/views/twitter_users/show.html.haml @@ -0,0 +1,30 @@ += link_to '&lt;-- Back to all users', url_for(:controller => 'tweets', :action => 'index') + +#profile + = image_tag(@twitter_user.profile_image_url, :class => 'user_image') + %h1= @twitter_user.screen_name + + #profile-details + - if @twitter_user.name + %br/ + %strong + Name + = @twitter_user.name + - if @twitter_user.location + %br/ + %strong + Location + = @twitter_user.location + - if @twitter_user.url + %br/ + %strong + Web + = link_to @twitter_user.url, @twitter_user.url + - if @twitter_user.description + %br/ + %strong + Bio + = @twitter_user.description + +#tweet_container{:style => 'clear:both'} + = render :partial => 'tweets/profile_tweet', :collection => @twitter_user.tweets, :spacer_template => 'tweets/spacer' \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 772cbf2..4a96350 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,45 +1,46 @@ ActionController::Routing::Routes.draw do |map| map.resources :twitter_users # 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 with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # 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 => "tweets" + map.profile 'user/:screen_name', :controller => 'twitter_users', :action => 'show' # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/public/stylesheets/twitter.css b/public/stylesheets/twitter.css index 8ebd756..427ccdb 100644 --- a/public/stylesheets/twitter.css +++ b/public/stylesheets/twitter.css @@ -1,67 +1,82 @@ .tweet_spacer { height: 20px; clear: left; } +#profile { margin-top: 20px; } + +#profile .user_image { float:left; } + +#profile h1 { + float: left; + padding-left: 20px; + margin-top: 0; +} + +#profile-details { + float: left; + padding-left: 30px; + margin-top: -20px; +} #tweet_container { padding: 15px 0 15px 0; } #neco_content { padding-left: 15px; } p.notice { color: red; } .tweet img.user_image { border: 1px solid #aaa; float: left; } .tweet .content { margin-left: 5px; float: left; } .tweet .text { padding: 8px; border: 1px solid #aaa; background-color: #fff; display: block; } .tweet .details { margin-left: 10px; margin-top: 3px; display: block; } div.pages { clear: both; padding-top: 20px; font-weight: bold; } a.page, span.page { padding: 4px 6px; } a.page { margin: 0 3px; border: 1px solid #ddd; text-decoration: none; color: #0063dc; } a.page:hover { border: 1px solid #003366; background-color: #0063dc; color: #fff; } span.disabled_page { color: #b1aab1; } span.current_page { color: #ff0084; } \ No newline at end of file
neco/twitter.neco.com
412d37554b2b4f4a36e49ccb949503a91f4314bd
changed auto refresh notice to red
diff --git a/app/views/tweets/index.html.haml b/app/views/tweets/index.html.haml index a6d6701..89f4522 100644 --- a/app/views/tweets/index.html.haml +++ b/app/views/tweets/index.html.haml @@ -1,21 +1,21 @@ %div{:style => 'float: right; margin-top: -18px'} / AddThis Button BEGIN :javascript var addthis_pub = "necotweet"; %a{:href => "http://www.addthis.com/bookmark.php", :onmouseover => "return addthis_open(this, '', 'http://twitter.neco.com', 'The Reality Twitter Show at National Event Company - Ticket Brokers - Rated R')", :onmouseout => "addthis_close()", :onclick => "return addthis_sendto()"} %img{:src => "http://s7.addthis.com/static/btn/lg-addthis-en.gif", :width => "125", :height => "16", :border => "0", :alt => ""}/ %script{:type => "text/javascript", :src => "http://s7.addthis.com/js/152/addthis_widget.js"} / AddThis Button END %br/ %img{:src => '/images/twitter.png', :alt => 'Twitter Logo'}/ %h1 The Neco Reality Ticket Broker Show -%p (This page auto-refreshes every 10 minutes.) +%p.notice (This page auto-refreshes every 10 minutes.) %p Live From New York... it's the funniest and most entertaining reality twitter show available online. Ever wonder what goes on in the office of a ticket broker. Tune in to twitter.neco.com to keep up with the characters that make up this secondary ticket market leader. %p Who knows, you might even pick up some insider tips along the way... #tweet_container = render :partial => 'tweet', :collection => @tweets, :spacer_template => 'spacer' .pages= page_links( :spread => 1 ) diff --git a/public/stylesheets/twitter.css b/public/stylesheets/twitter.css index 4ce15c4..8ebd756 100644 --- a/public/stylesheets/twitter.css +++ b/public/stylesheets/twitter.css @@ -1,65 +1,67 @@ .tweet_spacer { height: 20px; clear: left; } #tweet_container { padding: 15px 0 15px 0; } #neco_content { padding-left: 15px; } +p.notice { color: red; } + .tweet img.user_image { border: 1px solid #aaa; float: left; } .tweet .content { margin-left: 5px; float: left; } .tweet .text { padding: 8px; border: 1px solid #aaa; background-color: #fff; display: block; } .tweet .details { margin-left: 10px; margin-top: 3px; display: block; } div.pages { clear: both; padding-top: 20px; font-weight: bold; } a.page, span.page { padding: 4px 6px; } a.page { margin: 0 3px; border: 1px solid #ddd; text-decoration: none; color: #0063dc; } a.page:hover { border: 1px solid #003366; background-color: #0063dc; color: #fff; } span.disabled_page { color: #b1aab1; } span.current_page { color: #ff0084; } \ No newline at end of file
neco/twitter.neco.com
6707b719ad98e5c5941fd84e1f8995c6fffeced8
added analytics
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 2638efb..ad104f9 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,113 +1,121 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content="The funniest and most entertaining reality twitter show available online. Ever wonder what goes on in the office of a ticket broker. Tune in to twitter.neco.com to keep up with the characters that make up this secondary ticket market leader." /> <meta http-equiv="refresh" content="600" /> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> <title>The Reality Twitter Show at National Event Company - Ticket Brokers - Rated R</title> <link href="stylesheets/base.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/twitter.css" rel="stylesheet" type="text/css" /> <!--[if IE]> <link href="stylesheets/base_ie.css" rel="stylesheet" type="text/css" /> <![endif]--> </head> <body class="fixed blue"> <div id="bg"> <div id="container"> <div id="header"> <a title="Home" id="home" href="http://www.neco.com/"></a> <div id="top_right_container"> <div id="top_right"> <a href="http://www.neco.com/orders">Order Status</a>  |  <a href="http://www.neco.com/register">Register</a>  |  <a href="http://www.neco.com/password_resets/new">Forgot password?</a>  |  <a href="http://www.neco.com/help">Help</a>  |   <div class="spacer1"></div> </div> </div> <table cellspacing="0" cellpadding="0" id="top_nav"> <tbody><tr> <td><a href="http://www.neco.com/"><span class="left"><span class="right">Tickets</span></span></a></td> <td><a href="http://www.neco.com/event_packages"><span class="left"><span class="right">Event Packages</span></span></a></td> <td><a href="http://blog.neco.com"><span class="left"><span class="right">Blog</span></span></a></td> <td><a class="hover" href="http://twitter.neco.com"><span class="left"><span class="right">Twitter</span></span></a></td> </tr> </tbody></table> <div id="phone_number"><img src="http://assets1.neco.com/images/phone_icon.jpg" alt="Phone_icon"/>866-NECO-TIX (632-6849)</div> </div> <div id="content_top"> <div id="content_right"> <div id="content_bottom"> <div id="content_left"> <div id="content_top_left"> <div id="content_top_right"> <div id="content_bottom_right"> <div id="content_bottom_left"> <table cellspacing="0" cellpadding="0" id="content_middle"> <tbody><tr> <td id="content_middle_cell"> <div id="neco_content"> <%= yield %> </div> </td> </tr> </tbody></table> </div> </div> </div> </div> </div> </div> </div> </div> <div id="footer"> <div id="jargon"> <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://greenleaf.neco.com">Hip Hop Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://twitter.neco.com">Twitter</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> <div class="spacer2"></div> <a href="http://www.neco.com/contact">Contact Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/about">About Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/why">Why Us?</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/employment">Employment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/affiliate_groups/new">Affiliates</a> <div class="spacer3"></div></div> <div id="contact_info">866-NECO-TIX (632-6849)&nbsp;&nbsp;|&nbsp;&nbsp;1430 Broadway, 7th Floor, New York, NY 10018</div> <div id="legal"> Copyright &copy; 2008, National Event Company II LLC, All Rights Reserved<br /> <a href="http://www.neco.com/terms">Terms &amp; Conditions</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/privacy_policy">Privacy Policy</a> </div> </div> <div id="seals"> <a href="http://www.bbbonline.org/cks.asp?id=1080620144110&amp;popup=true" onclick="window.open(this.href,'bbb','bbb');return false;" style="position: relative; bottom: 7px;"><img alt="BBB Seal" src="http://assets2.neco.com/images/bbbseal.gif?1227893291" /></a> <a href="https://seal.godaddy.com/verifySeal?sealID=2082029625050c04df7127112c49aa7e517fcb04658573943778635413&amp;popup=true" onclick="window.open(this.href,'godaddy_ssl','height=620,width=536');return false;"><img alt="Godaddy_ssl" src="http://assets2.neco.com/images/godaddy_ssl.jpg?1227893291" /></a> <img alt="Credit_card_logos" src="http://assets2.neco.com/images/credit_card_logos.jpg?1227893291" /> <a href="https://www.paypal.com/us/verified/pal=paypal%40neco%2ecom?popup=true" onclick="window.open(this.href,'paypal_verified','paypal_verified');return false;"><img alt="Paypal_verified" src="http://assets2.neco.com/images/paypal_verified.jpg?1227893291" /></a> <a href="http://www.facebook.com/pages/National-Event-Company-Necocom/25632242064?popup=true" onclick="window.open(this.href);return false;" style="position: relative; bottom: 5px;"><img alt="Facebook_logo" src="http://assets0.neco.com/images/facebook_logo.jpg?1227893291" /></a> </div> </div> </div> </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"> +try { +var pageTracker = _gat._getTracker("UA-3488694-6"); +pageTracker._trackPageview(); +} catch(err) {}</script> </body> </html>
neco/twitter.neco.com
071cf5c5a78174c6d92cd473a41836e20d593d25
added auto refresh info to tweet page
diff --git a/app/views/tweets/index.html.haml b/app/views/tweets/index.html.haml index 8dac580..a6d6701 100644 --- a/app/views/tweets/index.html.haml +++ b/app/views/tweets/index.html.haml @@ -1,20 +1,21 @@ %div{:style => 'float: right; margin-top: -18px'} / AddThis Button BEGIN :javascript var addthis_pub = "necotweet"; %a{:href => "http://www.addthis.com/bookmark.php", :onmouseover => "return addthis_open(this, '', 'http://twitter.neco.com', 'The Reality Twitter Show at National Event Company - Ticket Brokers - Rated R')", :onmouseout => "addthis_close()", :onclick => "return addthis_sendto()"} %img{:src => "http://s7.addthis.com/static/btn/lg-addthis-en.gif", :width => "125", :height => "16", :border => "0", :alt => ""}/ %script{:type => "text/javascript", :src => "http://s7.addthis.com/js/152/addthis_widget.js"} / AddThis Button END %br/ %img{:src => '/images/twitter.png', :alt => 'Twitter Logo'}/ %h1 The Neco Reality Ticket Broker Show +%p (This page auto-refreshes every 10 minutes.) %p Live From New York... it's the funniest and most entertaining reality twitter show available online. Ever wonder what goes on in the office of a ticket broker. Tune in to twitter.neco.com to keep up with the characters that make up this secondary ticket market leader. %p Who knows, you might even pick up some insider tips along the way... #tweet_container = render :partial => 'tweet', :collection => @tweets, :spacer_template => 'spacer' .pages= page_links( :spread => 1 )
neco/twitter.neco.com
ad91be746e09142932de8ce0bcf767bc8a2df416
added add this button
diff --git a/app/views/tweets/index.html.haml b/app/views/tweets/index.html.haml index 6048f51..8dac580 100644 --- a/app/views/tweets/index.html.haml +++ b/app/views/tweets/index.html.haml @@ -1,10 +1,20 @@ -%img{:src => '/images/twitter.png', :alt => 'Twitter Logo', :style => 'float:right'}/ +%div{:style => 'float: right; margin-top: -18px'} + / AddThis Button BEGIN + :javascript + var addthis_pub = "necotweet"; + %a{:href => "http://www.addthis.com/bookmark.php", :onmouseover => "return addthis_open(this, '', 'http://twitter.neco.com', 'The Reality Twitter Show at National Event Company - Ticket Brokers - Rated R')", :onmouseout => "addthis_close()", :onclick => "return addthis_sendto()"} + %img{:src => "http://s7.addthis.com/static/btn/lg-addthis-en.gif", :width => "125", :height => "16", :border => "0", :alt => ""}/ + %script{:type => "text/javascript", :src => "http://s7.addthis.com/js/152/addthis_widget.js"} + / AddThis Button END + %br/ + %img{:src => '/images/twitter.png', :alt => 'Twitter Logo'}/ %h1 The Neco Reality Ticket Broker Show %p Live From New York... it's the funniest and most entertaining reality twitter show available online. Ever wonder what goes on in the office of a ticket broker. Tune in to twitter.neco.com to keep up with the characters that make up this secondary ticket market leader. %p Who knows, you might even pick up some insider tips along the way... + #tweet_container = render :partial => 'tweet', :collection => @tweets, :spacer_template => 'spacer' .pages= page_links( :spread => 1 )
neco/twitter.neco.com
f91f8883e98707cd28f2c5c89296d590270aa04b
added neco favicon
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index ffabab6..2638efb 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,112 +1,113 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content="The funniest and most entertaining reality twitter show available online. Ever wonder what goes on in the office of a ticket broker. Tune in to twitter.neco.com to keep up with the characters that make up this secondary ticket market leader." /> <meta http-equiv="refresh" content="600" /> +<link rel="icon" href="/favicon.ico" type="image/x-icon" /> <title>The Reality Twitter Show at National Event Company - Ticket Brokers - Rated R</title> <link href="stylesheets/base.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/twitter.css" rel="stylesheet" type="text/css" /> <!--[if IE]> <link href="stylesheets/base_ie.css" rel="stylesheet" type="text/css" /> <![endif]--> </head> <body class="fixed blue"> <div id="bg"> <div id="container"> <div id="header"> <a title="Home" id="home" href="http://www.neco.com/"></a> <div id="top_right_container"> <div id="top_right"> <a href="http://www.neco.com/orders">Order Status</a>  |  <a href="http://www.neco.com/register">Register</a>  |  <a href="http://www.neco.com/password_resets/new">Forgot password?</a>  |  <a href="http://www.neco.com/help">Help</a>  |   <div class="spacer1"></div> </div> </div> <table cellspacing="0" cellpadding="0" id="top_nav"> <tbody><tr> <td><a href="http://www.neco.com/"><span class="left"><span class="right">Tickets</span></span></a></td> <td><a href="http://www.neco.com/event_packages"><span class="left"><span class="right">Event Packages</span></span></a></td> <td><a href="http://blog.neco.com"><span class="left"><span class="right">Blog</span></span></a></td> <td><a class="hover" href="http://twitter.neco.com"><span class="left"><span class="right">Twitter</span></span></a></td> </tr> </tbody></table> <div id="phone_number"><img src="http://assets1.neco.com/images/phone_icon.jpg" alt="Phone_icon"/>866-NECO-TIX (632-6849)</div> </div> <div id="content_top"> <div id="content_right"> <div id="content_bottom"> <div id="content_left"> <div id="content_top_left"> <div id="content_top_right"> <div id="content_bottom_right"> <div id="content_bottom_left"> <table cellspacing="0" cellpadding="0" id="content_middle"> <tbody><tr> <td id="content_middle_cell"> <div id="neco_content"> <%= yield %> </div> </td> </tr> </tbody></table> </div> </div> </div> </div> </div> </div> </div> </div> <div id="footer"> <div id="jargon"> <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://greenleaf.neco.com">Hip Hop Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://twitter.neco.com">Twitter</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> <div class="spacer2"></div> <a href="http://www.neco.com/contact">Contact Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/about">About Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/why">Why Us?</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/employment">Employment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/affiliate_groups/new">Affiliates</a> <div class="spacer3"></div></div> <div id="contact_info">866-NECO-TIX (632-6849)&nbsp;&nbsp;|&nbsp;&nbsp;1430 Broadway, 7th Floor, New York, NY 10018</div> <div id="legal"> Copyright &copy; 2008, National Event Company II LLC, All Rights Reserved<br /> <a href="http://www.neco.com/terms">Terms &amp; Conditions</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/privacy_policy">Privacy Policy</a> </div> </div> <div id="seals"> <a href="http://www.bbbonline.org/cks.asp?id=1080620144110&amp;popup=true" onclick="window.open(this.href,'bbb','bbb');return false;" style="position: relative; bottom: 7px;"><img alt="BBB Seal" src="http://assets2.neco.com/images/bbbseal.gif?1227893291" /></a> <a href="https://seal.godaddy.com/verifySeal?sealID=2082029625050c04df7127112c49aa7e517fcb04658573943778635413&amp;popup=true" onclick="window.open(this.href,'godaddy_ssl','height=620,width=536');return false;"><img alt="Godaddy_ssl" src="http://assets2.neco.com/images/godaddy_ssl.jpg?1227893291" /></a> <img alt="Credit_card_logos" src="http://assets2.neco.com/images/credit_card_logos.jpg?1227893291" /> <a href="https://www.paypal.com/us/verified/pal=paypal%40neco%2ecom?popup=true" onclick="window.open(this.href,'paypal_verified','paypal_verified');return false;"><img alt="Paypal_verified" src="http://assets2.neco.com/images/paypal_verified.jpg?1227893291" /></a> <a href="http://www.facebook.com/pages/National-Event-Company-Necocom/25632242064?popup=true" onclick="window.open(this.href);return false;" style="position: relative; bottom: 5px;"><img alt="Facebook_logo" src="http://assets0.neco.com/images/facebook_logo.jpg?1227893291" /></a> </div> </div> </div> </div> </body> </html> diff --git a/public/favicon.ico b/public/favicon.ico index e69de29..0648060 100644 Binary files a/public/favicon.ico and b/public/favicon.ico differ
neco/twitter.neco.com
5d8ca2284455a0ca812e6cc625f4db986390fea4
added twitter logo
diff --git a/app/views/tweets/index.html.haml b/app/views/tweets/index.html.haml index 9e58beb..6048f51 100644 --- a/app/views/tweets/index.html.haml +++ b/app/views/tweets/index.html.haml @@ -1,8 +1,10 @@ +%img{:src => '/images/twitter.png', :alt => 'Twitter Logo', :style => 'float:right'}/ + %h1 The Neco Reality Ticket Broker Show %p Live From New York... it's the funniest and most entertaining reality twitter show available online. Ever wonder what goes on in the office of a ticket broker. Tune in to twitter.neco.com to keep up with the characters that make up this secondary ticket market leader. %p Who knows, you might even pick up some insider tips along the way... #tweet_container = render :partial => 'tweet', :collection => @tweets, :spacer_template => 'spacer' .pages= page_links( :spread => 1 ) diff --git a/public/images/twitter.png b/public/images/twitter.png new file mode 100644 index 0000000..238ea88 Binary files /dev/null and b/public/images/twitter.png differ
neco/twitter.neco.com
621f79838278baf908ded96fdd268923539f62e7
per page back at 100
diff --git a/app/controllers/tweets_controller.rb b/app/controllers/tweets_controller.rb index a41ca80..4fe9e45 100644 --- a/app/controllers/tweets_controller.rb +++ b/app/controllers/tweets_controller.rb @@ -1,10 +1,10 @@ class TweetsController < ApplicationController def index search_opts = params[:search] || {} - search_opts[:per_page] ||= 1 + search_opts[:per_page] ||= 100 search_opts[:order_by] = :tweeted_at search_opts[:order_as] = 'DESC' @search = Tweet.new_search(search_opts) @tweets, @tweets_count = @search.all, @search.count end end \ No newline at end of file
neco/twitter.neco.com
d06a7d093957628ff9d06b66554aa07222cc53c7
added hip hop blog to footer nav
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 8ec8ffa..621593a 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,116 +1,116 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> National Event Company Twitter Updates - Home </title> <link href="stylesheets/base.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/twitter.css" rel="stylesheet" type="text/css" /> <!--[if IE]> <link href="stylesheets/base_ie.css" rel="stylesheet" type="text/css" /> <![endif]--> </head> <body class="fixed blue"> <div id="bg"> <div id="container"> <div id="header"> <a title="Home" id="home" href="http://www.neco.com/"></a> <div id="top_right_container"> <div id="top_right"> <a href="http://www.neco.com/orders">Order Status</a>  |  <a href="http://www.neco.com/register">Register</a>  |  <a href="http://www.neco.com/password_resets/new">Forgot password?</a>  |  <a href="http://www.neco.com/help">Help</a>  |   <div class="spacer1"></div> </div> </div> <table cellspacing="0" cellpadding="0" id="top_nav"> <tbody><tr> <td><a href="http://www.neco.com/"><span class="left"><span class="right">Tickets</span></span></a></td> <td><a href="http://www.neco.com/event_packages"><span class="left"><span class="right">Event Packages</span></span></a></td> <td><a href="http://blog.neco.com"><span class="left"><span class="right">Blog</span></span></a></td> <td><a class="hover" href="http://twitter.neco.com"><span class="left"><span class="right">Twitter</span></span></a></td> </tr> </tbody></table> <div id="phone_number"><img src="http://assets1.neco.com/images/phone_icon.jpg" alt="Phone_icon"/>866-NECO-TIX (632-6849)</div> </div> <div id="content_top"> <div id="content_right"> <div id="content_bottom"> <div id="content_left"> <div id="content_top_left"> <div id="content_top_right"> <div id="content_bottom_right"> <div id="content_bottom_left"> <table cellspacing="0" cellpadding="0" id="content_middle"> <tbody><tr> <td id="content_middle_cell"> <div id="neco_content"> <%= yield %> </div> </td> </tr> </tbody></table> </div> </div> </div> </div> </div> </div> </div> </div> <div id="footer"> <div id="jargon"> - <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://twitter.neco.com">Twitter</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> + <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://greenleaf.neco.com">Hip Hop Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://twitter.neco.com">Twitter</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> <div class="spacer2"></div> <a href="http://www.neco.com/contact">Contact Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/about">About Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/why">Why Us?</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/employment">Employment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/affiliate_groups/new">Affiliates</a> <div class="spacer3"></div></div> <div id="contact_info">866-NECO-TIX (632-6849)&nbsp;&nbsp;|&nbsp;&nbsp;1430 Broadway, 7th Floor, New York, NY 10018</div> <div id="legal"> Copyright &copy; 2008, National Event Company II LLC, All Rights Reserved<br /> <a href="http://www.neco.com/terms">Terms &amp; Conditions</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/privacy_policy">Privacy Policy</a> </div> </div> <div id="seals"> <a href="http://www.bbbonline.org/cks.asp?id=1080620144110&amp;popup=true" onclick="window.open(this.href,'bbb','bbb');return false;" style="position: relative; bottom: 7px;"><img alt="BBB Seal" src="http://assets2.neco.com/images/bbbseal.gif?1227893291" /></a> <a href="https://seal.godaddy.com/verifySeal?sealID=2082029625050c04df7127112c49aa7e517fcb04658573943778635413&amp;popup=true" onclick="window.open(this.href,'godaddy_ssl','height=620,width=536');return false;"><img alt="Godaddy_ssl" src="http://assets2.neco.com/images/godaddy_ssl.jpg?1227893291" /></a> <img alt="Credit_card_logos" src="http://assets2.neco.com/images/credit_card_logos.jpg?1227893291" /> <a href="https://www.paypal.com/us/verified/pal=paypal%40neco%2ecom?popup=true" onclick="window.open(this.href,'paypal_verified','paypal_verified');return false;"><img alt="Paypal_verified" src="http://assets2.neco.com/images/paypal_verified.jpg?1227893291" /></a> <a href="http://www.facebook.com/pages/National-Event-Company-Necocom/25632242064?popup=true" onclick="window.open(this.href);return false;" style="position: relative; bottom: 5px;"><img alt="Facebook_logo" src="http://assets0.neco.com/images/facebook_logo.jpg?1227893291" /></a> </div> </div> </div> </div> </body> </html>
neco/twitter.neco.com
82721a874b90c0a7b0ae4bb6b603890741a7f003
added twitter to footer
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 2573346..8ec8ffa 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,116 +1,116 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> National Event Company Twitter Updates - Home </title> <link href="stylesheets/base.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/twitter.css" rel="stylesheet" type="text/css" /> <!--[if IE]> <link href="stylesheets/base_ie.css" rel="stylesheet" type="text/css" /> <![endif]--> </head> <body class="fixed blue"> <div id="bg"> <div id="container"> <div id="header"> <a title="Home" id="home" href="http://www.neco.com/"></a> <div id="top_right_container"> <div id="top_right"> <a href="http://www.neco.com/orders">Order Status</a>  |  <a href="http://www.neco.com/register">Register</a>  |  <a href="http://www.neco.com/password_resets/new">Forgot password?</a>  |  <a href="http://www.neco.com/help">Help</a>  |   <div class="spacer1"></div> </div> </div> <table cellspacing="0" cellpadding="0" id="top_nav"> <tbody><tr> <td><a href="http://www.neco.com/"><span class="left"><span class="right">Tickets</span></span></a></td> <td><a href="http://www.neco.com/event_packages"><span class="left"><span class="right">Event Packages</span></span></a></td> <td><a href="http://blog.neco.com"><span class="left"><span class="right">Blog</span></span></a></td> <td><a class="hover" href="http://twitter.neco.com"><span class="left"><span class="right">Twitter</span></span></a></td> </tr> </tbody></table> <div id="phone_number"><img src="http://assets1.neco.com/images/phone_icon.jpg" alt="Phone_icon"/>866-NECO-TIX (632-6849)</div> </div> <div id="content_top"> <div id="content_right"> <div id="content_bottom"> <div id="content_left"> <div id="content_top_left"> <div id="content_top_right"> <div id="content_bottom_right"> <div id="content_bottom_left"> <table cellspacing="0" cellpadding="0" id="content_middle"> <tbody><tr> <td id="content_middle_cell"> <div id="neco_content"> <%= yield %> </div> </td> </tr> </tbody></table> </div> </div> </div> </div> </div> </div> </div> </div> <div id="footer"> <div id="jargon"> - <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|<a href="http://twitter.neco.com">Twitter</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> + <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://twitter.neco.com">Twitter</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> <div class="spacer2"></div> <a href="http://www.neco.com/contact">Contact Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/about">About Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/why">Why Us?</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/employment">Employment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/affiliate_groups/new">Affiliates</a> <div class="spacer3"></div></div> <div id="contact_info">866-NECO-TIX (632-6849)&nbsp;&nbsp;|&nbsp;&nbsp;1430 Broadway, 7th Floor, New York, NY 10018</div> <div id="legal"> Copyright &copy; 2008, National Event Company II LLC, All Rights Reserved<br /> <a href="http://www.neco.com/terms">Terms &amp; Conditions</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/privacy_policy">Privacy Policy</a> </div> </div> <div id="seals"> <a href="http://www.bbbonline.org/cks.asp?id=1080620144110&amp;popup=true" onclick="window.open(this.href,'bbb','bbb');return false;" style="position: relative; bottom: 7px;"><img alt="BBB Seal" src="http://assets2.neco.com/images/bbbseal.gif?1227893291" /></a> <a href="https://seal.godaddy.com/verifySeal?sealID=2082029625050c04df7127112c49aa7e517fcb04658573943778635413&amp;popup=true" onclick="window.open(this.href,'godaddy_ssl','height=620,width=536');return false;"><img alt="Godaddy_ssl" src="http://assets2.neco.com/images/godaddy_ssl.jpg?1227893291" /></a> <img alt="Credit_card_logos" src="http://assets2.neco.com/images/credit_card_logos.jpg?1227893291" /> <a href="https://www.paypal.com/us/verified/pal=paypal%40neco%2ecom?popup=true" onclick="window.open(this.href,'paypal_verified','paypal_verified');return false;"><img alt="Paypal_verified" src="http://assets2.neco.com/images/paypal_verified.jpg?1227893291" /></a> <a href="http://www.facebook.com/pages/National-Event-Company-Necocom/25632242064?popup=true" onclick="window.open(this.href);return false;" style="position: relative; bottom: 5px;"><img alt="Facebook_logo" src="http://assets0.neco.com/images/facebook_logo.jpg?1227893291" /></a> </div> </div> </div> </div> </body> </html>
neco/twitter.neco.com
12133c9c6883cbbc7a2b7f864adaec309b6169d7
added twitter to footer
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 5a8a57c..2573346 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,116 +1,116 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> National Event Company Twitter Updates - Home </title> <link href="stylesheets/base.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/twitter.css" rel="stylesheet" type="text/css" /> <!--[if IE]> <link href="stylesheets/base_ie.css" rel="stylesheet" type="text/css" /> <![endif]--> </head> <body class="fixed blue"> <div id="bg"> <div id="container"> <div id="header"> <a title="Home" id="home" href="http://www.neco.com/"></a> <div id="top_right_container"> <div id="top_right"> <a href="http://www.neco.com/orders">Order Status</a>  |  <a href="http://www.neco.com/register">Register</a>  |  <a href="http://www.neco.com/password_resets/new">Forgot password?</a>  |  <a href="http://www.neco.com/help">Help</a>  |   <div class="spacer1"></div> </div> </div> <table cellspacing="0" cellpadding="0" id="top_nav"> <tbody><tr> <td><a href="http://www.neco.com/"><span class="left"><span class="right">Tickets</span></span></a></td> <td><a href="http://www.neco.com/event_packages"><span class="left"><span class="right">Event Packages</span></span></a></td> <td><a href="http://blog.neco.com"><span class="left"><span class="right">Blog</span></span></a></td> <td><a class="hover" href="http://twitter.neco.com"><span class="left"><span class="right">Twitter</span></span></a></td> </tr> </tbody></table> <div id="phone_number"><img src="http://assets1.neco.com/images/phone_icon.jpg" alt="Phone_icon"/>866-NECO-TIX (632-6849)</div> </div> <div id="content_top"> <div id="content_right"> <div id="content_bottom"> <div id="content_left"> <div id="content_top_left"> <div id="content_top_right"> <div id="content_bottom_right"> <div id="content_bottom_left"> <table cellspacing="0" cellpadding="0" id="content_middle"> <tbody><tr> <td id="content_middle_cell"> <div id="neco_content"> <%= yield %> </div> </td> </tr> </tbody></table> </div> </div> </div> </div> </div> </div> </div> </div> <div id="footer"> <div id="jargon"> - <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> + <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|<a href="http://twitter.neco.com">Twitter</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> <div class="spacer2"></div> <a href="http://www.neco.com/contact">Contact Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/about">About Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/why">Why Us?</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/employment">Employment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/affiliate_groups/new">Affiliates</a> <div class="spacer3"></div></div> <div id="contact_info">866-NECO-TIX (632-6849)&nbsp;&nbsp;|&nbsp;&nbsp;1430 Broadway, 7th Floor, New York, NY 10018</div> <div id="legal"> Copyright &copy; 2008, National Event Company II LLC, All Rights Reserved<br /> <a href="http://www.neco.com/terms">Terms &amp; Conditions</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/privacy_policy">Privacy Policy</a> </div> </div> <div id="seals"> <a href="http://www.bbbonline.org/cks.asp?id=1080620144110&amp;popup=true" onclick="window.open(this.href,'bbb','bbb');return false;" style="position: relative; bottom: 7px;"><img alt="BBB Seal" src="http://assets2.neco.com/images/bbbseal.gif?1227893291" /></a> <a href="https://seal.godaddy.com/verifySeal?sealID=2082029625050c04df7127112c49aa7e517fcb04658573943778635413&amp;popup=true" onclick="window.open(this.href,'godaddy_ssl','height=620,width=536');return false;"><img alt="Godaddy_ssl" src="http://assets2.neco.com/images/godaddy_ssl.jpg?1227893291" /></a> <img alt="Credit_card_logos" src="http://assets2.neco.com/images/credit_card_logos.jpg?1227893291" /> <a href="https://www.paypal.com/us/verified/pal=paypal%40neco%2ecom?popup=true" onclick="window.open(this.href,'paypal_verified','paypal_verified');return false;"><img alt="Paypal_verified" src="http://assets2.neco.com/images/paypal_verified.jpg?1227893291" /></a> <a href="http://www.facebook.com/pages/National-Event-Company-Necocom/25632242064?popup=true" onclick="window.open(this.href);return false;" style="position: relative; bottom: 5px;"><img alt="Facebook_logo" src="http://assets0.neco.com/images/facebook_logo.jpg?1227893291" /></a> </div> </div> </div> </div> </body> </html>
neco/twitter.neco.com
ee75c52e5ad7b0001f341852c89e4dbc5952d203
added blog tab to layout
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 2606090..5a8a57c 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,115 +1,116 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> National Event Company Twitter Updates - Home </title> <link href="stylesheets/base.css" rel="stylesheet" type="text/css" /> <link href="stylesheets/twitter.css" rel="stylesheet" type="text/css" /> <!--[if IE]> <link href="stylesheets/base_ie.css" rel="stylesheet" type="text/css" /> <![endif]--> </head> <body class="fixed blue"> <div id="bg"> <div id="container"> <div id="header"> <a title="Home" id="home" href="http://www.neco.com/"></a> <div id="top_right_container"> <div id="top_right"> <a href="http://www.neco.com/orders">Order Status</a>  |  <a href="http://www.neco.com/register">Register</a>  |  <a href="http://www.neco.com/password_resets/new">Forgot password?</a>  |  <a href="http://www.neco.com/help">Help</a>  |   <div class="spacer1"></div> </div> </div> <table cellspacing="0" cellpadding="0" id="top_nav"> <tbody><tr> <td><a href="http://www.neco.com/"><span class="left"><span class="right">Tickets</span></span></a></td> <td><a href="http://www.neco.com/event_packages"><span class="left"><span class="right">Event Packages</span></span></a></td> + <td><a href="http://blog.neco.com"><span class="left"><span class="right">Blog</span></span></a></td> <td><a class="hover" href="http://twitter.neco.com"><span class="left"><span class="right">Twitter</span></span></a></td> </tr> </tbody></table> <div id="phone_number"><img src="http://assets1.neco.com/images/phone_icon.jpg" alt="Phone_icon"/>866-NECO-TIX (632-6849)</div> </div> <div id="content_top"> <div id="content_right"> <div id="content_bottom"> <div id="content_left"> <div id="content_top_left"> <div id="content_top_right"> <div id="content_bottom_right"> <div id="content_bottom_left"> <table cellspacing="0" cellpadding="0" id="content_middle"> <tbody><tr> <td id="content_middle_cell"> <div id="neco_content"> <%= yield %> </div> </td> </tr> </tbody></table> </div> </div> </div> </div> </div> </div> </div> </div> <div id="footer"> <div id="jargon"> <div id="nav"><a href="http://www.neco.com/tickets">Tickets</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/event_packages">Event Packages</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://blog.neco.com">Blog</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/help">Help</a> <div class="spacer2"></div> <a href="http://www.neco.com/contact">Contact Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/about">About Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/why">Why Us?</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/employment">Employment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/affiliate_groups/new">Affiliates</a> <div class="spacer3"></div></div> <div id="contact_info">866-NECO-TIX (632-6849)&nbsp;&nbsp;|&nbsp;&nbsp;1430 Broadway, 7th Floor, New York, NY 10018</div> <div id="legal"> Copyright &copy; 2008, National Event Company II LLC, All Rights Reserved<br /> <a href="http://www.neco.com/terms">Terms &amp; Conditions</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="http://www.neco.com/privacy_policy">Privacy Policy</a> </div> </div> <div id="seals"> <a href="http://www.bbbonline.org/cks.asp?id=1080620144110&amp;popup=true" onclick="window.open(this.href,'bbb','bbb');return false;" style="position: relative; bottom: 7px;"><img alt="BBB Seal" src="http://assets2.neco.com/images/bbbseal.gif?1227893291" /></a> <a href="https://seal.godaddy.com/verifySeal?sealID=2082029625050c04df7127112c49aa7e517fcb04658573943778635413&amp;popup=true" onclick="window.open(this.href,'godaddy_ssl','height=620,width=536');return false;"><img alt="Godaddy_ssl" src="http://assets2.neco.com/images/godaddy_ssl.jpg?1227893291" /></a> <img alt="Credit_card_logos" src="http://assets2.neco.com/images/credit_card_logos.jpg?1227893291" /> <a href="https://www.paypal.com/us/verified/pal=paypal%40neco%2ecom?popup=true" onclick="window.open(this.href,'paypal_verified','paypal_verified');return false;"><img alt="Paypal_verified" src="http://assets2.neco.com/images/paypal_verified.jpg?1227893291" /></a> <a href="http://www.facebook.com/pages/National-Event-Company-Necocom/25632242064?popup=true" onclick="window.open(this.href);return false;" style="position: relative; bottom: 5px;"><img alt="Facebook_logo" src="http://assets0.neco.com/images/facebook_logo.jpg?1227893291" /></a> </div> </div> </div> </div> </body> </html>
neco/twitter.neco.com
b6c85b5887d4ef50c5deb6f8410a31f021931bde
added dependent destroy
diff --git a/app/models/twitter_user.rb b/app/models/twitter_user.rb index a725e10..695829b 100644 --- a/app/models/twitter_user.rb +++ b/app/models/twitter_user.rb @@ -1,3 +1,3 @@ class TwitterUser < ActiveRecord::Base - has_many :tweets, :order => 'tweets.tweeted_at desc' + has_many :tweets, :order => 'tweets.tweeted_at desc', :dependent => :destroy end
benben/shuffle
621d539496aa7eae60da4d28c69c96ec1ca1bd04
made the code easier with modulo
diff --git a/shuffle.pde b/shuffle.pde index 2d24810..4509905 100644 --- a/shuffle.pde +++ b/shuffle.pde @@ -1,129 +1,119 @@ /* * This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ * or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. */ //how many frames between spawning of triangles int interval = 15; //speed float speed = 2.8; //randomness 1 float s = 50.0; //randomness 2 float r = 50.0; //maximum amount of triangles -int NUM = 50; +int NUM = 20; int count; Triangles[] myTriangles = new Triangles[NUM]; float x,y,ratio; boolean flip; void setup() { size(1280, 720, P2D); frameRate(30); textMode(SCREEN); smooth(); ratio = (float)width / (float)height; } void draw() { - + if (frameCount % interval == 0) { - //this is just for the first creation - if (myTriangles[0] == null) { - myTriangles[count] = new Triangles(); + //this is just for the first creation + if (myTriangles[0] == null) { + myTriangles[0] = new Triangles(); } else { //if there is one or more object, create one as successor - myTriangles[count] = new Triangles(myTriangles[getAncestor(count)].getVectors()); - } - count++; - if(count == NUM) { - count = 0; + myTriangles[count%NUM] = new Triangles(myTriangles[(count - 1)%NUM].getVectors()); } + count++; } - + background(0); fill(255, 255, 255); text((int)frameRate + " fps",10,20); noStroke(); - + x = frameCount*speed*ratio; y = frameCount*speed; - + translate(-x,-y); if(myTriangles[NUM-1] == null) { for (int i = 0; i < count; i++) { myTriangles[i].drawtri(); } } else { for (int i = 0; i < NUM; i++) { myTriangles[i].drawtri(); } - } + } } class Triangles { PVector v1 = new PVector(x+(width -100) + random(s),y+(height)+random(s)); PVector v2 = new PVector(x+(width) + random(s),y+(height -100)+random(s)); PVector v3 = v2; PVector c = new PVector(random(255),random(255),random(255)); Triangles () { } Triangles (PVector[] ancestor) { v1 = ancestor[0]; v2 = ancestor[1]; if(flip) { v3 = new PVector(x+(width - 100 - random(r)) + random(s),y+(height)+random(s)); - } else { + } + else { v3 = new PVector(x+(width) + random(s),y+(height - 100 - random(r))+random(s)); } } PVector getLastVector() { return v3; } PVector[] getVectors() { PVector[] returnVector = new PVector[2]; //return the two vectors for touching randomly //just return the two vectors from the new positions (which means including v3) if(flip) { returnVector[1] = v2; returnVector[0] = v3; flip = false; - } else { + } + else { returnVector[0] = v1; returnVector[1] = v3; flip = true; } return returnVector; } void drawtri() { beginShape(TRIANGLES); fill(c.x, c.y, c.z); vertex(v1.x, v1.y); vertex(v2.x, v2.y); vertex(v3.x, v3.y); endShape(); } } - -int getAncestor(int i) { - if(i == 0) { - return NUM - 1; - } - else { - return i - 1; - } -}
benben/shuffle
eac433577ec1f44e5e03c22eb57bb6d862d2cb39
cleaned up the code and put everything in parameters
diff --git a/shuffle.pde b/shuffle.pde index 1098060..2d24810 100644 --- a/shuffle.pde +++ b/shuffle.pde @@ -1,124 +1,129 @@ /* * This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ * or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. */ -//how fast will the triangles be spawned -int interval = 500; +//how many frames between spawning of triangles +int interval = 15; +//speed +float speed = 2.8; +//randomness 1 +float s = 50.0; +//randomness 2 +float r = 50.0; //maximum amount of triangles int NUM = 50; -int a; -long previousMillis = 0; + + +int count; Triangles[] myTriangles = new Triangles[NUM]; float x,y,ratio; boolean flip; void setup() { size(1280, 720, P2D); frameRate(30); textMode(SCREEN); smooth(); ratio = (float)width / (float)height; } void draw() { - if (frameCount % 5 == 0) + + if (frameCount % interval == 0) { - previousMillis = millis(); - - //this is just for the first creation + //this is just for the first creation if (myTriangles[0] == null) { - myTriangles[a] = new Triangles(); + myTriangles[count] = new Triangles(); } else { //if there is one or more object, create one as successor - myTriangles[a] = new Triangles(myTriangles[getAncestor(a)].getVectors()); + myTriangles[count] = new Triangles(myTriangles[getAncestor(count)].getVectors()); } - a++; - if(a == NUM) { - a = 0; + count++; + if(count == NUM) { + count = 0; } } background(0); fill(255, 255, 255); text((int)frameRate + " fps",10,20); noStroke(); - x = frameCount*2.8*ratio; - y = frameCount*2.8; + x = frameCount*speed*ratio; + y = frameCount*speed; translate(-x,-y); if(myTriangles[NUM-1] == null) { - for (int i = 0; i < a; i++) { + for (int i = 0; i < count; i++) { myTriangles[i].drawtri(); } } else { for (int i = 0; i < NUM; i++) { myTriangles[i].drawtri(); } } } class Triangles { - int s = 10; PVector v1 = new PVector(x+(width -100) + random(s),y+(height)+random(s)); PVector v2 = new PVector(x+(width) + random(s),y+(height -100)+random(s)); - PVector v3 = new PVector(x+(width -100) + random(s),y+(height)+random(s)); + PVector v3 = v2; PVector c = new PVector(random(255),random(255),random(255)); Triangles () { } Triangles (PVector[] ancestor) { v1 = ancestor[0]; v2 = ancestor[1]; if(flip) { - v3 = new PVector(x+(width -100) + random(s),y+(height)+random(s)); + v3 = new PVector(x+(width - 100 - random(r)) + random(s),y+(height)+random(s)); } else { - v3 = new PVector(x+(width) + random(s),y+(height -100)+random(s)); + v3 = new PVector(x+(width) + random(s),y+(height - 100 - random(r))+random(s)); } } PVector getLastVector() { return v3; } PVector[] getVectors() { PVector[] returnVector = new PVector[2]; //return the two vectors for touching randomly //just return the two vectors from the new positions (which means including v3) if(flip) { returnVector[1] = v2; returnVector[0] = v3; flip = false; } else { returnVector[0] = v1; returnVector[1] = v3; flip = true; } return returnVector; } void drawtri() { beginShape(TRIANGLES); fill(c.x, c.y, c.z); vertex(v1.x, v1.y); vertex(v2.x, v2.y); vertex(v3.x, v3.y); endShape(); } } int getAncestor(int i) { if(i == 0) { return NUM - 1; } else { return i - 1; } }
benben/shuffle
7bf6e2cd773b95f7769f50112bf995e2cf33ce8b
switched from time based to frame based animation, improved the spawning for a better ribbon
diff --git a/shuffle.pde b/shuffle.pde index b082c43..1098060 100644 --- a/shuffle.pde +++ b/shuffle.pde @@ -1,119 +1,124 @@ /* * This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ * or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. */ //how fast will the triangles be spawned int interval = 500; //maximum amount of triangles -int NUM = 30; +int NUM = 50; int a; long previousMillis = 0; Triangles[] myTriangles = new Triangles[NUM]; -float x,y; +float x,y,ratio; +boolean flip; void setup() { size(1280, 720, P2D); frameRate(30); textMode(SCREEN); smooth(); + ratio = (float)width / (float)height; } void draw() { - if (millis() - previousMillis > interval ) + if (frameCount % 5 == 0) { previousMillis = millis(); //this is just for the first creation if (myTriangles[0] == null) { myTriangles[a] = new Triangles(); } else { //if there is one or more object, create one as successor myTriangles[a] = new Triangles(myTriangles[getAncestor(a)].getVectors()); } a++; if(a == NUM) { a = 0; } } background(0); fill(255, 255, 255); text((int)frameRate + " fps",10,20); noStroke(); - x = millis() / (12 * 0.6); - y = millis() / 12; + x = frameCount*2.8*ratio; + y = frameCount*2.8; + translate(-x,-y); - if(myTriangles[NUM-1] == null) { for (int i = 0; i < a; i++) { myTriangles[i].drawtri(); } } else { for (int i = 0; i < NUM; i++) { myTriangles[i].drawtri(); } } } class Triangles { - int s = interval / 5; - PVector v1 = new PVector(x + width - 100,y + height - 100); - PVector v2 = new PVector(v1.x + random(s),v1.y + random(s)); - PVector v3 = new PVector(v1.x + random(s),v1.y + random(s)); + int s = 10; + PVector v1 = new PVector(x+(width -100) + random(s),y+(height)+random(s)); + PVector v2 = new PVector(x+(width) + random(s),y+(height -100)+random(s)); + PVector v3 = new PVector(x+(width -100) + random(s),y+(height)+random(s)); PVector c = new PVector(random(255),random(255),random(255)); Triangles () { } Triangles (PVector[] ancestor) { v1 = ancestor[0]; - v2 = ancestor[1]; - v3 = new PVector(x + (width -160) + random(s * 1.6),y + (height -100) + random(s)); + v2 = ancestor[1]; + if(flip) { + v3 = new PVector(x+(width -100) + random(s),y+(height)+random(s)); + } else { + v3 = new PVector(x+(width) + random(s),y+(height -100)+random(s)); + } } PVector getLastVector() { return v3; } PVector[] getVectors() { PVector[] returnVector = new PVector[2]; //return the two vectors for touching randomly //just return the two vectors from the new positions (which means including v3) - switch((int)random(1)) { - case 0: - returnVector[0] = v2; - returnVector[1] = v3; - break; - case 1: + if(flip) { + returnVector[1] = v2; + returnVector[0] = v3; + flip = false; + } else { returnVector[0] = v1; returnVector[1] = v3; - break; + flip = true; } return returnVector; } void drawtri() { beginShape(TRIANGLES); fill(c.x, c.y, c.z); vertex(v1.x, v1.y); vertex(v2.x, v2.y); vertex(v3.x, v3.y); endShape(); } } int getAncestor(int i) { if(i == 0) { return NUM - 1; } else { return i - 1; } }
benben/shuffle
4189a44d13540c0b9fc7654abf607d5316b85002
improved better switch for the first drawings
diff --git a/shuffle.pde b/shuffle.pde index 80eabb5..b082c43 100644 --- a/shuffle.pde +++ b/shuffle.pde @@ -1,121 +1,119 @@ /* * This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ * or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. */ //how fast will the triangles be spawned int interval = 500; //maximum amount of triangles int NUM = 30; int a; long previousMillis = 0; Triangles[] myTriangles = new Triangles[NUM]; float x,y; -boolean test = false; void setup() { size(1280, 720, P2D); frameRate(30); textMode(SCREEN); smooth(); } void draw() { if (millis() - previousMillis > interval ) { previousMillis = millis(); //this is just for the first creation - if (a < 1 && !test) { + if (myTriangles[0] == null) { myTriangles[a] = new Triangles(); } else { //if there is one or more object, create one as successor myTriangles[a] = new Triangles(myTriangles[getAncestor(a)].getVectors()); } a++; if(a == NUM) { - a = 0; - test = true; + a = 0; } } background(0); fill(255, 255, 255); text((int)frameRate + " fps",10,20); noStroke(); x = millis() / (12 * 0.6); y = millis() / 12; translate(-x,-y); - - if(!test) { + + if(myTriangles[NUM-1] == null) { for (int i = 0; i < a; i++) { myTriangles[i].drawtri(); } } else { for (int i = 0; i < NUM; i++) { myTriangles[i].drawtri(); } } } class Triangles { int s = interval / 5; PVector v1 = new PVector(x + width - 100,y + height - 100); PVector v2 = new PVector(v1.x + random(s),v1.y + random(s)); PVector v3 = new PVector(v1.x + random(s),v1.y + random(s)); PVector c = new PVector(random(255),random(255),random(255)); Triangles () { } Triangles (PVector[] ancestor) { v1 = ancestor[0]; v2 = ancestor[1]; v3 = new PVector(x + (width -160) + random(s * 1.6),y + (height -100) + random(s)); } PVector getLastVector() { return v3; } PVector[] getVectors() { PVector[] returnVector = new PVector[2]; //return the two vectors for touching randomly //just return the two vectors from the new positions (which means including v3) switch((int)random(1)) { case 0: returnVector[0] = v2; returnVector[1] = v3; break; case 1: returnVector[0] = v1; returnVector[1] = v3; break; } return returnVector; } void drawtri() { beginShape(TRIANGLES); fill(c.x, c.y, c.z); vertex(v1.x, v1.y); vertex(v2.x, v2.y); vertex(v3.x, v3.y); endShape(); } } int getAncestor(int i) { if(i == 0) { return NUM - 1; } else { return i - 1; } }
benben/shuffle
dbbb6a0f1d35945fa20415650f73fbb9001ff7a3
added cc license
diff --git a/shuffle.pde b/shuffle.pde index 83517bc..80eabb5 100644 --- a/shuffle.pde +++ b/shuffle.pde @@ -1,115 +1,121 @@ +/* + * This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. + * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ + * or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. + */ + //how fast will the triangles be spawned int interval = 500; //maximum amount of triangles int NUM = 30; int a; long previousMillis = 0; Triangles[] myTriangles = new Triangles[NUM]; float x,y; boolean test = false; void setup() { size(1280, 720, P2D); frameRate(30); textMode(SCREEN); smooth(); } void draw() { if (millis() - previousMillis > interval ) { previousMillis = millis(); //this is just for the first creation if (a < 1 && !test) { myTriangles[a] = new Triangles(); } else { //if there is one or more object, create one as successor myTriangles[a] = new Triangles(myTriangles[getAncestor(a)].getVectors()); } a++; if(a == NUM) { a = 0; test = true; } } background(0); fill(255, 255, 255); text((int)frameRate + " fps",10,20); noStroke(); x = millis() / (12 * 0.6); y = millis() / 12; translate(-x,-y); if(!test) { for (int i = 0; i < a; i++) { myTriangles[i].drawtri(); } } else { for (int i = 0; i < NUM; i++) { myTriangles[i].drawtri(); } } } class Triangles { int s = interval / 5; PVector v1 = new PVector(x + width - 100,y + height - 100); PVector v2 = new PVector(v1.x + random(s),v1.y + random(s)); PVector v3 = new PVector(v1.x + random(s),v1.y + random(s)); PVector c = new PVector(random(255),random(255),random(255)); Triangles () { } Triangles (PVector[] ancestor) { v1 = ancestor[0]; v2 = ancestor[1]; v3 = new PVector(x + (width -160) + random(s * 1.6),y + (height -100) + random(s)); } PVector getLastVector() { return v3; } PVector[] getVectors() { PVector[] returnVector = new PVector[2]; //return the two vectors for touching randomly //just return the two vectors from the new positions (which means including v3) switch((int)random(1)) { case 0: returnVector[0] = v2; returnVector[1] = v3; break; case 1: returnVector[0] = v1; returnVector[1] = v3; break; } return returnVector; } void drawtri() { beginShape(TRIANGLES); fill(c.x, c.y, c.z); vertex(v1.x, v1.y); vertex(v2.x, v2.y); vertex(v3.x, v3.y); endShape(); } } int getAncestor(int i) { if(i == 0) { return NUM - 1; } else { return i - 1; } }
benben/shuffle
1aaee8e7c3e2ce404c5e07f1ed7a0d54b8468583
first version of the basic animation
diff --git a/shuffle.pde b/shuffle.pde new file mode 100644 index 0000000..83517bc --- /dev/null +++ b/shuffle.pde @@ -0,0 +1,115 @@ +//how fast will the triangles be spawned +int interval = 500; +//maximum amount of triangles +int NUM = 30; + +int a; +long previousMillis = 0; +Triangles[] myTriangles = new Triangles[NUM]; +float x,y; +boolean test = false; + +void setup() { + size(1280, 720, P2D); + frameRate(30); + textMode(SCREEN); + smooth(); +} + +void draw() { + if (millis() - previousMillis > interval ) + { + previousMillis = millis(); + + //this is just for the first creation + if (a < 1 && !test) { + myTriangles[a] = new Triangles(); + } + else { + //if there is one or more object, create one as successor + myTriangles[a] = new Triangles(myTriangles[getAncestor(a)].getVectors()); + } + a++; + if(a == NUM) { + a = 0; + test = true; + } + } + + background(0); + fill(255, 255, 255); + text((int)frameRate + " fps",10,20); + noStroke(); + + x = millis() / (12 * 0.6); + y = millis() / 12; + translate(-x,-y); + + if(!test) { + for (int i = 0; i < a; i++) { + myTriangles[i].drawtri(); + } + } + else { + for (int i = 0; i < NUM; i++) { + myTriangles[i].drawtri(); + } + } +} + +class Triangles { + int s = interval / 5; + PVector v1 = new PVector(x + width - 100,y + height - 100); + PVector v2 = new PVector(v1.x + random(s),v1.y + random(s)); + PVector v3 = new PVector(v1.x + random(s),v1.y + random(s)); + PVector c = new PVector(random(255),random(255),random(255)); + + Triangles () { + } + + Triangles (PVector[] ancestor) { + v1 = ancestor[0]; + v2 = ancestor[1]; + v3 = new PVector(x + (width -160) + random(s * 1.6),y + (height -100) + random(s)); + } + + PVector getLastVector() { + return v3; + } + + PVector[] getVectors() { + PVector[] returnVector = new PVector[2]; + //return the two vectors for touching randomly + //just return the two vectors from the new positions (which means including v3) + switch((int)random(1)) { + case 0: + returnVector[0] = v2; + returnVector[1] = v3; + break; + case 1: + returnVector[0] = v1; + returnVector[1] = v3; + break; + } + + return returnVector; + } + + void drawtri() { + beginShape(TRIANGLES); + fill(c.x, c.y, c.z); + vertex(v1.x, v1.y); + vertex(v2.x, v2.y); + vertex(v3.x, v3.y); + endShape(); + } +} + +int getAncestor(int i) { + if(i == 0) { + return NUM - 1; + } + else { + return i - 1; + } +}
straup/osm-tools
ed9be16f295309a3c388acea1f0e31554bc2a2da
add support for Lines; stop using liljson because python :-(
diff --git a/ways-to-geojson.py b/ways-to-geojson.py index 7bab621..321adef 100755 --- a/ways-to-geojson.py +++ b/ways-to-geojson.py @@ -1,153 +1,165 @@ #!/usr/bin/env python import sys import urllib import xml.etree.ElementTree as xml import json import re import logging import liljson def nodes_for_way(id): url = 'http://www.openstreetmap.org/api/0.6/way/%s' % id logging.debug("fetch way %s" % url) nodes = [] rsp = urllib.urlopen(url) tree = xml.fromstring(rsp.read()) for nd in tree.findall('*//nd'): attrs = nd.attrib nodes.append(attrs['ref']) return nodes def coords_for_node(id): url = 'http://www.openstreetmap.org/api/0.6/node/%s' % id logging.debug("fetch node %s" % url) rsp = urllib.urlopen(url) tree = xml.fromstring(rsp.read()) node = tree.find('node') attrs = node.attrib return ( float(attrs['lon']), float(attrs['lat']) ) def ways_to_geojson(ids, precision=2): features = [] for id in ids: nodes = nodes_for_way(id) coords = [] swlat = None swlon = None nelat = None nelon = None for n in nodes: pt = coords_for_node(n) coords.append(pt) if swlat: swlat = min(swlat, pt[1]) else: swlat = pt[1] if swlon: swlon = min(swlat, pt[0]) else: swlon = pt[0] if nelat: nelat = max(nelat, pt[1]) else: nelat = pt[1] if nelon: nelon = max(nelon, pt[0]) else: nelon = pt[0] bbox = [ swlon, swlat, nelon, nelat ] # TO DO: check to see if this a closed set of # coordinates or not... - type = 'Polygon' + first = coords[0] + last = coords[-1] + + if first[0] == last[0] and first[1] == last[1]: + type = 'Polygon' + coords = [ coords ] + else: + type = 'LineString' properties = { 'id': id } geom = { 'type': type, - 'coordinates': [ coords ] + 'coordinates': coords } feature = { 'type': 'Feature', 'bbox': bbox, 'properties': properties, 'geometry' : geom } features.append(feature) geojson = { 'type': 'FeatureCollection', 'features': features } return geojson if __name__ == '__main__': import optparse parser = optparse.OptionParser(usage="python ways-to-geojson.py --options way-ids") parser.add_option('--path', dest='path', help='Where to write your GeoJSON file. Default filename is the concationation of all the way IDs, dot json.', action='store') parser.add_option('--precision', dest='precision', help='The decimal precision for your GeoJSON file. Default is 6.', action='store', default=None) parser.add_option('--indent', dest='indent', help='Indent your GeoJSON file. Default is false.', action='store_true', default=False) parser.add_option('--debug', dest='debug', help='Enable debug logging', action='store_true', default=False) options, ids = parser.parse_args() if options.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) if len(ids) == 0: logging.error("missing way IDs") sys.exit() output = options.path and open(options.path, 'w') or sys.stdout data = ways_to_geojson(ids, options.precision) - liljson.write_liljson(data, output, options.precision) + args = {} + + if options.indent: + args['indent'] = options.indent + + json.dump(data, output, indent=2) logging.info("done")
straup/osm-tools
40c95797adddd8745115eaf585a80e3394ff2734
use liljson to do all the writing (this means no indenting but one thing at a time...)
diff --git a/liljson.py b/liljson.py new file mode 100755 index 0000000..8a0c0ac --- /dev/null +++ b/liljson.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python + +# https://github.com/straup/LilJSON + +from sys import stdin, stdout +from json import load, JSONEncoder +from optparse import OptionParser +from re import compile + +defaults = dict(precision=3) + +float_pat = compile(r'^-?\d+\.\d+(e-?\d+)?$') +charfloat_pat = compile(r'^[\[,\,]-?\d+\.\d+(e-?\d+)?$') + +def write_liljson(data, output, precision): + + args = { 'separators': (',', ':') } + + encoder = JSONEncoder(**args) + encoded = encoder.iterencode(data) + + format = '%.' + str(precision) + 'f' + + for token in encoded: + + if charfloat_pat.match(token): + # in python 2.7, we see a character followed by a float literal + output.write(token[0] + format % float(token[1:])) + + elif float_pat.match(token): + # in python 2.6, we see a simple float literal + output.write(format % float(token)) + + else: + output.write(token) + +if __name__ == '__main__': + + parser = OptionParser(usage="""%prog [options] + +Make JSON smaller by reducing precision of floating point values +and removing white space. Works great for GeoJSON! + +Examples: + cat input.json | python %prog --precision 2 > output.json + python %prog --precision 2 input.json > output.json + python %prog -p 2 input.json output.json""") + + parser.set_defaults(**defaults) + + parser.add_option('-p', '--precision', dest='precision', + type='int', help='Digits of precision, default %(precision)d.' % defaults) + + options, args = parser.parse_args() + + # + # Read! + # + + input = len(args) and open(args[0], 'r') or stdin + output = len(args) >= 2 and open(args[1], 'w') or stdout + + data = load(input) + + write_liljson(data, output, options.precision) diff --git a/ways-to-geojson.py b/ways-to-geojson.py index 435504b..7bab621 100755 --- a/ways-to-geojson.py +++ b/ways-to-geojson.py @@ -1,181 +1,153 @@ #!/usr/bin/env python import sys import urllib import xml.etree.ElementTree as xml import json import re import logging - -def write_json(data, path, precision=6, indent=False): - - logging.debug("write data to %s" % path) - - kwargs = {} - - if indent: - kwargs['indent'] = 2 - - float_pat = re.compile(r'^-?\d+\.\d+(e-?\d+)?$') - - fh = open(path, 'w') - - encoder = json.JSONEncoder(**kwargs) - encoded = encoder.iterencode(data) - - format = '%.' + str(precision) + 'f' - - for token in encoded: - if float_pat.match(token): - fh.write(format % float(token)) - else: - fh.write(token) - - fh.close() +import liljson def nodes_for_way(id): url = 'http://www.openstreetmap.org/api/0.6/way/%s' % id logging.debug("fetch way %s" % url) nodes = [] rsp = urllib.urlopen(url) tree = xml.fromstring(rsp.read()) for nd in tree.findall('*//nd'): attrs = nd.attrib nodes.append(attrs['ref']) return nodes def coords_for_node(id): url = 'http://www.openstreetmap.org/api/0.6/node/%s' % id logging.debug("fetch node %s" % url) rsp = urllib.urlopen(url) tree = xml.fromstring(rsp.read()) node = tree.find('node') attrs = node.attrib return ( float(attrs['lon']), float(attrs['lat']) ) -def ways_to_geojson(ids): +def ways_to_geojson(ids, precision=2): features = [] for id in ids: nodes = nodes_for_way(id) coords = [] swlat = None swlon = None nelat = None nelon = None for n in nodes: pt = coords_for_node(n) coords.append(pt) if swlat: swlat = min(swlat, pt[1]) else: swlat = pt[1] if swlon: swlon = min(swlat, pt[0]) else: swlon = pt[0] if nelat: nelat = max(nelat, pt[1]) else: nelat = pt[1] if nelon: nelon = max(nelon, pt[0]) else: nelon = pt[0] bbox = [ swlon, swlat, nelon, nelat ] # TO DO: check to see if this a closed set of # coordinates or not... type = 'Polygon' properties = { 'id': id } geom = { 'type': type, 'coordinates': [ coords ] } feature = { 'type': 'Feature', 'bbox': bbox, 'properties': properties, 'geometry' : geom } features.append(feature) geojson = { 'type': 'FeatureCollection', 'features': features } return geojson if __name__ == '__main__': import optparse parser = optparse.OptionParser(usage="python ways-to-geojson.py --options way-ids") parser.add_option('--path', dest='path', help='Where to write your GeoJSON file. Default filename is the concationation of all the way IDs, dot json.', action='store') parser.add_option('--precision', dest='precision', help='The decimal precision for your GeoJSON file. Default is 6.', action='store', default=None) parser.add_option('--indent', dest='indent', help='Indent your GeoJSON file. Default is false.', action='store_true', default=False) parser.add_option('--debug', dest='debug', help='Enable debug logging', action='store_true', default=False) options, ids = parser.parse_args() if options.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) if len(ids) == 0: logging.error("missing way IDs") sys.exit() - if options.path: - path = options.path - else: - path = "-".join(ids) + ".json" + output = options.path and open(options.path, 'w') or sys.stdout - data = ways_to_geojson(ids) + data = ways_to_geojson(ids, options.precision) - write_json(data, path, options.precision, options.indent) + liljson.write_liljson(data, output, options.precision) logging.info("done")
straup/osm-tools
824a6666bfaff54d1294c112943f0478bb061a11
calculate bbox for features
diff --git a/ways-to-geojson.py b/ways-to-geojson.py index e13b46f..435504b 100755 --- a/ways-to-geojson.py +++ b/ways-to-geojson.py @@ -1,153 +1,181 @@ #!/usr/bin/env python import sys import urllib import xml.etree.ElementTree as xml import json import re - -import pprint import logging def write_json(data, path, precision=6, indent=False): logging.debug("write data to %s" % path) kwargs = {} if indent: kwargs['indent'] = 2 float_pat = re.compile(r'^-?\d+\.\d+(e-?\d+)?$') fh = open(path, 'w') encoder = json.JSONEncoder(**kwargs) encoded = encoder.iterencode(data) format = '%.' + str(precision) + 'f' for token in encoded: if float_pat.match(token): fh.write(format % float(token)) else: fh.write(token) fh.close() def nodes_for_way(id): url = 'http://www.openstreetmap.org/api/0.6/way/%s' % id logging.debug("fetch way %s" % url) nodes = [] rsp = urllib.urlopen(url) tree = xml.fromstring(rsp.read()) for nd in tree.findall('*//nd'): attrs = nd.attrib nodes.append(attrs['ref']) return nodes def coords_for_node(id): url = 'http://www.openstreetmap.org/api/0.6/node/%s' % id logging.debug("fetch node %s" % url) rsp = urllib.urlopen(url) tree = xml.fromstring(rsp.read()) node = tree.find('node') attrs = node.attrib return ( float(attrs['lon']), float(attrs['lat']) ) def ways_to_geojson(ids): features = [] for id in ids: nodes = nodes_for_way(id) coords = [] + swlat = None + swlon = None + nelat = None + nelon = None + for n in nodes: - coords.append(coords_for_node(n)) + + pt = coords_for_node(n) + coords.append(pt) + + if swlat: + swlat = min(swlat, pt[1]) + else: + swlat = pt[1] + + if swlon: + swlon = min(swlat, pt[0]) + else: + swlon = pt[0] + + if nelat: + nelat = max(nelat, pt[1]) + else: + nelat = pt[1] + + if nelon: + nelon = max(nelon, pt[0]) + else: + nelon = pt[0] + + bbox = [ swlon, swlat, nelon, nelat ] # TO DO: check to see if this a closed set of # coordinates or not... type = 'Polygon' properties = { 'id': id } geom = { 'type': type, 'coordinates': [ coords ] } feature = { 'type': 'Feature', + 'bbox': bbox, 'properties': properties, 'geometry' : geom } features.append(feature) geojson = { 'type': 'FeatureCollection', 'features': features } return geojson if __name__ == '__main__': import optparse parser = optparse.OptionParser(usage="python ways-to-geojson.py --options way-ids") parser.add_option('--path', dest='path', help='Where to write your GeoJSON file. Default filename is the concationation of all the way IDs, dot json.', action='store') parser.add_option('--precision', dest='precision', help='The decimal precision for your GeoJSON file. Default is 6.', action='store', default=None) parser.add_option('--indent', dest='indent', help='Indent your GeoJSON file. Default is false.', action='store_true', default=False) parser.add_option('--debug', dest='debug', help='Enable debug logging', action='store_true', default=False) options, ids = parser.parse_args() if options.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) if len(ids) == 0: logging.error("missing way IDs") sys.exit() if options.path: path = options.path else: path = "-".join(ids) + ".json" data = ways_to_geojson(ids) write_json(data, path, options.precision, options.indent) logging.info("done")
straup/osm-tools
ec9f5b9e27c30400ef0e726bb987bf971d0ee0a9
add ways-to-geojson
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f836aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*~ +*.pyc diff --git a/README.md b/README.md new file mode 100644 index 0000000..8e103db --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +osm-tools +== + +These are Aaron's tools for doing things with OSM data. diff --git a/mapfeature_extractor.README b/mapfeature_extractor.README deleted file mode 100644 index 05a25a5..0000000 --- a/mapfeature_extractor.README +++ /dev/null @@ -1,45 +0,0 @@ -NAME - mapfeature_extractor.pl - A CLI tool for generating a machine (tag) - readable dump of the OSM Map Features wiki page - -SYNOPSIS - $> mapfeature_extractor.pl -o /path/to/outfile - -DESCRIPTION - mapfeature_extractor.pl is a command-line tool for generating a machine - (tag) readable (JSON) dump of the OSM Map Features wiki page. - -OPTIONS - * o (outfile) - - The path to a file where the data should be written. - - Required. - - * d (description) - - Include OSM descriptions with each item. - - Optional. - -TO DO - * Generate output formats other than JSON - - * Include a "pretty print" option - - * Be smart about generating multiple entries for features whose values - are "foo / bar / baz" - - * Uh...stuff? - - <http://wiki.openstreetmap.org/wiki/Map_Features> - -AUTHOR - Aaron Straup Cope. - -LICENSE - Copyright (c) 2009 Aaron Straup Cope. All rights reserved. - - This is free software, you may use it and distribute it under the same - terms as Perl itself. - diff --git a/ways-to-geojson.py b/ways-to-geojson.py new file mode 100755 index 0000000..e13b46f --- /dev/null +++ b/ways-to-geojson.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python + +import sys +import urllib +import xml.etree.ElementTree as xml +import json +import re + +import pprint +import logging + +def write_json(data, path, precision=6, indent=False): + + logging.debug("write data to %s" % path) + + kwargs = {} + + if indent: + kwargs['indent'] = 2 + + float_pat = re.compile(r'^-?\d+\.\d+(e-?\d+)?$') + + fh = open(path, 'w') + + encoder = json.JSONEncoder(**kwargs) + encoded = encoder.iterencode(data) + + format = '%.' + str(precision) + 'f' + + for token in encoded: + if float_pat.match(token): + fh.write(format % float(token)) + else: + fh.write(token) + + fh.close() + +def nodes_for_way(id): + + url = 'http://www.openstreetmap.org/api/0.6/way/%s' % id + logging.debug("fetch way %s" % url) + + nodes = [] + + rsp = urllib.urlopen(url) + tree = xml.fromstring(rsp.read()) + + for nd in tree.findall('*//nd'): + attrs = nd.attrib + nodes.append(attrs['ref']) + + return nodes + +def coords_for_node(id): + + url = 'http://www.openstreetmap.org/api/0.6/node/%s' % id + logging.debug("fetch node %s" % url) + + rsp = urllib.urlopen(url) + tree = xml.fromstring(rsp.read()) + + node = tree.find('node') + attrs = node.attrib + + return ( + float(attrs['lon']), + float(attrs['lat']) + ) + +def ways_to_geojson(ids): + + features = [] + + for id in ids: + + nodes = nodes_for_way(id) + coords = [] + + for n in nodes: + coords.append(coords_for_node(n)) + + # TO DO: check to see if this a closed set of + # coordinates or not... + + type = 'Polygon' + + properties = { + 'id': id + } + + geom = { + 'type': type, + 'coordinates': [ coords ] + } + + feature = { + 'type': 'Feature', + 'properties': properties, + 'geometry' : geom + } + + features.append(feature) + + geojson = { + 'type': 'FeatureCollection', + 'features': features + } + + return geojson + +if __name__ == '__main__': + + import optparse + + parser = optparse.OptionParser(usage="python ways-to-geojson.py --options way-ids") + + parser.add_option('--path', dest='path', + help='Where to write your GeoJSON file. Default filename is the concationation of all the way IDs, dot json.', + action='store') + + parser.add_option('--precision', dest='precision', + help='The decimal precision for your GeoJSON file. Default is 6.', + action='store', default=None) + + parser.add_option('--indent', dest='indent', + help='Indent your GeoJSON file. Default is false.', + action='store_true', default=False) + + parser.add_option('--debug', dest='debug', + help='Enable debug logging', + action='store_true', default=False) + + options, ids = parser.parse_args() + + if options.debug: + logging.basicConfig(level=logging.DEBUG) + else: + logging.basicConfig(level=logging.INFO) + + if len(ids) == 0: + logging.error("missing way IDs") + sys.exit() + + if options.path: + path = options.path + else: + path = "-".join(ids) + ".json" + + data = ways_to_geojson(ids) + + write_json(data, path, options.precision, options.indent) + + logging.info("done")
kristianmandrup/proxy_party
09d3862fefe43411bf6305ff86dc6af956862d7b
Regenerate gemspec for version 0.2.2
diff --git a/proxy_party.gemspec b/proxy_party.gemspec index bea79bd..ef82be1 100644 --- a/proxy_party.gemspec +++ b/proxy_party.gemspec @@ -1,57 +1,57 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{proxy_party} - s.version = "0.2.1" + s.version = "0.2.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.authors = ["Kristian Mandrup"] - s.date = %q{2011-02-21} + s.authors = [%q{Kristian Mandrup}] + s.date = %q{2011-05-11} s.description = %q{Method missing proxy pattern} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.textile" ] s.files = [ ".document", ".rspec", "LICENSE", "README.textile", "Rakefile", "VERSION", "lib/proxy_party.rb", "proxy_party.gemspec", "spec/proxy_party_complex_spec.rb", "spec/proxy_party_spec.rb", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/kristianmandrup/proxy_party} - s.require_paths = ["lib"] - s.rubygems_version = %q{1.5.2} + s.require_paths = [%q{lib}] + s.rubygems_version = %q{1.8.0} s.summary = %q{Add proxy functionality the fun way} s.test_files = [ "spec/proxy_party_complex_spec.rb", "spec/proxy_party_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<sugar-high>, [">= 0.3.5"]) s.add_development_dependency(%q<rspec>, [">= 2.4.0"]) else s.add_dependency(%q<sugar-high>, [">= 0.3.5"]) s.add_dependency(%q<rspec>, [">= 2.4.0"]) end else s.add_dependency(%q<sugar-high>, [">= 0.3.5"]) s.add_dependency(%q<rspec>, [">= 2.4.0"]) end end
kristianmandrup/proxy_party
0ce8308f34bc9ee221520edace75672d004472ff
added single methods for proxying such as #proxy_accessor_for
diff --git a/README.textile b/README.textile index 5c1c943..b9cadc8 100644 --- a/README.textile +++ b/README.textile @@ -1,128 +1,135 @@ h1. Proxy Party Greatly facilitates adding proxies through the proxy method_missing pattern. Can now also dynamically add proxy methods and use other amazing meta strategies! h2. Install @$ gem install party_proxy@ h2. Use @require 'party_proxy'@ h2. Latest news Now supports renaming of proxy method so you can avoid method name collisions! h2. TODO Major DRYing up needed. Currently a lot of code duplication :O h2. Usage <pre> class State attr_accessor :name def initialize(name) @name = name end end class Info attr_accessor :text def initialize(text) @text = text end end module Party class Subject # proxy state and info objects to make their methods # directly accessible from subject objects proxy :state, :info def initialize(name) @state = State.new name @info = Info.new 'hello' end end end </pre> <pre> describe Party::Proxy do describe '#proxy' do it "proxies state and info so it can call name directly on subject" do subject = Party::Subject.new 'kristian' subject.name.should == 'kristian' end end describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' Party::Subject.proxy_for :mic, :speak_it! subject.proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end it "proxies speak_it! as speak_up! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' Party::Subject.proxy_for :mic, :rename => {:speak_it! => :speak_up!} subject.speak_up!.should == 'hello' end end describe '#proxy_accessor_for' do it "proxies speak accessor methods on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' - subject.proxy_accessors_for :mic, :speak + + # multi + subject.proxy_accessors_for :mic, :speak, :miau + + # single + subject.proxy_accessor_for :mic, :speak + subject.proxy_accessor_for :mic => :speak + subject.speak = 'do it!' subject.speak.should == 'do it!' end it "proxies speak accessor method on mic as yell" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.proxy_accessors_for :mic, :rename => {:speak => :yell} subject.yell = 'do it!' subject.yell.should == 'do it!' end end describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' end end end </pre> h2. Note on Patches/Pull Requests * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) * Send me a pull request. Bonus points for topic branches. h2. Copyright Copyright (c) 2010 Kristian Mandrup. See LICENSE for details. 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/lib/proxy_party.rb b/lib/proxy_party.rb index eb46f82..8849854 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,346 +1,364 @@ require 'sugar-high/array' require 'sugar-high/kind_of' require 'sugar-high/arguments' module Party module Proxy class Factory attr_reader :create_method, :klass def initialize klass, create_method = nil @klass = klass @create_method = create_method end def create create_method ? klass.send(create_method) : klass.new end end def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module InstanceMethods attr_accessor :proxy_factories def proxy_factory proxy_factories end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else case factory when Array fac = factory.first meth = factory.last if factory.size == 2 raise ArgumentError, "Factory must be a Class, was #{fac}" if !fac.kind_of?(Class) raise ArgumentError, "Factory method be a label, was #{meth}" if meth && !meth.kind_of_label? Party::Proxy::Factory.new(fac, meth) else raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to?(:create) factory end end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories # Add instance proxy methods def proxy_for obj, *methods check = last_arg_value({:check => false}, methods) rename_methods = last_arg_value({:rename => {}}, methods) methods.delete(:rename) if rename_methods methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end class_eval %{ define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end } end rename_methods.each_pair do |meth, new_meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end class_eval %{ define_method :#{new_meth} do #{obj}.send(:#{meth}) if #{obj} end } end end # Add instance proxy methods def proxy_accessors_for obj, *methods proxy_for obj, methods check = last_arg_value({:check => false}, methods) rename_methods = last_arg_value({:rename => {}}, methods) methods.delete(:rename) if rename_methods methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end class_eval %{ define_method :#{meth}= do |arg| self.#{obj} ||= create_in_factory(:#{obj}) self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) #{obj}.send(:#{meth}=, arg) if #{obj} end } end + def proxy_accessor_for obj, method = nil + method ||= obj[1] if obj.kind_of?(Hash) + raise ArgumentError, "Takes only a single accessor to proxy" if method.kind_of? Array + proxy_accessor_for obj, [method].flatten + end + rename_methods.each_pair do |meth, new_meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end class_eval %{ define_method :#{new_meth}= do |arg| self.#{obj} ||= create_in_factory(:#{obj}) self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) #{obj}.send(:#{meth}=, arg) if #{obj} end } end end # Add proxy methods only to the instance object def instance_proxy_for obj, *methods check = last_arg_value({:check => false}, methods) rename_methods = last_arg_value({:rename => {}}, methods) methods.delete(:rename) if rename_methods methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end end } end rename_methods.each_pair do |meth, new_meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{new_meth} do #{obj}.send(:#{meth}) if #{obj} end end } end end # Add proxy methods only to the instance object def instance_proxy_accessors_for obj, *methods instance_proxy_for obj, methods check = last_arg_value({:check => false}, methods) rename_methods = last_arg_value({:rename => {}}, methods) methods.delete(:rename) if rename_methods methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end instance_eval %{ class << self define_method :#{meth}= do |arg| self.#{obj} ||= create_in_factory(:#{obj}) self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) #{obj}.send(:#{meth}=, arg) if #{obj} end end } end rename_methods.each_pair do |meth, new_meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{new_meth}= do |arg| self.#{obj} ||= create_in_factory(:#{obj}) self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) #{obj}.send(:#{meth}=, arg) if #{obj} end end } end end + def instance_proxy_accessor_for obj, method = nil + method ||= obj[1] if obj.kind_of?(Hash) + raise ArgumentError, "Takes only a single accessor to proxy" if method.kind_of? Array + instance_proxy_accessors_for obj, [method].flatten + end + def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash self.class.send :include, Party::Proxy hash.each_pair do |proxy, methods| instance_proxy_accessors_for proxy, methods end end protected def create_in_factory name raise ArgumentError, "Factory name must be a label, was #{name}" if !name.kind_of_label? proxy_factory[name].create if !send(name) && proxy_factory && proxy_factory[name] end end # Define class methods here. module ClassMethods attr_accessor :proxies attr_accessor :proxy_factories def proxy_factory proxy_factories end def remove_proxy_factory name @proxy_factories[name] = nil end def remove_proxy_factories self.proxy_factories = nil end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else case factory when Array fac = factory.first meth = factory.last if factory.size == 2 raise ArgumentError, "Factory must be a Class, was #{fac}" if !fac.kind_of?(Class) raise ArgumentError, "Factory method be a label, was #{meth}" if meth && !meth.kind_of_label? Party::Proxy::Factory.new(fac, meth) else raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to?(:create) factory end end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories def remove_proxy name proxies.delete(name) end def proxy_for obj, *methods rename_methods = last_arg_value({:rename => {}}, methods) methods.delete(:rename) if rename_methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do send(obj).send(name) if send(obj) end end rename_methods.each_pair do |meth, new_meth| name = meth.to_sym define_method new_meth.to_sym do send(obj).send(name) if send(obj) end end end def proxy_accessors_for obj, *methods proxy_for obj, methods rename_methods = last_arg_value({:rename => {}}, methods) methods.delete(:rename) if rename_methods methods.flat_uniq.each do |meth| name = meth.to_sym obj_name = obj.to_sym define_method name do |arg| send(obj_name).send('||=', create_in_factory(obj_name)) send(obj_name).send("#{name}=", arg) if send(obj) end end rename_methods.each_pair do |meth, new_meth| name = meth.to_sym obj_name = obj.to_sym define_method new_meth.to_sym do |arg| send(obj_name).send('||=', create_in_factory(obj_name)) send(obj_name).send("#{name}=", arg) if send(obj) end end end + def proxy_accessor_for obj, method = nil + method ||= obj[1] if obj.kind_of?(Hash) + raise ArgumentError, "Takes only a single accessor to proxy" if method.kind_of? Array + proxy_accessors_for obj, [method].flatten + end + protected def create_in_factory name proxy_factory[name].create if proxy_factory && proxy_factory[name] end end # proxy to state def method_missing(name, *args, &block) return if !self.class.proxies self.class.proxies.each do |proxi| proxy_obj = self.send proxi return proxy_obj.send(name, *args, &block) if proxy_obj.respond_to? :"#{name}" end super end end end class Module def party_proxy include Party::Proxy end alias_method :proxy_party, :party_proxy def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash include Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end def proxy *proxy_objs include Party::Proxy proxy_objs.flat_uniq.each do |proxy_obj| raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index 81b1cde..301969d 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,149 +1,151 @@ require 'spec_helper' class State attr_accessor :name def initialize name = nil @name = name end end class Info attr_accessor :text def initialize text = nil @text = text end end class Mic attr_accessor :speak, :yawn def initialize text = nil @speak = text end def speak_it! speak end def self.create_empty mic = self.new mic.speak = 'empty' mic.yawn = 'miau' mic end end module Party class Subject attr_accessor :mic proxy :state, :info def initialize name = nil @state = State.new name @info = Info.new 'hello' end end end module PartyModule party_proxy end class PartyClass proxy_party end describe Party::Proxy do describe '#party_proxy' do it "Should add party proxy to Module" do PartyModule.methods.grep(/proxy_for/).should_not be_empty PartyModule.should respond_to(:add_proxy_factory) end it "Should add party proxy to Class" do PartyClass.methods.grep(/proxy_for/).should_not be_empty PartyClass.should respond_to(:add_proxy_factory) end end describe '#proxy' do it "proxies state and info so it can call name directly on subject" do subject = Party::Subject.new 'kristian' subject.name.should == 'kristian' end end describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.instance_proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end it "handles proxy when the proxied object (mic) is nil" do subject = Party::Subject.new 'kristian' subject.instance_proxy_for :mic, :speak_it! subject.speak_it!.should == nil end it "handles proxy when the proxied object (mic) is set to nil later" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.instance_proxy_for :mic, :speak_it!, :check => true subject.mic = nil subject.speak_it!.should == nil end it "errors when proxy when the proxied object (mic) is nil and nil check is on" do subject = Party::Subject.new 'kristian' subject.mic = nil lambda {subject.proxy_for :mic, :speak_it!, :check => true}.should raise_error end it "proxies uses class level proxy factory with factory method" do subject = Party::Subject.new 'kristian' subject.add_proxy_factory :mic => [Mic, :create_empty] - subject.instance_proxy_accessors_for :mic, :speak, :yawn + subject.instance_proxy_accessors_for :mic, :speak + subject.instance_proxy_accessor_for :mic, :yawn + subject.instance_proxy_accessor_for :mic => :yawn subject.speak = 'blip' subject.speak.should == 'blip' subject.yawn.should == 'miau' end end describe '#proxy_for renaming using :as' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.instance_proxy_for :mic, :rename => {:speak_it! => :speak_up!} subject.speak_up!.should == 'hello' end it "proxies uses class level proxy factory with factory method" do subject = Party::Subject.new 'kristian' subject.add_proxy_factory :mic => [Mic, :create_empty] subject.instance_proxy_accessors_for :mic, :rename => {:speak => :yell, :yawn => :gaab} subject.yell = 'blip' subject.yell.should == 'blip' subject.gaab.should == 'miau' end end describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' end end end
kristianmandrup/proxy_party
07b2a228cb3222d0003c2611da341f08b27ca459
Regenerate gemspec for version 0.2.1
diff --git a/proxy_party.gemspec b/proxy_party.gemspec index 9346586..bea79bd 100644 --- a/proxy_party.gemspec +++ b/proxy_party.gemspec @@ -1,48 +1,57 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY -# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command +# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{proxy_party} - s.version = "0.2.0" + s.version = "0.2.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Kristian Mandrup"] - s.date = %q{2011-02-13} + s.date = %q{2011-02-21} s.description = %q{Method missing proxy pattern} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.textile" ] s.files = [ ".document", - ".gitignore", - "LICENSE", - "README.textile", - "Rakefile", - "VERSION", - "lib/proxy_party.rb", + ".rspec", + "LICENSE", + "README.textile", + "Rakefile", + "VERSION", + "lib/proxy_party.rb", + "proxy_party.gemspec", + "spec/proxy_party_complex_spec.rb", + "spec/proxy_party_spec.rb", + "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/kristianmandrup/proxy_party} - s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] - s.rubygems_version = %q{1.3.7} + s.rubygems_version = %q{1.5.2} s.summary = %q{Add proxy functionality the fun way} s.test_files = [ + "spec/proxy_party_complex_spec.rb", "spec/proxy_party_spec.rb", - "spec/spec_helper.rb" + "spec/spec_helper.rb" ] if s.respond_to? :specification_version then - current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then + s.add_runtime_dependency(%q<sugar-high>, [">= 0.3.5"]) + s.add_development_dependency(%q<rspec>, [">= 2.4.0"]) else + s.add_dependency(%q<sugar-high>, [">= 0.3.5"]) + s.add_dependency(%q<rspec>, [">= 2.4.0"]) end else + s.add_dependency(%q<sugar-high>, [">= 0.3.5"]) + s.add_dependency(%q<rspec>, [">= 2.4.0"]) end end
kristianmandrup/proxy_party
ddceba8977efdd8292958f06e09232dbe4e7685a
added psych and bumped version
diff --git a/Rakefile b/Rakefile index 3ada8d3..cfded62 100644 --- a/Rakefile +++ b/Rakefile @@ -1,23 +1,24 @@ require 'rubygems' +require 'psych' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "proxy_party" gem.summary = %Q{Add proxy functionality the fun way} gem.description = %Q{Method missing proxy pattern} gem.email = "[email protected]" gem.homepage = "http://github.com/kristianmandrup/proxy_party" gem.authors = ["Kristian Mandrup"] gem.add_dependency "sugar-high", ">= 0.3.5" gem.add_development_dependency "rspec", ">= 2.4.0" # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end diff --git a/VERSION b/VERSION index 0ea3a94..0c62199 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.2.0 +0.2.1
kristianmandrup/proxy_party
58aead09540054a746f17b360424e42961db3bf6
added option to rename methods
diff --git a/README.textile b/README.textile index 17e5de7..5c1c943 100644 --- a/README.textile +++ b/README.textile @@ -1,105 +1,128 @@ h1. Proxy Party Greatly facilitates adding proxies through the proxy method_missing pattern. Can now also dynamically add proxy methods and use other amazing meta strategies! h2. Install @$ gem install party_proxy@ h2. Use @require 'party_proxy'@ +h2. Latest news + +Now supports renaming of proxy method so you can avoid method name collisions! + +h2. TODO + +Major DRYing up needed. Currently a lot of code duplication :O + h2. Usage <pre> class State attr_accessor :name def initialize(name) @name = name end end class Info attr_accessor :text def initialize(text) @text = text end end module Party class Subject # proxy state and info objects to make their methods # directly accessible from subject objects proxy :state, :info def initialize(name) @state = State.new name @info = Info.new 'hello' end end end </pre> <pre> describe Party::Proxy do describe '#proxy' do it "proxies state and info so it can call name directly on subject" do subject = Party::Subject.new 'kristian' subject.name.should == 'kristian' end end describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' Party::Subject.proxy_for :mic, :speak_it! subject.proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end + + it "proxies speak_it! as speak_up! on mic" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + Party::Subject.proxy_for :mic, :rename => {:speak_it! => :speak_up!} + subject.speak_up!.should == 'hello' + end end describe '#proxy_accessor_for' do it "proxies speak accessor methods on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == 'do it!' end + + it "proxies speak accessor method on mic as yell" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + subject.proxy_accessors_for :mic, :rename => {:speak => :yell} + subject.yell = 'do it!' + subject.yell.should == 'do it!' + end end describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' end end end </pre> h2. Note on Patches/Pull Requests * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) * Send me a pull request. Bonus points for topic branches. h2. Copyright Copyright (c) 2010 Kristian Mandrup. See LICENSE for details. diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index 71dd1bc..eb46f82 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,254 +1,346 @@ require 'sugar-high/array' require 'sugar-high/kind_of' require 'sugar-high/arguments' module Party module Proxy class Factory attr_reader :create_method, :klass def initialize klass, create_method = nil @klass = klass @create_method = create_method end def create create_method ? klass.send(create_method) : klass.new end end def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module InstanceMethods attr_accessor :proxy_factories def proxy_factory proxy_factories end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else case factory when Array fac = factory.first meth = factory.last if factory.size == 2 raise ArgumentError, "Factory must be a Class, was #{fac}" if !fac.kind_of?(Class) raise ArgumentError, "Factory method be a label, was #{meth}" if meth && !meth.kind_of_label? Party::Proxy::Factory.new(fac, meth) else raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to?(:create) factory end end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories # Add instance proxy methods def proxy_for obj, *methods - check = last_arg_value({:check => false}, methods) - methods.to_symbols.flat_uniq.each do |meth| + check = last_arg_value({:check => false}, methods) + rename_methods = last_arg_value({:rename => {}}, methods) + methods.delete(:rename) if rename_methods + + methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end class_eval %{ define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end } end + + rename_methods.each_pair do |meth, new_meth| + if check + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) + end + class_eval %{ + define_method :#{new_meth} do + #{obj}.send(:#{meth}) if #{obj} + end + } + end end # Add instance proxy methods def proxy_accessors_for obj, *methods proxy_for obj, methods check = last_arg_value({:check => false}, methods) + rename_methods = last_arg_value({:rename => {}}, methods) + methods.delete(:rename) if rename_methods + methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end class_eval %{ define_method :#{meth}= do |arg| self.#{obj} ||= create_in_factory(:#{obj}) self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) #{obj}.send(:#{meth}=, arg) if #{obj} end } end + + rename_methods.each_pair do |meth, new_meth| + if check + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") + end + class_eval %{ + define_method :#{new_meth}= do |arg| + self.#{obj} ||= create_in_factory(:#{obj}) + self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) + #{obj}.send(:#{meth}=, arg) if #{obj} + end + } + end end # Add proxy methods only to the instance object def instance_proxy_for obj, *methods - check = last_arg_value({:check => false}, methods) + check = last_arg_value({:check => false}, methods) + rename_methods = last_arg_value({:rename => {}}, methods) + methods.delete(:rename) if rename_methods + methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end end } - end + end + + rename_methods.each_pair do |meth, new_meth| + if check + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) + end + instance_eval %{ + class << self + define_method :#{new_meth} do + #{obj}.send(:#{meth}) if #{obj} + end + end + } + end end # Add proxy methods only to the instance object def instance_proxy_accessors_for obj, *methods instance_proxy_for obj, methods check = last_arg_value({:check => false}, methods) + + rename_methods = last_arg_value({:rename => {}}, methods) + methods.delete(:rename) if rename_methods + methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end instance_eval %{ class << self define_method :#{meth}= do |arg| self.#{obj} ||= create_in_factory(:#{obj}) self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) #{obj}.send(:#{meth}=, arg) if #{obj} end end } + end + + rename_methods.each_pair do |meth, new_meth| + if check + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) + end + instance_eval %{ + class << self + define_method :#{new_meth}= do |arg| + self.#{obj} ||= create_in_factory(:#{obj}) + self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) + #{obj}.send(:#{meth}=, arg) if #{obj} + end + end + } end end def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash self.class.send :include, Party::Proxy hash.each_pair do |proxy, methods| instance_proxy_accessors_for proxy, methods end end protected def create_in_factory name raise ArgumentError, "Factory name must be a label, was #{name}" if !name.kind_of_label? proxy_factory[name].create if !send(name) && proxy_factory && proxy_factory[name] end end # Define class methods here. module ClassMethods attr_accessor :proxies attr_accessor :proxy_factories def proxy_factory proxy_factories end def remove_proxy_factory name @proxy_factories[name] = nil end def remove_proxy_factories self.proxy_factories = nil end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else case factory when Array fac = factory.first meth = factory.last if factory.size == 2 raise ArgumentError, "Factory must be a Class, was #{fac}" if !fac.kind_of?(Class) raise ArgumentError, "Factory method be a label, was #{meth}" if meth && !meth.kind_of_label? Party::Proxy::Factory.new(fac, meth) else raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to?(:create) factory end end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories def remove_proxy name proxies.delete(name) end def proxy_for obj, *methods + rename_methods = last_arg_value({:rename => {}}, methods) + methods.delete(:rename) if rename_methods + methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do send(obj).send(name) if send(obj) end end + + rename_methods.each_pair do |meth, new_meth| + name = meth.to_sym + define_method new_meth.to_sym do + send(obj).send(name) if send(obj) + end + end end def proxy_accessors_for obj, *methods proxy_for obj, methods + + rename_methods = last_arg_value({:rename => {}}, methods) + methods.delete(:rename) if rename_methods + methods.flat_uniq.each do |meth| name = meth.to_sym obj_name = obj.to_sym define_method name do |arg| send(obj_name).send('||=', create_in_factory(obj_name)) send(obj_name).send("#{name}=", arg) if send(obj) end end + + rename_methods.each_pair do |meth, new_meth| + name = meth.to_sym + obj_name = obj.to_sym + define_method new_meth.to_sym do |arg| + send(obj_name).send('||=', create_in_factory(obj_name)) + send(obj_name).send("#{name}=", arg) if send(obj) + end + end end protected def create_in_factory name proxy_factory[name].create if proxy_factory && proxy_factory[name] end end # proxy to state def method_missing(name, *args, &block) return if !self.class.proxies self.class.proxies.each do |proxi| proxy_obj = self.send proxi return proxy_obj.send(name, *args, &block) if proxy_obj.respond_to? :"#{name}" end super end end end class Module def party_proxy include Party::Proxy end alias_method :proxy_party, :party_proxy def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash include Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end def proxy *proxy_objs include Party::Proxy proxy_objs.flat_uniq.each do |proxy_obj| raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/spec/proxy_party_complex_spec.rb b/spec/proxy_party_complex_spec.rb index 6bee000..2f69d59 100644 --- a/spec/proxy_party_complex_spec.rb +++ b/spec/proxy_party_complex_spec.rb @@ -1,68 +1,62 @@ require 'spec_helper' class Module include Party::Proxy end class Address attr_accessor :street end -module Proxies - # def self.included(base) - # base.class_eval do - # make_proxy_for :address, :street - # end - # end - +module Proxies proxy_accessors_for :address, :street - # make_proxy_accessors_for :address, :street end class Place attr_accessor :address # include Proxies def self.inherited(base) - puts "Inherited: #{base}" - base.class_eval do - send :include, Proxies - end + # Alternative + # base.class_eval do + # send :include, Proxies + # end + base.send :include, Proxies # puts base.methods.sort end end class OtherPlace attr_accessor :address proxy_accessors_for :address, :street end class Pickup attr_accessor :address include Proxies end class Dropoff < Place end describe Party::Proxy do context 'Dropoff inherits from Place' do before do @dropoff = Dropoff.new @pickup = Pickup.new @other = OtherPlace.new end it 'should add proxies for address' do @dropoff.should respond_to :street @pickup.should respond_to :street @other.should respond_to :street @dropoff.should respond_to :street= @pickup.should respond_to :street= @other.should respond_to :street= end end end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index 56be115..81b1cde 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,131 +1,149 @@ require 'spec_helper' class State attr_accessor :name def initialize name = nil @name = name end end class Info attr_accessor :text def initialize text = nil @text = text end end class Mic attr_accessor :speak, :yawn def initialize text = nil @speak = text end def speak_it! speak end def self.create_empty mic = self.new mic.speak = 'empty' mic.yawn = 'miau' mic end end module Party class Subject attr_accessor :mic proxy :state, :info def initialize name = nil @state = State.new name @info = Info.new 'hello' end end end module PartyModule party_proxy end class PartyClass proxy_party end describe Party::Proxy do describe '#party_proxy' do it "Should add party proxy to Module" do PartyModule.methods.grep(/proxy_for/).should_not be_empty PartyModule.should respond_to(:add_proxy_factory) end it "Should add party proxy to Class" do PartyClass.methods.grep(/proxy_for/).should_not be_empty PartyClass.should respond_to(:add_proxy_factory) end end describe '#proxy' do it "proxies state and info so it can call name directly on subject" do subject = Party::Subject.new 'kristian' subject.name.should == 'kristian' end end describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.instance_proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end it "handles proxy when the proxied object (mic) is nil" do subject = Party::Subject.new 'kristian' subject.instance_proxy_for :mic, :speak_it! subject.speak_it!.should == nil end it "handles proxy when the proxied object (mic) is set to nil later" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.instance_proxy_for :mic, :speak_it!, :check => true subject.mic = nil subject.speak_it!.should == nil end it "errors when proxy when the proxied object (mic) is nil and nil check is on" do subject = Party::Subject.new 'kristian' subject.mic = nil lambda {subject.proxy_for :mic, :speak_it!, :check => true}.should raise_error end it "proxies uses class level proxy factory with factory method" do subject = Party::Subject.new 'kristian' subject.add_proxy_factory :mic => [Mic, :create_empty] subject.instance_proxy_accessors_for :mic, :speak, :yawn subject.speak = 'blip' subject.speak.should == 'blip' subject.yawn.should == 'miau' end end + + describe '#proxy_for renaming using :as' do + it "proxies speak_it! on mic" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + subject.instance_proxy_for :mic, :rename => {:speak_it! => :speak_up!} + subject.speak_up!.should == 'hello' + end + + it "proxies uses class level proxy factory with factory method" do + subject = Party::Subject.new 'kristian' + subject.add_proxy_factory :mic => [Mic, :create_empty] + subject.instance_proxy_accessors_for :mic, :rename => {:speak => :yell, :yawn => :gaab} + subject.yell = 'blip' + subject.yell.should == 'blip' + subject.gaab.should == 'miau' + end + end describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' end end end
kristianmandrup/proxy_party
c559230adc1cf5005ca73ce4b58e9463a716f028
added specs to demonstrate use in more complex scenarios, inheriting class or including module
diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index 5944aa2..71dd1bc 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,216 +1,254 @@ require 'sugar-high/array' require 'sugar-high/kind_of' require 'sugar-high/arguments' module Party module Proxy class Factory attr_reader :create_method, :klass def initialize klass, create_method = nil @klass = klass @create_method = create_method end def create create_method ? klass.send(create_method) : klass.new end end def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module InstanceMethods attr_accessor :proxy_factories def proxy_factory proxy_factories end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else case factory when Array fac = factory.first meth = factory.last if factory.size == 2 raise ArgumentError, "Factory must be a Class, was #{fac}" if !fac.kind_of?(Class) raise ArgumentError, "Factory method be a label, was #{meth}" if meth && !meth.kind_of_label? Party::Proxy::Factory.new(fac, meth) else raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to?(:create) factory end end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories - + + # Add instance proxy methods def proxy_for obj, *methods + check = last_arg_value({:check => false}, methods) + methods.to_symbols.flat_uniq.each do |meth| + if check + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) + end + class_eval %{ + define_method :#{meth} do + #{obj}.send(:#{meth}) if #{obj} + end + } + end + end + + # Add instance proxy methods + def proxy_accessors_for obj, *methods + proxy_for obj, methods + check = last_arg_value({:check => false}, methods) + methods.to_symbols.flat_uniq.each do |meth| + if check + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") + end + class_eval %{ + define_method :#{meth}= do |arg| + self.#{obj} ||= create_in_factory(:#{obj}) + self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) + #{obj}.send(:#{meth}=, arg) if #{obj} + end + } + end + end + + # Add proxy methods only to the instance object + def instance_proxy_for obj, *methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end end } end end - - def proxy_accessors_for obj, *methods - proxy_for obj, methods + + # Add proxy methods only to the instance object + def instance_proxy_accessors_for obj, *methods + instance_proxy_for obj, methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end instance_eval %{ class << self define_method :#{meth}= do |arg| self.#{obj} ||= create_in_factory(:#{obj}) self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) #{obj}.send(:#{meth}=, arg) if #{obj} end end } end end def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash self.class.send :include, Party::Proxy hash.each_pair do |proxy, methods| - proxy_accessors_for proxy, methods + instance_proxy_accessors_for proxy, methods end end protected def create_in_factory name raise ArgumentError, "Factory name must be a label, was #{name}" if !name.kind_of_label? proxy_factory[name].create if !send(name) && proxy_factory && proxy_factory[name] end end # Define class methods here. module ClassMethods attr_accessor :proxies attr_accessor :proxy_factories def proxy_factory proxy_factories end def remove_proxy_factory name @proxy_factories[name] = nil end def remove_proxy_factories self.proxy_factories = nil end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else case factory when Array fac = factory.first meth = factory.last if factory.size == 2 raise ArgumentError, "Factory must be a Class, was #{fac}" if !fac.kind_of?(Class) raise ArgumentError, "Factory method be a label, was #{meth}" if meth && !meth.kind_of_label? Party::Proxy::Factory.new(fac, meth) else raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to?(:create) factory end end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories def remove_proxy name proxies.delete(name) end def proxy_for obj, *methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do send(obj).send(name) if send(obj) end end end def proxy_accessors_for obj, *methods proxy_for obj, methods methods.flat_uniq.each do |meth| name = meth.to_sym obj_name = obj.to_sym define_method name do |arg| send(obj_name).send('||=', create_in_factory(obj_name)) send(obj_name).send("#{name}=", arg) if send(obj) end end end protected def create_in_factory name proxy_factory[name].create if proxy_factory && proxy_factory[name] end end # proxy to state def method_missing(name, *args, &block) + return if !self.class.proxies self.class.proxies.each do |proxi| proxy_obj = self.send proxi return proxy_obj.send(name, *args, &block) if proxy_obj.respond_to? :"#{name}" end super end end end class Module def party_proxy include Party::Proxy end alias_method :proxy_party, :party_proxy def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash include Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end def proxy *proxy_objs include Party::Proxy proxy_objs.flat_uniq.each do |proxy_obj| raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/spec/proxy_party_complex_spec.rb b/spec/proxy_party_complex_spec.rb new file mode 100644 index 0000000..6bee000 --- /dev/null +++ b/spec/proxy_party_complex_spec.rb @@ -0,0 +1,68 @@ +require 'spec_helper' + +class Module + include Party::Proxy +end + +class Address + attr_accessor :street +end + +module Proxies + # def self.included(base) + # base.class_eval do + # make_proxy_for :address, :street + # end + # end + + proxy_accessors_for :address, :street + # make_proxy_accessors_for :address, :street +end + +class Place + attr_accessor :address + # include Proxies + + def self.inherited(base) + puts "Inherited: #{base}" + base.class_eval do + send :include, Proxies + end + # puts base.methods.sort + end +end + +class OtherPlace + attr_accessor :address + + proxy_accessors_for :address, :street +end + +class Pickup + attr_accessor :address + + include Proxies +end + +class Dropoff < Place +end + +describe Party::Proxy do + context 'Dropoff inherits from Place' do + before do + @dropoff = Dropoff.new + @pickup = Pickup.new + @other = OtherPlace.new + end + + it 'should add proxies for address' do + @dropoff.should respond_to :street + @pickup.should respond_to :street + @other.should respond_to :street + + @dropoff.should respond_to :street= + @pickup.should respond_to :street= + @other.should respond_to :street= + end + end +end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index 496999b..56be115 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,172 +1,131 @@ require 'spec_helper' class State attr_accessor :name - + def initialize name = nil - @name = name - end -end + @name = name + end +end class Info attr_accessor :text - + def initialize text = nil - @text = text - end -end + @text = text + end +end class Mic attr_accessor :speak, :yawn - + def initialize text = nil - @speak = text - end - + @speak = text + end + def speak_it! speak end - + def self.create_empty mic = self.new mic.speak = 'empty' mic.yawn = 'miau' mic end -end +end -module Party +module Party class Subject attr_accessor :mic - + proxy :state, :info - + def initialize name = nil @state = State.new name - @info = Info.new 'hello' + @info = Info.new 'hello' end end end module PartyModule party_proxy end class PartyClass proxy_party end describe Party::Proxy do - # describe '#party_proxy' do - # it "Should add party proxy to Module" do - # PartyModule.methods.grep(/proxy_for/).should_not be_empty - # end - # - # it "Should add party proxy to Class" do - # PartyClass.methods.grep(/proxy_for/).should_not be_empty - # end - # end - # - # describe '#proxy' do - # it "proxies state and info so it can call name directly on subject" do - # subject = Party::Subject.new 'kristian' - # subject.name.should == 'kristian' - # end - # end - + describe '#party_proxy' do + it "Should add party proxy to Module" do + PartyModule.methods.grep(/proxy_for/).should_not be_empty + PartyModule.should respond_to(:add_proxy_factory) + end + + it "Should add party proxy to Class" do + PartyClass.methods.grep(/proxy_for/).should_not be_empty + PartyClass.should respond_to(:add_proxy_factory) + end + end + + describe '#proxy' do + it "proxies state and info so it can call name directly on subject" do + subject = Party::Subject.new 'kristian' + subject.name.should == 'kristian' + end + end + describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' - Party::Subject.proxy_for :mic, :speak_it! - - subject.proxy_for :mic, :speak_it! - + subject.instance_proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end - + it "handles proxy when the proxied object (mic) is nil" do subject = Party::Subject.new 'kristian' - subject.proxy_for :mic, :speak_it! + subject.instance_proxy_for :mic, :speak_it! subject.speak_it!.should == nil end - + it "handles proxy when the proxied object (mic) is set to nil later" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' - subject.proxy_for :mic, :speak_it!, :check => true - subject.mic = nil + subject.instance_proxy_for :mic, :speak_it!, :check => true + subject.mic = nil subject.speak_it!.should == nil end - + it "errors when proxy when the proxied object (mic) is nil and nil check is on" do subject = Party::Subject.new 'kristian' subject.mic = nil lambda {subject.proxy_for :mic, :speak_it!, :check => true}.should raise_error - end - - it "proxies uses class level proxy factory with factory method" do - subject = Party::Subject.new 'kristian' - subject.add_proxy_factory :mic => [Mic, :create_empty] - subject.proxy_accessors_for :mic, :speak, :yawn - subject.speak = 'blip' - subject.speak.should == 'blip' - subject.yawn.should == 'miau' - end - - end - - describe 'Class methods' do - it "proxies uses class level proxy factory" do - subject = Party::Subject.new 'kristian' - Party::Subject.add_proxy_factory :mic => Mic - subject.proxy_accessors_for :mic, :speak - subject.speak = 'do it!' - subject.speak.should == 'do it!' end it "proxies uses class level proxy factory with factory method" do subject = Party::Subject.new 'kristian' - Party::Subject.add_proxy_factory :mic => [Mic, :create_empty] - subject.proxy_accessors_for :mic, :speak, :yawn - subject.speak = 'blip' + subject.add_proxy_factory :mic => [Mic, :create_empty] + subject.instance_proxy_accessors_for :mic, :speak, :yawn + subject.speak = 'blip' subject.speak.should == 'blip' subject.yawn.should == 'miau' - end - end - - describe '#proxy_accessor_for' do - it "proxies speak accessor methods on mic bu can't set accessor since proxy not initialized and no proxy factory defined" do - subject = Party::Subject.new 'kristian' - Party::Subject.remove_proxy_factories - subject.proxy_accessors_for :mic, :speak - subject.speak = 'do it!' - subject.speak.should == nil end - - it "proxies speak accessor methods on mic and uses factory to create proxy obj if nil on setting value" do - subject = Party::Subject.new 'kristian' - subject.add_proxy_factory :mic => Mic - subject.proxy_accessors_for :mic, :speak - subject.speak = 'do it!' - subject.speak.should == 'do it!' - end end - describe '#named_proxies' do + describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' - end - end + end + end end - -
kristianmandrup/proxy_party
184b65ed52d0079eb5d73c366e355d8d7805d792
added option to customize factory create method
diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index b4da628..5944aa2 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,196 +1,216 @@ require 'sugar-high/array' require 'sugar-high/kind_of' require 'sugar-high/arguments' module Party module Proxy class Factory + attr_reader :create_method, :klass - def initialize klass + def initialize klass, create_method = nil @klass = klass + @create_method = create_method end def create - @klass.new + create_method ? klass.send(create_method) : klass.new end end def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module InstanceMethods attr_accessor :proxy_factories def proxy_factory proxy_factories end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else - raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to? create - factory + case factory + when Array + fac = factory.first + meth = factory.last if factory.size == 2 + raise ArgumentError, "Factory must be a Class, was #{fac}" if !fac.kind_of?(Class) + raise ArgumentError, "Factory method be a label, was #{meth}" if meth && !meth.kind_of_label? + Party::Proxy::Factory.new(fac, meth) + else + raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to?(:create) + factory + end end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories def proxy_for obj, *methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end end } end end def proxy_accessors_for obj, *methods proxy_for obj, methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end instance_eval %{ class << self define_method :#{meth}= do |arg| self.#{obj} ||= create_in_factory(:#{obj}) self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) #{obj}.send(:#{meth}=, arg) if #{obj} end end } end end def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash self.class.send :include, Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end protected def create_in_factory name raise ArgumentError, "Factory name must be a label, was #{name}" if !name.kind_of_label? proxy_factory[name].create if !send(name) && proxy_factory && proxy_factory[name] end end # Define class methods here. module ClassMethods attr_accessor :proxies attr_accessor :proxy_factories def proxy_factory proxy_factories end def remove_proxy_factory name @proxy_factories[name] = nil end def remove_proxy_factories self.proxy_factories = nil end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else - raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to? create - factory + case factory + when Array + fac = factory.first + meth = factory.last if factory.size == 2 + raise ArgumentError, "Factory must be a Class, was #{fac}" if !fac.kind_of?(Class) + raise ArgumentError, "Factory method be a label, was #{meth}" if meth && !meth.kind_of_label? + Party::Proxy::Factory.new(fac, meth) + else + raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to?(:create) + factory + end end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories def remove_proxy name proxies.delete(name) end def proxy_for obj, *methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do send(obj).send(name) if send(obj) end end end def proxy_accessors_for obj, *methods proxy_for obj, methods methods.flat_uniq.each do |meth| name = meth.to_sym obj_name = obj.to_sym define_method name do |arg| send(obj_name).send('||=', create_in_factory(obj_name)) send(obj_name).send("#{name}=", arg) if send(obj) end end end protected def create_in_factory name proxy_factory[name].create if proxy_factory && proxy_factory[name] end end # proxy to state def method_missing(name, *args, &block) self.class.proxies.each do |proxi| proxy_obj = self.send proxi return proxy_obj.send(name, *args, &block) if proxy_obj.respond_to? :"#{name}" end super end end end class Module def party_proxy include Party::Proxy end alias_method :proxy_party, :party_proxy def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash include Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end def proxy *proxy_objs include Party::Proxy proxy_objs.flat_uniq.each do |proxy_obj| raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index 0c18813..496999b 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,148 +1,172 @@ require 'spec_helper' class State attr_accessor :name def initialize name = nil @name = name end end class Info attr_accessor :text def initialize text = nil @text = text end end class Mic - attr_accessor :speak + attr_accessor :speak, :yawn def initialize text = nil @speak = text end def speak_it! speak end + + def self.create_empty + mic = self.new + mic.speak = 'empty' + mic.yawn = 'miau' + mic + end end - - module Party class Subject attr_accessor :mic proxy :state, :info def initialize name = nil @state = State.new name @info = Info.new 'hello' end end end module PartyModule party_proxy end class PartyClass proxy_party end describe Party::Proxy do - describe '#party_proxy' do - it "Should add party proxy to Module" do - PartyModule.methods.grep(/proxy_for/).should_not be_empty - end - - it "Should add party proxy to Class" do - PartyClass.methods.grep(/proxy_for/).should_not be_empty - end - end - - describe '#proxy' do - it "proxies state and info so it can call name directly on subject" do - subject = Party::Subject.new 'kristian' - subject.name.should == 'kristian' - end - end + # describe '#party_proxy' do + # it "Should add party proxy to Module" do + # PartyModule.methods.grep(/proxy_for/).should_not be_empty + # end + # + # it "Should add party proxy to Class" do + # PartyClass.methods.grep(/proxy_for/).should_not be_empty + # end + # end + # + # describe '#proxy' do + # it "proxies state and info so it can call name directly on subject" do + # subject = Party::Subject.new 'kristian' + # subject.name.should == 'kristian' + # end + # end describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' Party::Subject.proxy_for :mic, :speak_it! - + subject.proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end - + it "handles proxy when the proxied object (mic) is nil" do subject = Party::Subject.new 'kristian' subject.proxy_for :mic, :speak_it! subject.speak_it!.should == nil end - + it "handles proxy when the proxied object (mic) is set to nil later" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.proxy_for :mic, :speak_it!, :check => true subject.mic = nil subject.speak_it!.should == nil end - + it "errors when proxy when the proxied object (mic) is nil and nil check is on" do subject = Party::Subject.new 'kristian' subject.mic = nil lambda {subject.proxy_for :mic, :speak_it!, :check => true}.should raise_error - end + end + + it "proxies uses class level proxy factory with factory method" do + subject = Party::Subject.new 'kristian' + subject.add_proxy_factory :mic => [Mic, :create_empty] + subject.proxy_accessors_for :mic, :speak, :yawn + subject.speak = 'blip' + subject.speak.should == 'blip' + subject.yawn.should == 'miau' + end + end describe 'Class methods' do it "proxies uses class level proxy factory" do subject = Party::Subject.new 'kristian' Party::Subject.add_proxy_factory :mic => Mic subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == 'do it!' + end + + it "proxies uses class level proxy factory with factory method" do + subject = Party::Subject.new 'kristian' + Party::Subject.add_proxy_factory :mic => [Mic, :create_empty] + subject.proxy_accessors_for :mic, :speak, :yawn + subject.speak = 'blip' + subject.speak.should == 'blip' + subject.yawn.should == 'miau' end end - + describe '#proxy_accessor_for' do it "proxies speak accessor methods on mic bu can't set accessor since proxy not initialized and no proxy factory defined" do subject = Party::Subject.new 'kristian' Party::Subject.remove_proxy_factories subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == nil end it "proxies speak accessor methods on mic and uses factory to create proxy obj if nil on setting value" do subject = Party::Subject.new 'kristian' subject.add_proxy_factory :mic => Mic subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == 'do it!' end end describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' end - end + end end
kristianmandrup/proxy_party
23d5983f3d5e0ddde6223ad1cd9c109518714e1f
works with proxy factories on class and instance level
diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index 84dc785..b4da628 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,152 +1,196 @@ require 'sugar-high/array' require 'sugar-high/kind_of' require 'sugar-high/arguments' module Party module Proxy class Factory def initialize klass @klass = klass end def create @klass.new end end def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module InstanceMethods attr_accessor :proxy_factories def proxy_factory proxy_factories end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to? create factory end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories def proxy_for obj, *methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end end } end end def proxy_accessors_for obj, *methods proxy_for obj, methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end instance_eval %{ class << self define_method :#{meth}= do |arg| - self.#{obj} ||= proxy_factory[:#{obj}].create if !#{obj} && proxy_factory + self.#{obj} ||= create_in_factory(:#{obj}) + self.#{obj} ||= self.class.send(:create_in_factory, :#{obj}) #{obj}.send(:#{meth}=, arg) if #{obj} end end } end end - + def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash self.class.send :include, Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end - end + end + + protected + + def create_in_factory name + raise ArgumentError, "Factory name must be a label, was #{name}" if !name.kind_of_label? + proxy_factory[name].create if !send(name) && proxy_factory && proxy_factory[name] + end end # Define class methods here. module ClassMethods attr_accessor :proxies + attr_accessor :proxy_factories + + def proxy_factory + proxy_factories + end + + def remove_proxy_factory name + @proxy_factories[name] = nil + end + + def remove_proxy_factories + self.proxy_factories = nil + end + + def add_proxy_factories hash + hash.each_pair do |name, factory| + factory = if factory.kind_of?(Class) + Party::Proxy::Factory.new(factory) + else + raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to? create + factory + end + self.proxy_factories ||= {} + self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? + end + end + alias_method :add_proxy_factory, :add_proxy_factories + def remove_proxy name proxies.delete(name) end def proxy_for obj, *methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do send(obj).send(name) if send(obj) end end end def proxy_accessors_for obj, *methods proxy_for obj, methods methods.flat_uniq.each do |meth| name = meth.to_sym + obj_name = obj.to_sym define_method name do |arg| - obj.send("#{name}=", arg) if send(obj) + send(obj_name).send('||=', create_in_factory(obj_name)) + send(obj_name).send("#{name}=", arg) if send(obj) end end end + + protected + + def create_in_factory name + proxy_factory[name].create if proxy_factory && proxy_factory[name] + end end # proxy to state def method_missing(name, *args, &block) self.class.proxies.each do |proxi| proxy_obj = self.send proxi return proxy_obj.send(name, *args, &block) if proxy_obj.respond_to? :"#{name}" end super end end end class Module def party_proxy include Party::Proxy end alias_method :proxy_party, :party_proxy def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash include Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end def proxy *proxy_objs include Party::Proxy proxy_objs.flat_uniq.each do |proxy_obj| raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index 3be7437..0c18813 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,137 +1,148 @@ require 'spec_helper' class State attr_accessor :name def initialize name = nil @name = name end end class Info attr_accessor :text def initialize text = nil @text = text end end class Mic attr_accessor :speak def initialize text = nil @speak = text end def speak_it! speak end end module Party class Subject attr_accessor :mic proxy :state, :info def initialize name = nil @state = State.new name @info = Info.new 'hello' end end end module PartyModule party_proxy end class PartyClass proxy_party end describe Party::Proxy do describe '#party_proxy' do it "Should add party proxy to Module" do PartyModule.methods.grep(/proxy_for/).should_not be_empty end - + it "Should add party proxy to Class" do PartyClass.methods.grep(/proxy_for/).should_not be_empty end end describe '#proxy' do it "proxies state and info so it can call name directly on subject" do subject = Party::Subject.new 'kristian' subject.name.should == 'kristian' end end - + describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' Party::Subject.proxy_for :mic, :speak_it! - + subject.proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end - + it "handles proxy when the proxied object (mic) is nil" do subject = Party::Subject.new 'kristian' subject.proxy_for :mic, :speak_it! subject.speak_it!.should == nil end - + it "handles proxy when the proxied object (mic) is set to nil later" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.proxy_for :mic, :speak_it!, :check => true subject.mic = nil subject.speak_it!.should == nil end - + it "errors when proxy when the proxied object (mic) is nil and nil check is on" do subject = Party::Subject.new 'kristian' subject.mic = nil lambda {subject.proxy_for :mic, :speak_it!, :check => true}.should raise_error end end + describe 'Class methods' do + it "proxies uses class level proxy factory" do + subject = Party::Subject.new 'kristian' + Party::Subject.add_proxy_factory :mic => Mic + subject.proxy_accessors_for :mic, :speak + subject.speak = 'do it!' + subject.speak.should == 'do it!' + end + end + describe '#proxy_accessor_for' do it "proxies speak accessor methods on mic bu can't set accessor since proxy not initialized and no proxy factory defined" do subject = Party::Subject.new 'kristian' + Party::Subject.remove_proxy_factories subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == nil end - + it "proxies speak accessor methods on mic and uses factory to create proxy obj if nil on setting value" do subject = Party::Subject.new 'kristian' subject.add_proxy_factory :mic => Mic subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == 'do it!' end end - + describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' - + subject.name = 'kris' subject.name.should == 'kris' end end end
kristianmandrup/proxy_party
0466b264d93a3b0ce5959d35d920e8b1ed35347d
aliased macro
diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index 435c9df..84dc785 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,151 +1,152 @@ require 'sugar-high/array' require 'sugar-high/kind_of' require 'sugar-high/arguments' module Party module Proxy class Factory def initialize klass @klass = klass end def create @klass.new end end def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module InstanceMethods attr_accessor :proxy_factories def proxy_factory proxy_factories end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to? create factory end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories def proxy_for obj, *methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end end } end end def proxy_accessors_for obj, *methods proxy_for obj, methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end instance_eval %{ class << self define_method :#{meth}= do |arg| self.#{obj} ||= proxy_factory[:#{obj}].create if !#{obj} && proxy_factory #{obj}.send(:#{meth}=, arg) if #{obj} end end } end end def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash self.class.send :include, Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end end # Define class methods here. module ClassMethods attr_accessor :proxies def remove_proxy name proxies.delete(name) end def proxy_for obj, *methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do send(obj).send(name) if send(obj) end end end def proxy_accessors_for obj, *methods proxy_for obj, methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do |arg| obj.send("#{name}=", arg) if send(obj) end end end end # proxy to state def method_missing(name, *args, &block) self.class.proxies.each do |proxi| proxy_obj = self.send proxi return proxy_obj.send(name, *args, &block) if proxy_obj.respond_to? :"#{name}" end super end end end class Module def party_proxy include Party::Proxy end + alias_method :proxy_party, :party_proxy def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash include Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end def proxy *proxy_objs include Party::Proxy proxy_objs.flat_uniq.each do |proxy_obj| raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index 48495d0..3be7437 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,137 +1,137 @@ require 'spec_helper' class State attr_accessor :name def initialize name = nil @name = name end end class Info attr_accessor :text def initialize text = nil @text = text end end class Mic attr_accessor :speak def initialize text = nil @speak = text end def speak_it! speak end end module Party class Subject attr_accessor :mic proxy :state, :info def initialize name = nil @state = State.new name @info = Info.new 'hello' end end end module PartyModule party_proxy end class PartyClass - party_proxy + proxy_party end describe Party::Proxy do describe '#party_proxy' do it "Should add party proxy to Module" do PartyModule.methods.grep(/proxy_for/).should_not be_empty end it "Should add party proxy to Class" do PartyClass.methods.grep(/proxy_for/).should_not be_empty end end describe '#proxy' do it "proxies state and info so it can call name directly on subject" do subject = Party::Subject.new 'kristian' subject.name.should == 'kristian' end end describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' Party::Subject.proxy_for :mic, :speak_it! subject.proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end it "handles proxy when the proxied object (mic) is nil" do subject = Party::Subject.new 'kristian' subject.proxy_for :mic, :speak_it! subject.speak_it!.should == nil end it "handles proxy when the proxied object (mic) is set to nil later" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.proxy_for :mic, :speak_it!, :check => true subject.mic = nil subject.speak_it!.should == nil end it "errors when proxy when the proxied object (mic) is nil and nil check is on" do subject = Party::Subject.new 'kristian' subject.mic = nil lambda {subject.proxy_for :mic, :speak_it!, :check => true}.should raise_error end end describe '#proxy_accessor_for' do it "proxies speak accessor methods on mic bu can't set accessor since proxy not initialized and no proxy factory defined" do subject = Party::Subject.new 'kristian' subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == nil end it "proxies speak accessor methods on mic and uses factory to create proxy obj if nil on setting value" do subject = Party::Subject.new 'kristian' subject.add_proxy_factory :mic => Mic subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == 'do it!' end end describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' end end end
kristianmandrup/proxy_party
ce8e79fc338759be67f905e532c64bee85ccac2a
added party_proxy macro for Module and Class
diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index 18408e7..435c9df 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,148 +1,151 @@ require 'sugar-high/array' require 'sugar-high/kind_of' require 'sugar-high/arguments' module Party - module Proxy - + module Proxy class Factory def initialize klass @klass = klass end def create @klass.new end end def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module InstanceMethods attr_accessor :proxy_factories def proxy_factory proxy_factories end def add_proxy_factories hash hash.each_pair do |name, factory| factory = if factory.kind_of?(Class) Party::Proxy::Factory.new(factory) else raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to? create factory end self.proxy_factories ||= {} self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? end end alias_method :add_proxy_factory, :add_proxy_factories def proxy_for obj, *methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end end } end end def proxy_accessors_for obj, *methods proxy_for obj, methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end instance_eval %{ class << self define_method :#{meth}= do |arg| self.#{obj} ||= proxy_factory[:#{obj}].create if !#{obj} && proxy_factory #{obj}.send(:#{meth}=, arg) if #{obj} end end } end end def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash self.class.send :include, Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end end # Define class methods here. module ClassMethods attr_accessor :proxies def remove_proxy name proxies.delete(name) end def proxy_for obj, *methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do send(obj).send(name) if send(obj) end end end def proxy_accessors_for obj, *methods proxy_for obj, methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do |arg| obj.send("#{name}=", arg) if send(obj) end end end end # proxy to state def method_missing(name, *args, &block) self.class.proxies.each do |proxi| proxy_obj = self.send proxi return proxy_obj.send(name, *args, &block) if proxy_obj.respond_to? :"#{name}" end super end end end -class Class +class Module + def party_proxy + include Party::Proxy + end + def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash include Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end def proxy *proxy_objs include Party::Proxy proxy_objs.flat_uniq.each do |proxy_obj| raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index ea9faa7..48495d0 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,117 +1,137 @@ require 'spec_helper' class State attr_accessor :name def initialize name = nil @name = name end end class Info attr_accessor :text def initialize text = nil @text = text end end class Mic attr_accessor :speak def initialize text = nil @speak = text end def speak_it! speak end end module Party class Subject attr_accessor :mic proxy :state, :info def initialize name = nil @state = State.new name @info = Info.new 'hello' end end end +module PartyModule + party_proxy +end + +class PartyClass + party_proxy +end + + + describe Party::Proxy do + describe '#party_proxy' do + it "Should add party proxy to Module" do + PartyModule.methods.grep(/proxy_for/).should_not be_empty + end + + it "Should add party proxy to Class" do + PartyClass.methods.grep(/proxy_for/).should_not be_empty + end + end + describe '#proxy' do it "proxies state and info so it can call name directly on subject" do subject = Party::Subject.new 'kristian' subject.name.should == 'kristian' end end describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' Party::Subject.proxy_for :mic, :speak_it! subject.proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end it "handles proxy when the proxied object (mic) is nil" do subject = Party::Subject.new 'kristian' subject.proxy_for :mic, :speak_it! subject.speak_it!.should == nil end it "handles proxy when the proxied object (mic) is set to nil later" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.proxy_for :mic, :speak_it!, :check => true subject.mic = nil subject.speak_it!.should == nil end it "errors when proxy when the proxied object (mic) is nil and nil check is on" do subject = Party::Subject.new 'kristian' subject.mic = nil lambda {subject.proxy_for :mic, :speak_it!, :check => true}.should raise_error end end describe '#proxy_accessor_for' do it "proxies speak accessor methods on mic bu can't set accessor since proxy not initialized and no proxy factory defined" do subject = Party::Subject.new 'kristian' subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == nil end it "proxies speak accessor methods on mic and uses factory to create proxy obj if nil on setting value" do subject = Party::Subject.new 'kristian' subject.add_proxy_factory :mic => Mic subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == 'do it!' end end describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' end end end
kristianmandrup/proxy_party
d2115c46ea17b75f58325fba1df63b1db1969784
proxy factory added
diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index 0c71871..18408e7 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,116 +1,148 @@ require 'sugar-high/array' require 'sugar-high/kind_of' require 'sugar-high/arguments' module Party module Proxy + class Factory + + def initialize klass + @klass = klass + end + + def create + @klass.new + end + end + def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module InstanceMethods + attr_accessor :proxy_factories + + def proxy_factory + proxy_factories + end + + def add_proxy_factories hash + hash.each_pair do |name, factory| + factory = if factory.kind_of?(Class) + Party::Proxy::Factory.new(factory) + else + raise ArgumentError, "Factory must be a Class or have a #create method: #{factory}" if !factory.respond_to? create + factory + end + self.proxy_factories ||= {} + self.proxy_factories.merge!(name.to_sym => factory) if name.kind_of_label? + end + end + alias_method :add_proxy_factory, :add_proxy_factories + def proxy_for obj, *methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) end instance_eval %{ class << self define_method :#{meth} do #{obj}.send(:#{meth}) if #{obj} end end } end end def proxy_accessors_for obj, *methods proxy_for obj, methods check = last_arg_value({:check => false}, methods) methods.to_symbols.flat_uniq.each do |meth| if check raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") end instance_eval %{ class << self define_method :#{meth}= do |arg| + self.#{obj} ||= proxy_factory[:#{obj}].create if !#{obj} && proxy_factory #{obj}.send(:#{meth}=, arg) if #{obj} end end } end end def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash self.class.send :include, Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end end # Define class methods here. module ClassMethods attr_accessor :proxies def remove_proxy name proxies.delete(name) end def proxy_for obj, *methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do send(obj).send(name) if send(obj) end end end def proxy_accessors_for obj, *methods proxy_for obj, methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do |arg| obj.send("#{name}=", arg) if send(obj) end end end end # proxy to state def method_missing(name, *args, &block) self.class.proxies.each do |proxi| proxy_obj = self.send proxi return proxy_obj.send(name, *args, &block) if proxy_obj.respond_to? :"#{name}" end super end end end class Class def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash include Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end def proxy *proxy_objs include Party::Proxy proxy_objs.flat_uniq.each do |proxy_obj| raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index 0d2ef82..ea9faa7 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,110 +1,117 @@ require 'spec_helper' class State attr_accessor :name - def initialize(name) + def initialize name = nil @name = name end end class Info attr_accessor :text - def initialize(text) + def initialize text = nil @text = text end end class Mic attr_accessor :speak - def initialize(text) + def initialize text = nil @speak = text end def speak_it! speak end end module Party class Subject attr_accessor :mic proxy :state, :info - def initialize(name) + def initialize name = nil @state = State.new name @info = Info.new 'hello' end end end describe Party::Proxy do describe '#proxy' do it "proxies state and info so it can call name directly on subject" do subject = Party::Subject.new 'kristian' subject.name.should == 'kristian' end end describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' Party::Subject.proxy_for :mic, :speak_it! subject.proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end it "handles proxy when the proxied object (mic) is nil" do subject = Party::Subject.new 'kristian' subject.proxy_for :mic, :speak_it! subject.speak_it!.should == nil end it "handles proxy when the proxied object (mic) is set to nil later" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.proxy_for :mic, :speak_it!, :check => true subject.mic = nil subject.speak_it!.should == nil end it "errors when proxy when the proxied object (mic) is nil and nil check is on" do subject = Party::Subject.new 'kristian' subject.mic = nil lambda {subject.proxy_for :mic, :speak_it!, :check => true}.should raise_error end end describe '#proxy_accessor_for' do - it "proxies speak accessor methods on mic" do + it "proxies speak accessor methods on mic bu can't set accessor since proxy not initialized and no proxy factory defined" do subject = Party::Subject.new 'kristian' - subject.mic = Mic.new 'hello' subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' + subject.speak.should == nil + end + + it "proxies speak accessor methods on mic and uses factory to create proxy obj if nil on setting value" do + subject = Party::Subject.new 'kristian' + subject.add_proxy_factory :mic => Mic + subject.proxy_accessors_for :mic, :speak + subject.speak = 'do it!' subject.speak.should == 'do it!' end end describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' end end end
kristianmandrup/proxy_party
f110f48fd76aecab717aab55770a9a1a605f543e
better nil handling
diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index 11bf785..0c71871 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,109 +1,116 @@ require 'sugar-high/array' require 'sugar-high/kind_of' +require 'sugar-high/arguments' module Party module Proxy def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end module InstanceMethods def proxy_for obj, *methods - methods.flat_uniq.each do |meth| - raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) - raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) + check = last_arg_value({:check => false}, methods) + methods.to_symbols.flat_uniq.each do |meth| + if check + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) + end instance_eval %{ class << self define_method :#{meth} do - #{obj}.send :#{meth} + #{obj}.send(:#{meth}) if #{obj} end end } end end def proxy_accessors_for obj, *methods proxy_for obj, methods - methods.flat_uniq.each do |meth| - raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) - raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") + check = last_arg_value({:check => false}, methods) + methods.to_symbols.flat_uniq.each do |meth| + if check + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") + end instance_eval %{ class << self define_method :#{meth}= do |arg| - #{obj}.send :#{meth}=, arg + #{obj}.send(:#{meth}=, arg) if #{obj} end end } end end def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash self.class.send :include, Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end end # Define class methods here. module ClassMethods attr_accessor :proxies def remove_proxy name proxies.delete(name) end def proxy_for obj, *methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do - send(obj).send name + send(obj).send(name) if send(obj) end end end def proxy_accessors_for obj, *methods proxy_for obj, methods methods.flat_uniq.each do |meth| name = meth.to_sym define_method name do |arg| - obj.send "#{name}=", arg + obj.send("#{name}=", arg) if send(obj) end end end end # proxy to state def method_missing(name, *args, &block) self.class.proxies.each do |proxi| proxy_obj = self.send proxi - return proxy_obj.send name, *args, &block if proxy_obj.respond_to? :"#{name}" + return proxy_obj.send(name, *args, &block) if proxy_obj.respond_to? :"#{name}" end super end end end class Class def named_proxies hash raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash include Party::Proxy hash.each_pair do |proxy, methods| proxy_accessors_for proxy, methods end end def proxy *proxy_objs include Party::Proxy proxy_objs.flat_uniq.each do |proxy_obj| raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index fdd3076..0d2ef82 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,90 +1,110 @@ require 'spec_helper' class State attr_accessor :name def initialize(name) @name = name end end class Info attr_accessor :text def initialize(text) @text = text end end class Mic attr_accessor :speak def initialize(text) @speak = text end def speak_it! speak end end module Party class Subject attr_accessor :mic proxy :state, :info def initialize(name) @state = State.new name @info = Info.new 'hello' end end end describe Party::Proxy do describe '#proxy' do it "proxies state and info so it can call name directly on subject" do subject = Party::Subject.new 'kristian' subject.name.should == 'kristian' end end describe '#proxy_for' do it "proxies speak_it! on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' Party::Subject.proxy_for :mic, :speak_it! subject.proxy_for :mic, :speak_it! subject.speak_it!.should == 'hello' end + + it "handles proxy when the proxied object (mic) is nil" do + subject = Party::Subject.new 'kristian' + subject.proxy_for :mic, :speak_it! + subject.speak_it!.should == nil + end + + it "handles proxy when the proxied object (mic) is set to nil later" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + subject.proxy_for :mic, :speak_it!, :check => true + subject.mic = nil + subject.speak_it!.should == nil + end + + it "errors when proxy when the proxied object (mic) is nil and nil check is on" do + subject = Party::Subject.new 'kristian' + subject.mic = nil + lambda {subject.proxy_for :mic, :speak_it!, :check => true}.should raise_error + end end describe '#proxy_accessor_for' do it "proxies speak accessor methods on mic" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.proxy_accessors_for :mic, :speak subject.speak = 'do it!' subject.speak.should == 'do it!' end end describe '#named_proxies' do it "proxies select :mic and :state methods" do subject = Party::Subject.new 'kristian' subject.mic = Mic.new 'hello' subject.named_proxies :mic => :speak, :state => :name subject.speak = 'do it!' subject.speak.should == 'do it!' subject.name = 'kris' subject.name.should == 'kris' end end end
kristianmandrup/proxy_party
0ab5bd1923794503ac12179a1c63b3683701c264
fixed gemspec
diff --git a/.gitignore b/.gitignore index c1e0daf..d78daa1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,22 @@ ## MAC OS .DS_Store ## TEXTMATE *.tmproj tmtags ## EMACS *~ \#* .\#* ## VIM *.swp ## PROJECT::GENERAL coverage rdoc pkg +pkg/*.gem ## PROJECT::SPECIFIC diff --git a/proxy_party-0.2.0.gem b/proxy_party-0.2.0.gem deleted file mode 100644 index 91cafae..0000000 Binary files a/proxy_party-0.2.0.gem and /dev/null differ
kristianmandrup/proxy_party
91fdd7bae3a2f80909d5c52c9866ba36e9d25264
fix README
diff --git a/proxy_party.gemspec b/proxy_party.gemspec index 8ef6163..9346586 100644 --- a/proxy_party.gemspec +++ b/proxy_party.gemspec @@ -1,48 +1,48 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{proxy_party} s.version = "0.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Kristian Mandrup"] s.date = %q{2011-02-13} s.description = %q{Method missing proxy pattern} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", - "README.markdown" + "README.textile" ] s.files = [ ".document", ".gitignore", "LICENSE", "README.textile", "Rakefile", "VERSION", "lib/proxy_party.rb", ] s.homepage = %q{http://github.com/kristianmandrup/proxy_party} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Add proxy functionality the fun way} s.test_files = [ "spec/proxy_party_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
kristianmandrup/proxy_party
01e8b3a90079eddbeace5c0ad7779028bdd847af
new README
diff --git a/proxy_party.gemspec b/proxy_party.gemspec index d09c1e6..8ef6163 100644 --- a/proxy_party.gemspec +++ b/proxy_party.gemspec @@ -1,48 +1,48 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{proxy_party} s.version = "0.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Kristian Mandrup"] s.date = %q{2011-02-13} s.description = %q{Method missing proxy pattern} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".document", ".gitignore", "LICENSE", - "README.markdown", + "README.textile", "Rakefile", "VERSION", "lib/proxy_party.rb", ] s.homepage = %q{http://github.com/kristianmandrup/proxy_party} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Add proxy functionality the fun way} s.test_files = [ "spec/proxy_party_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
kristianmandrup/proxy_party
77ed023356ea6feb7bc40af52110f951bc30473c
bumped version
diff --git a/proxy_party-0.2.0.gem b/proxy_party-0.2.0.gem new file mode 100644 index 0000000..91cafae Binary files /dev/null and b/proxy_party-0.2.0.gem differ diff --git a/proxy_party.gemspec b/proxy_party.gemspec index 7bb5578..d09c1e6 100644 --- a/proxy_party.gemspec +++ b/proxy_party.gemspec @@ -1,51 +1,48 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{proxy_party} - s.version = "0.1.0" + s.version = "0.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Kristian Mandrup"] - s.date = %q{2010-06-30} + s.date = %q{2011-02-13} s.description = %q{Method missing proxy pattern} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".document", ".gitignore", "LICENSE", "README.markdown", "Rakefile", "VERSION", "lib/proxy_party.rb", - "spec/proxy_party_spec.rb", - "spec/spec.opts", - "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/kristianmandrup/proxy_party} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Add proxy functionality the fun way} s.test_files = [ "spec/proxy_party_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
kristianmandrup/proxy_party
743c36227e06296005ae73a5bc1673a7e776f0fb
major update and new features
diff --git a/spec/spec.opts b/.rspec similarity index 100% rename from spec/spec.opts rename to .rspec diff --git a/README.markdown b/README.markdown deleted file mode 100644 index e94c55b..0000000 --- a/README.markdown +++ /dev/null @@ -1,67 +0,0 @@ -# Proxy Party - -Greatly facilitates adding proxies through the proxy method_missing pattern - -## Install ## - -<code>$ gem install party_proxy</code> - -## Usage Configuration ## - -<code>require 'party_proxy'</code> - -## Usage ## - -<pre><code> - class State - attr_accessor :name - - def initialize(name) - @name = name - end - end - - class Info - attr_accessor :text - - def initialize(text) - @text = text - end - end - - module Party - class Subject - # proxy state and info objects to make their methods - # directly accessible from subject objects - proxy :state, :info - - def initialize(name) - @state = State.new name - @info = Info.new 'hello' - end - end - end - - subject = Party::Subject.new 'kristian' - # access 'name' directly through 'state' proxy - puts subject.name - # access 'text' directly through 'info' proxy - puts subject.text - -=> 'kristian' -=> 'hello' -</code></pre> - -## Note on Patches/Pull Requests ## - -* Fork the project. -* Make your feature addition or bug fix. -* Add tests for it. This is important so I don't break it in a - future version unintentionally. -* Commit, do not mess with rakefile, version, or history. - (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) -* Send me a pull request. Bonus points for topic branches. - -## Copyright ## - -Copyright (c) 2010 Kristian Mandrup. See LICENSE for details. diff --git a/README.textile b/README.textile new file mode 100644 index 0000000..17e5de7 --- /dev/null +++ b/README.textile @@ -0,0 +1,105 @@ +h1. Proxy Party + +Greatly facilitates adding proxies through the proxy method_missing pattern. +Can now also dynamically add proxy methods and use other amazing meta strategies! + +h2. Install + +@$ gem install party_proxy@ + +h2. Use + +@require 'party_proxy'@ + +h2. Usage + +<pre> + class State + attr_accessor :name + + def initialize(name) + @name = name + end + end + + class Info + attr_accessor :text + + def initialize(text) + @text = text + end + end + + module Party + class Subject + # proxy state and info objects to make their methods + # directly accessible from subject objects + proxy :state, :info + + def initialize(name) + @state = State.new name + @info = Info.new 'hello' + end + end + end +</pre> + +<pre> + describe Party::Proxy do + describe '#proxy' do + it "proxies state and info so it can call name directly on subject" do + subject = Party::Subject.new 'kristian' + subject.name.should == 'kristian' + end + end + + describe '#proxy_for' do + it "proxies speak_it! on mic" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + Party::Subject.proxy_for :mic, :speak_it! + + subject.proxy_for :mic, :speak_it! + + subject.speak_it!.should == 'hello' + end + end + + describe '#proxy_accessor_for' do + it "proxies speak accessor methods on mic" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + subject.proxy_accessors_for :mic, :speak + subject.speak = 'do it!' + subject.speak.should == 'do it!' + end + end + + describe '#named_proxies' do + it "proxies select :mic and :state methods" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + subject.named_proxies :mic => :speak, :state => :name + subject.speak = 'do it!' + subject.speak.should == 'do it!' + + subject.name = 'kris' + subject.name.should == 'kris' + end + end + end +</pre> + +h2. Note on Patches/Pull Requests + +* Fork the project. +* Make your feature addition or bug fix. +* Add tests for it. This is important so I don't break it in a + future version unintentionally. +* Commit, do not mess with rakefile, version, or history. + (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) +* Send me a pull request. Bonus points for topic branches. + +h2. Copyright + +Copyright (c) 2010 Kristian Mandrup. See LICENSE for details. diff --git a/Rakefile b/Rakefile index 0f78f68..3ada8d3 100644 --- a/Rakefile +++ b/Rakefile @@ -1,45 +1,23 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "proxy_party" gem.summary = %Q{Add proxy functionality the fun way} gem.description = %Q{Method missing proxy pattern} gem.email = "[email protected]" gem.homepage = "http://github.com/kristianmandrup/proxy_party" gem.authors = ["Kristian Mandrup"] - # gem.add_development_dependency "rspec", ">= 1.2.9" + + gem.add_dependency "sugar-high", ">= 0.3.5" + gem.add_development_dependency "rspec", ">= 2.4.0" + # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end -# require 'spec/rake/spectask' -# Spec::Rake::SpecTask.new(:spec) do |spec| -# spec.libs << 'lib' << 'spec' -# spec.spec_files = FileList['spec/**/*_spec.rb'] -# end -# -# Spec::Rake::SpecTask.new(:rcov) do |spec| -# spec.libs << 'lib' << 'spec' -# spec.pattern = 'spec/**/*_spec.rb' -# spec.rcov = true -# end -# -# task :spec => :check_dependencies -# -# task :default => :spec -# -# require 'rake/rdoctask' -# Rake::RDocTask.new do |rdoc| -# version = File.exist?('VERSION') ? File.read('VERSION') : "" -# -# rdoc.rdoc_dir = 'rdoc' -# rdoc.title = "proxy_party #{version}" -# rdoc.rdoc_files.include('README*') -# rdoc.rdoc_files.include('lib/**/*.rb') -# end diff --git a/VERSION b/VERSION index 6e8bf73..0ea3a94 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.0 +0.2.0 diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index 570761c..11bf785 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -1,34 +1,109 @@ +require 'sugar-high/array' +require 'sugar-high/kind_of' + module Party module Proxy def self.included(base) base.extend ClassMethods + base.send :include, InstanceMethods + end + + module InstanceMethods + def proxy_for obj, *methods + methods.flat_uniq.each do |meth| + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method to proxy for #{obj}" if !self.send(obj).respond_to?(meth) + instance_eval %{ + class << self + define_method :#{meth} do + #{obj}.send :#{meth} + end + end + } + end + end + + def proxy_accessors_for obj, *methods + proxy_for obj, methods + methods.flat_uniq.each do |meth| + raise ArgumentError, "No such object to proxy #{obj}" if !self.respond_to?(obj) + raise ArgumentError, "No such method #{meth} to proxy for #{obj}" if !self.send(obj).respond_to?(:"#{meth}=") + instance_eval %{ + class << self + define_method :#{meth}= do |arg| + #{obj}.send :#{meth}=, arg + end + end + } + end + end + + def named_proxies hash + raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash + self.class.send :include, Party::Proxy + hash.each_pair do |proxy, methods| + proxy_accessors_for proxy, methods + end + end end # Define class methods here. - module ClassMethods - attr_accessor :proxies + module ClassMethods + attr_accessor :proxies + + def remove_proxy name + proxies.delete(name) + end + + def proxy_for obj, *methods + methods.flat_uniq.each do |meth| + name = meth.to_sym + define_method name do + send(obj).send name + end + end + end + + def proxy_accessors_for obj, *methods + proxy_for obj, methods + methods.flat_uniq.each do |meth| + name = meth.to_sym + define_method name do |arg| + obj.send "#{name}=", arg + end + end + end end # proxy to state def method_missing(name, *args, &block) self.class.proxies.each do |proxi| proxy_obj = self.send proxi return proxy_obj.send name, *args, &block if proxy_obj.respond_to? :"#{name}" end super end end end class Class + def named_proxies hash + raise ArgumentError, "Argument must be a hash" if !hash.kind_of? Hash + include Party::Proxy + hash.each_pair do |proxy, methods| + proxy_accessors_for proxy, methods + end + end + def proxy *proxy_objs include Party::Proxy - proxy_objs.each do |proxy_obj| + proxy_objs.flat_uniq.each do |proxy_obj| + raise ArgumentError, "bad proxy object #{proxy_obj}" if !proxy_obj.kind_of_label? attr_accessor proxy_obj @proxies ||= [] - @proxies << proxy_obj + @proxies << proxy_obj if [email protected]? proxy_obj end end end \ No newline at end of file diff --git a/proxy_party.gemspec b/proxy_party.gemspec new file mode 100644 index 0000000..7bb5578 --- /dev/null +++ b/proxy_party.gemspec @@ -0,0 +1,51 @@ +# Generated by jeweler +# DO NOT EDIT THIS FILE DIRECTLY +# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command +# -*- encoding: utf-8 -*- + +Gem::Specification.new do |s| + s.name = %q{proxy_party} + s.version = "0.1.0" + + s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.authors = ["Kristian Mandrup"] + s.date = %q{2010-06-30} + s.description = %q{Method missing proxy pattern} + s.email = %q{[email protected]} + s.extra_rdoc_files = [ + "LICENSE", + "README.markdown" + ] + s.files = [ + ".document", + ".gitignore", + "LICENSE", + "README.markdown", + "Rakefile", + "VERSION", + "lib/proxy_party.rb", + "spec/proxy_party_spec.rb", + "spec/spec.opts", + "spec/spec_helper.rb" + ] + s.homepage = %q{http://github.com/kristianmandrup/proxy_party} + s.rdoc_options = ["--charset=UTF-8"] + s.require_paths = ["lib"] + s.rubygems_version = %q{1.3.7} + s.summary = %q{Add proxy functionality the fun way} + s.test_files = [ + "spec/proxy_party_spec.rb", + "spec/spec_helper.rb" + ] + + if s.respond_to? :specification_version then + current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION + s.specification_version = 3 + + if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then + else + end + else + end +end + diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index eaa7b00..fdd3076 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,37 +1,90 @@ -require File.expand_path(File.dirname(__FILE__) + '/spec_helper') +require 'spec_helper' class State attr_accessor :name def initialize(name) @name = name end end class Info attr_accessor :text def initialize(text) @text = text end end +class Mic + attr_accessor :speak + + def initialize(text) + @speak = text + end + + def speak_it! + speak + end +end + + module Party class Subject + attr_accessor :mic + proxy :state, :info def initialize(name) @state = State.new name @info = Info.new 'hello' end end end describe Party::Proxy do - it "proxies state so it can call name directly on subject" do - subject = Party::Subject.new 'kristian' - subject.name.should == 'kristian' - subject.text.should == 'hello' + describe '#proxy' do + it "proxies state and info so it can call name directly on subject" do + subject = Party::Subject.new 'kristian' + subject.name.should == 'kristian' + end + end + + describe '#proxy_for' do + it "proxies speak_it! on mic" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + Party::Subject.proxy_for :mic, :speak_it! + + subject.proxy_for :mic, :speak_it! + + subject.speak_it!.should == 'hello' + end + end + + describe '#proxy_accessor_for' do + it "proxies speak accessor methods on mic" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + subject.proxy_accessors_for :mic, :speak + subject.speak = 'do it!' + subject.speak.should == 'do it!' + end + end + + describe '#named_proxies' do + it "proxies select :mic and :state methods" do + subject = Party::Subject.new 'kristian' + subject.mic = Mic.new 'hello' + subject.named_proxies :mic => :speak, :state => :name + subject.speak = 'do it!' + subject.speak.should == 'do it!' + + subject.name = 'kris' + subject.name.should == 'kris' + end end end + + diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index e03cc99..201a2c0 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,3 +1,3 @@ require 'rspec' -require 'rspec/autorun' +# require 'rspec/autorun' require 'proxy_party'
kristianmandrup/proxy_party
fa5ba9f8f4471d237420a5ee41718b12b9762db4
initial release
diff --git a/README.markdown b/README.markdown new file mode 100644 index 0000000..e94c55b --- /dev/null +++ b/README.markdown @@ -0,0 +1,67 @@ +# Proxy Party + +Greatly facilitates adding proxies through the proxy method_missing pattern + +## Install ## + +<code>$ gem install party_proxy</code> + +## Usage Configuration ## + +<code>require 'party_proxy'</code> + +## Usage ## + +<pre><code> + class State + attr_accessor :name + + def initialize(name) + @name = name + end + end + + class Info + attr_accessor :text + + def initialize(text) + @text = text + end + end + + module Party + class Subject + # proxy state and info objects to make their methods + # directly accessible from subject objects + proxy :state, :info + + def initialize(name) + @state = State.new name + @info = Info.new 'hello' + end + end + end + + subject = Party::Subject.new 'kristian' + # access 'name' directly through 'state' proxy + puts subject.name + # access 'text' directly through 'info' proxy + puts subject.text + +=> 'kristian' +=> 'hello' +</code></pre> + +## Note on Patches/Pull Requests ## + +* Fork the project. +* Make your feature addition or bug fix. +* Add tests for it. This is important so I don't break it in a + future version unintentionally. +* Commit, do not mess with rakefile, version, or history. + (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) +* Send me a pull request. Bonus points for topic branches. + +## Copyright ## + +Copyright (c) 2010 Kristian Mandrup. See LICENSE for details.
kristianmandrup/proxy_party
310f4e20535ca63996913ed12d6ce615442b4f59
Version bump to 0.1.0
diff --git a/VERSION b/VERSION index 77d6f4c..6e8bf73 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.0 +0.1.0
kristianmandrup/proxy_party
0daa5d717157961aa60cef47d5816274c4f4170d
Version bump to 0.0.0
diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..77d6f4c --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.0.0
kristianmandrup/proxy_party
26d0873abbf97594d026fc47529d5c57bc786e6f
initial party proxy code
diff --git a/README.rdoc b/README.rdoc deleted file mode 100644 index 9128331..0000000 --- a/README.rdoc +++ /dev/null @@ -1,17 +0,0 @@ -= proxy_party - -Description goes here. - -== Note on Patches/Pull Requests - -* Fork the project. -* Make your feature addition or bug fix. -* Add tests for it. This is important so I don't break it in a - future version unintentionally. -* Commit, do not mess with rakefile, version, or history. - (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) -* Send me a pull request. Bonus points for topic branches. - -== Copyright - -Copyright (c) 2010 Kristian Mandrup. See LICENSE for details. diff --git a/Rakefile b/Rakefile index 31d1b40..0f78f68 100644 --- a/Rakefile +++ b/Rakefile @@ -1,45 +1,45 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "proxy_party" - gem.summary = %Q{TODO: one-line summary of your gem} - gem.description = %Q{TODO: longer description of your gem} + gem.summary = %Q{Add proxy functionality the fun way} + gem.description = %Q{Method missing proxy pattern} gem.email = "[email protected]" gem.homepage = "http://github.com/kristianmandrup/proxy_party" gem.authors = ["Kristian Mandrup"] - gem.add_development_dependency "rspec", ">= 1.2.9" + # gem.add_development_dependency "rspec", ">= 1.2.9" # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end -require 'spec/rake/spectask' -Spec::Rake::SpecTask.new(:spec) do |spec| - spec.libs << 'lib' << 'spec' - spec.spec_files = FileList['spec/**/*_spec.rb'] -end - -Spec::Rake::SpecTask.new(:rcov) do |spec| - spec.libs << 'lib' << 'spec' - spec.pattern = 'spec/**/*_spec.rb' - spec.rcov = true -end - -task :spec => :check_dependencies - -task :default => :spec - -require 'rake/rdoctask' -Rake::RDocTask.new do |rdoc| - version = File.exist?('VERSION') ? File.read('VERSION') : "" - - rdoc.rdoc_dir = 'rdoc' - rdoc.title = "proxy_party #{version}" - rdoc.rdoc_files.include('README*') - rdoc.rdoc_files.include('lib/**/*.rb') -end +# require 'spec/rake/spectask' +# Spec::Rake::SpecTask.new(:spec) do |spec| +# spec.libs << 'lib' << 'spec' +# spec.spec_files = FileList['spec/**/*_spec.rb'] +# end +# +# Spec::Rake::SpecTask.new(:rcov) do |spec| +# spec.libs << 'lib' << 'spec' +# spec.pattern = 'spec/**/*_spec.rb' +# spec.rcov = true +# end +# +# task :spec => :check_dependencies +# +# task :default => :spec +# +# require 'rake/rdoctask' +# Rake::RDocTask.new do |rdoc| +# version = File.exist?('VERSION') ? File.read('VERSION') : "" +# +# rdoc.rdoc_dir = 'rdoc' +# rdoc.title = "proxy_party #{version}" +# rdoc.rdoc_files.include('README*') +# rdoc.rdoc_files.include('lib/**/*.rb') +# end diff --git a/lib/proxy_party.rb b/lib/proxy_party.rb index e69de29..570761c 100644 --- a/lib/proxy_party.rb +++ b/lib/proxy_party.rb @@ -0,0 +1,34 @@ +module Party + module Proxy + + def self.included(base) + base.extend ClassMethods + end + + # Define class methods here. + module ClassMethods + attr_accessor :proxies + end + + # proxy to state + def method_missing(name, *args, &block) + self.class.proxies.each do |proxi| + proxy_obj = self.send proxi + return proxy_obj.send name, *args, &block if proxy_obj.respond_to? :"#{name}" + end + super + end + end +end + +class Class + def proxy *proxy_objs + include Party::Proxy + + proxy_objs.each do |proxy_obj| + attr_accessor proxy_obj + @proxies ||= [] + @proxies << proxy_obj + end + end +end \ No newline at end of file diff --git a/spec/proxy_party_spec.rb b/spec/proxy_party_spec.rb index 66d70c3..eaa7b00 100644 --- a/spec/proxy_party_spec.rb +++ b/spec/proxy_party_spec.rb @@ -1,7 +1,37 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') -describe "ProxyParty" do - it "fails" do - fail "hey buddy, you should probably rename this file and start specing for real" +class State + attr_accessor :name + + def initialize(name) + @name = name + end +end + +class Info + attr_accessor :text + + def initialize(text) + @text = text + end +end + + +module Party + class Subject + proxy :state, :info + + def initialize(name) + @state = State.new name + @info = Info.new 'hello' + end + end +end + +describe Party::Proxy do + it "proxies state so it can call name directly on subject" do + subject = Party::Subject.new 'kristian' + subject.name.should == 'kristian' + subject.text.should == 'hello' end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 1601bb8..e03cc99 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,9 +1,3 @@ -$LOAD_PATH.unshift(File.dirname(__FILE__)) -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) +require 'rspec' +require 'rspec/autorun' require 'proxy_party' -require 'spec' -require 'spec/autorun' - -Spec::Runner.configure do |config| - -end
parrot-studio/rdgc-dm
38d6220ab296cb5ba7c737039ae2af79f12eb50d
構築をjewelerからbundlerに変更
diff --git a/.gitignore b/.gitignore index f013ea7..fa58148 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,6 @@ -## MAC OS -.DS_Store - -## TEXTMATE -*.tmproj -tmtags - -## EMACS -*~ -\#* -.\#* - -## VIM -*.swp - -## PROJECT::GENERAL -coverage -rdoc -pkg - -## PROJECT::SPECIFIC +*.gem +.bundle +Gemfile.lock +pkg/* +rdoc + diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..a1d278f --- /dev/null +++ b/Gemfile @@ -0,0 +1,4 @@ +source "http://rubygems.org" + +# Specify your gem's dependencies in rdgc-dm.gemspec +gemspec diff --git a/Rakefile b/Rakefile index 302bf0d..23a79da 100644 --- a/Rakefile +++ b/Rakefile @@ -1,50 +1,10 @@ -require 'rubygems' -require 'rake' - -begin - require 'jeweler' - Jeweler::Tasks.new do |gem| - gem.name = "rdgc-dm" - gem.summary = %Q{Random Dungeon Maker from RDGC} - gem.description = <<-TXT - This gem is part of RDGC - Ruby(Random) Dungeon Game Core. - RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. - TXT - gem.email = "[email protected]" - gem.homepage = "http://github.com/parrot-studio/rdgc-dm" - gem.authors = ["parrot_studio"] - gem.required_ruby_version = ">= 1.8.7" - #gem.add_development_dependency "rspec", ">= 1.2.9" - # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings - end - Jeweler::GemcutterTasks.new -rescue LoadError - puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" -end - -require 'spec/rake/spectask' -Spec::Rake::SpecTask.new(:spec) do |spec| - spec.libs << 'lib' << 'spec' - spec.spec_files = FileList['spec/**/*_spec.rb'] -end - -Spec::Rake::SpecTask.new(:rcov) do |spec| - spec.libs << 'lib' << 'spec' - spec.pattern = 'spec/**/*_spec.rb' - spec.rcov = true -end - -task :spec => :check_dependencies - -task :default => :spec - -require 'rake/rdoctask' -Rake::RDocTask.new do |rdoc| - version = File.exist?('VERSION') ? File.read('VERSION') : "" - - rdoc.rdoc_dir = 'rdoc' - rdoc.title = "rdgc-dm #{version}" - rdoc.rdoc_files.include('README*') - rdoc.rdoc_files.include('lib/**/*.rb') - rdoc.options << '-S' << '-N' << '-c UTF8' -end +require "bundler/gem_tasks" + +require 'rspec/core' +require 'rspec/core/rake_task' +RSpec::Core::RakeTask.new(:spec) do |spec| + spec.pattern = FileList['spec/**/*_spec.rb'] +end + +task :default => :spec + diff --git a/VERSION b/VERSION deleted file mode 100644 index f477849..0000000 --- a/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.2.2 \ No newline at end of file diff --git a/lib/rdgc-dm/version.rb b/lib/rdgc-dm/version.rb new file mode 100644 index 0000000..22c42b0 --- /dev/null +++ b/lib/rdgc-dm/version.rb @@ -0,0 +1,5 @@ +module Rdgc + module Dm + VERSION = "0.2.3" + end +end diff --git a/rdgc-dm.gemspec b/rdgc-dm.gemspec index 6d55c42..8eef836 100644 --- a/rdgc-dm.gemspec +++ b/rdgc-dm.gemspec @@ -1,94 +1,27 @@ -# Generated by jeweler -# DO NOT EDIT THIS FILE DIRECTLY -# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- +$:.push File.expand_path("../lib", __FILE__) +require "rdgc-dm/version" Gem::Specification.new do |s| - s.name = %q{rdgc-dm} - s.version = "0.2.2" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.authors = ["parrot_studio"] - s.date = %q{2011-01-22} - s.description = %q{ This gem is part of RDGC - Ruby(Random) Dungeon Game Core. + s.name = "rdgc-dm" + s.version = Rdgc::Dm::VERSION + s.authors = ["parrot_studio", "parrot-studio"] + s.email = ["[email protected]", "[email protected]"] + s.homepage = "http://github.com/parrot-studio/rdgc-dm" + s.summary = %q{Random Dungeon Maker from RDGC} + s.description = %q{ + This gem is part of RDGC - Ruby(Random) Dungeon Game Core. RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. -} - s.email = %q{[email protected]} - s.extra_rdoc_files = [ - "LICENSE", - "README.rdoc" - ] - s.files = [ - ".document", - "LICENSE", - "README.rdoc", - "Rakefile", - "VERSION", - "lib/rdgc-dm.rb", - "lib/rdgc/maker/divide_dungeon_maker.rb", - "lib/rdgc/maker/divide_temp_block.rb", - "lib/rdgc/maker/dungeon_maker.rb", - "lib/rdgc/maker/temp_block.rb", - "lib/rdgc/map/area.rb", - "lib/rdgc/map/blind_area.rb", - "lib/rdgc/map/block.rb", - "lib/rdgc/map/board.rb", - "lib/rdgc/map/direction.rb", - "lib/rdgc/map/road.rb", - "lib/rdgc/map/room.rb", - "lib/rdgc/map/tile.rb", - "lib/rdgc/map/tile_type.rb", - "lib/rdgc/util/config.rb", - "lib/rdgc/util/random_util.rb", - "rdgc-dm.gemspec", - "spec/rdgc/maker/01_temp_block_spec.rb", - "spec/rdgc/maker/02_divide_temp_block_spec.rb", - "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb", - "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", - "spec/rdgc/map/01_tile_spec.rb", - "spec/rdgc/map/02_area_spec.rb", - "spec/rdgc/map/03_road_spec.rb", - "spec/rdgc/map/04_room_spec.rb", - "spec/rdgc/map/05_block_spec.rb", - "spec/rdgc/map/06_board_spec.rb", - "spec/rdgc/map/07_direction_spec.rb", - "spec/rdgc/map/08_blind_area_spec.rb", - "spec/rdgc/util/01_config_spec.rb", - "spec/rdgc/util/02_random_util_spec.rb", - "spec/spec.opts", - "spec/spec_helper.rb" - ] - s.homepage = %q{http://github.com/parrot-studio/rdgc-dm} - s.require_paths = ["lib"] - s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") - s.rubygems_version = %q{1.3.7} - s.summary = %q{Random Dungeon Maker from RDGC} - s.test_files = [ - "spec/rdgc/maker/01_temp_block_spec.rb", - "spec/rdgc/maker/02_divide_temp_block_spec.rb", - "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb", - "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", - "spec/rdgc/map/01_tile_spec.rb", - "spec/rdgc/map/02_area_spec.rb", - "spec/rdgc/map/03_road_spec.rb", - "spec/rdgc/map/04_room_spec.rb", - "spec/rdgc/map/05_block_spec.rb", - "spec/rdgc/map/06_board_spec.rb", - "spec/rdgc/map/07_direction_spec.rb", - "spec/rdgc/map/08_blind_area_spec.rb", - "spec/rdgc/util/01_config_spec.rb", - "spec/rdgc/util/02_random_util_spec.rb", - "spec/spec_helper.rb" - ] + } - if s.respond_to? :specification_version then - current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION - s.specification_version = 3 + s.rubyforge_project = "rdgc-dm" - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - else - end - else - end -end + s.files = `git ls-files`.split("\n") + s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") + s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } + s.require_paths = ["lib"] + # specify any dependencies here; for example: + s.add_development_dependency "rspec" + # s.add_runtime_dependency "rest-client" +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index dd0ec27..7ebf54d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,11 +1,7 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'rdgc-dm' -require 'spec' -require 'spec/autorun' +require 'rspec' include RDGC -Spec::Runner.configure do |config| - -end
parrot-studio/rdgc-dm
82880fbaeb37a7cabc02dab8e5303cf785a99223
Regenerate gemspec for version 0.2.2
diff --git a/rdgc-dm.gemspec b/rdgc-dm.gemspec index 6fa26e1..6d55c42 100644 --- a/rdgc-dm.gemspec +++ b/rdgc-dm.gemspec @@ -1,96 +1,94 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY -# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command +# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{rdgc-dm} - s.version = "0.2.1" + s.version = "0.2.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["parrot_studio"] - s.date = %q{2010-09-22} + s.date = %q{2011-01-22} s.description = %q{ This gem is part of RDGC - Ruby(Random) Dungeon Game Core. RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. } s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", - "README.rdoc" + "README.rdoc" ] s.files = [ ".document", - ".gitignore", - "LICENSE", - "README.rdoc", - "Rakefile", - "VERSION", - "lib/rdgc-dm.rb", - "lib/rdgc/maker/divide_dungeon_maker.rb", - "lib/rdgc/maker/divide_temp_block.rb", - "lib/rdgc/maker/dungeon_maker.rb", - "lib/rdgc/maker/temp_block.rb", - "lib/rdgc/map/area.rb", - "lib/rdgc/map/blind_area.rb", - "lib/rdgc/map/block.rb", - "lib/rdgc/map/board.rb", - "lib/rdgc/map/direction.rb", - "lib/rdgc/map/road.rb", - "lib/rdgc/map/room.rb", - "lib/rdgc/map/tile.rb", - "lib/rdgc/map/tile_type.rb", - "lib/rdgc/util/config.rb", - "lib/rdgc/util/random_util.rb", - "rdgc-dm.gemspec", - "spec/rdgc/maker/01_temp_block_spec.rb", - "spec/rdgc/maker/02_divide_temp_block_spec.rb", - "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb", - "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", - "spec/rdgc/map/01_tile_spec.rb", - "spec/rdgc/map/02_area_spec.rb", - "spec/rdgc/map/03_road_spec.rb", - "spec/rdgc/map/04_room_spec.rb", - "spec/rdgc/map/05_block_spec.rb", - "spec/rdgc/map/06_board_spec.rb", - "spec/rdgc/map/07_direction_spec.rb", - "spec/rdgc/map/08_blind_area_spec.rb", - "spec/rdgc/util/01_config_spec.rb", - "spec/rdgc/util/02_random_util_spec.rb", - "spec/spec.opts", - "spec/spec_helper.rb" + "LICENSE", + "README.rdoc", + "Rakefile", + "VERSION", + "lib/rdgc-dm.rb", + "lib/rdgc/maker/divide_dungeon_maker.rb", + "lib/rdgc/maker/divide_temp_block.rb", + "lib/rdgc/maker/dungeon_maker.rb", + "lib/rdgc/maker/temp_block.rb", + "lib/rdgc/map/area.rb", + "lib/rdgc/map/blind_area.rb", + "lib/rdgc/map/block.rb", + "lib/rdgc/map/board.rb", + "lib/rdgc/map/direction.rb", + "lib/rdgc/map/road.rb", + "lib/rdgc/map/room.rb", + "lib/rdgc/map/tile.rb", + "lib/rdgc/map/tile_type.rb", + "lib/rdgc/util/config.rb", + "lib/rdgc/util/random_util.rb", + "rdgc-dm.gemspec", + "spec/rdgc/maker/01_temp_block_spec.rb", + "spec/rdgc/maker/02_divide_temp_block_spec.rb", + "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb", + "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", + "spec/rdgc/map/01_tile_spec.rb", + "spec/rdgc/map/02_area_spec.rb", + "spec/rdgc/map/03_road_spec.rb", + "spec/rdgc/map/04_room_spec.rb", + "spec/rdgc/map/05_block_spec.rb", + "spec/rdgc/map/06_board_spec.rb", + "spec/rdgc/map/07_direction_spec.rb", + "spec/rdgc/map/08_blind_area_spec.rb", + "spec/rdgc/util/01_config_spec.rb", + "spec/rdgc/util/02_random_util_spec.rb", + "spec/spec.opts", + "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/parrot-studio/rdgc-dm} - s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") s.rubygems_version = %q{1.3.7} s.summary = %q{Random Dungeon Maker from RDGC} s.test_files = [ - "spec/spec_helper.rb", - "spec/rdgc/util/02_random_util_spec.rb", - "spec/rdgc/util/01_config_spec.rb", - "spec/rdgc/map/04_room_spec.rb", - "spec/rdgc/map/06_board_spec.rb", - "spec/rdgc/map/01_tile_spec.rb", - "spec/rdgc/map/03_road_spec.rb", - "spec/rdgc/map/08_blind_area_spec.rb", - "spec/rdgc/map/07_direction_spec.rb", - "spec/rdgc/map/05_block_spec.rb", - "spec/rdgc/map/02_area_spec.rb", - "spec/rdgc/maker/02_divide_temp_block_spec.rb", - "spec/rdgc/maker/01_temp_block_spec.rb", - "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", - "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb" + "spec/rdgc/maker/01_temp_block_spec.rb", + "spec/rdgc/maker/02_divide_temp_block_spec.rb", + "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb", + "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", + "spec/rdgc/map/01_tile_spec.rb", + "spec/rdgc/map/02_area_spec.rb", + "spec/rdgc/map/03_road_spec.rb", + "spec/rdgc/map/04_room_spec.rb", + "spec/rdgc/map/05_block_spec.rb", + "spec/rdgc/map/06_board_spec.rb", + "spec/rdgc/map/07_direction_spec.rb", + "spec/rdgc/map/08_blind_area_spec.rb", + "spec/rdgc/util/01_config_spec.rb", + "spec/rdgc/util/02_random_util_spec.rb", + "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
parrot-studio/rdgc-dm
cd50da97985ad17f2d30f3b434da393895a0b9cf
ダンジョン生成パラメータを変更
diff --git a/lib/rdgc/maker/divide_dungeon_maker.rb b/lib/rdgc/maker/divide_dungeon_maker.rb index db643b1..df02577 100644 --- a/lib/rdgc/maker/divide_dungeon_maker.rb +++ b/lib/rdgc/maker/divide_dungeon_maker.rb @@ -1,371 +1,403 @@ # coding: UTF-8 module RDGC module Maker class DivideDungeonMaker include DungeonMaker def self.create(width, height, params = nil) dm = self.new list = dm.make(width, height, params) Map::Board.create_from_blocks(list) end DEFAULT_CROSS_ROAD_RATIO = 2 # override def create_whole_block(width, height) tb = DivideTempBlock.create_whole_block(width, height) tb.min_size = min_block_size tb.dividable tb end def make_blocks(tb) # 分割キューに最初のBlockを入れる divide_queue << tb # 再帰分割 divide # 完了キューの中身を返す done_queue end # override def create_room - # 部屋と交差点を分ける - room_blocks = [] - cross_blocks = [] - force_room_blocks = [] - - param = { - :room => (10 - cross_road_ratio), - :cross => cross_road_ratio - } - - blocks.each do |b| - # 初回分割のBlockは行き止まりになるので避ける - if b.depth < 2 - force_room_blocks << b - next - end - - r = select_rand(param) - case r - when :room - room_blocks << b - when :cross - cross_blocks << b - end - end - - room_count = room_blocks.size + force_room_blocks.size - if max_room_count > 0 && room_count > max_room_count - # 超えた分だけ移動する - (room_count - max_room_count).times do - break if room_blocks.size + force_room_blocks.size <= 1 - break if room_blocks.empty? - b = room_blocks.pickup! - cross_blocks << b if b - end - end - - room_count = room_blocks.size + force_room_blocks.size - if room_count < min_room_count - # 足りない分を移動する - (min_room_count - room_count).times do - break if cross_blocks.empty? - b = cross_blocks.pickup! - room_blocks << b if b - end - end - - # それぞれのblockを処理 - [room_blocks, force_room_blocks].flatten.each do |b| - b.create_room(:min => min_room_size, :max => max_room_size) - end - cross_blocks.each{|b| b.create_cross_point} + force_room_count ? create_room_force : create_room_normal end # override def create_road return if blocks.size <= 1 # 再帰的に道を作成 recursive_road_create(blocks.choice) # 道がない部屋で、既存と接しているところを処理 connect_cling_block_has_road # 道がなく、孤立した部屋を移動 move_room_and_connect # 行き止まりの交差点を処理 add_road_for_dead_end end # ------------------------------------------------------------- def min_block_size unless @min_block_size val = params[:min_block_size] if val # 指定がある場合はそれを評価 val = val.to_i else # 指定が無く、min_room_sizeが存在するならそちらに合わせる val = (min_room_size ? min_room_size + 3 : 0) end val = Util::Config.min_block_size if val < Util::Config.min_block_size @min_block_size = val end @min_block_size end def min_room_size params[:min_room_size] end def max_room_size params[:max_room_size] end + def min_block_count + params[:min_block_count].to_i + end + def max_block_count params[:max_block_count].to_i end def min_room_count + return force_room_count if force_room_count unless @min_room_count val = params[:min_room_count].to_i - # 明示的に「1」という指定がない限り2部屋は作る - val = 2 if val <= 0 - @min_room_count = val + # force_room_countを使わない限り、1部屋・部屋なしは作れない + @min_room_count = (val > 2 ? val : 2) end @min_room_count end def max_room_count params[:max_room_count].to_i end def max_depth params[:max_depth].to_i end def cross_road_ratio unless @cross_road_ratio val = params[:cross_road_ratio] if val val = val.to_i # 交差点生成率は 1<=x<=9 / 10 val = DEFAULT_CROSS_ROAD_RATIO if (val < 0 || val > 9) else # 指定なし => デフォルト val = DEFAULT_CROSS_ROAD_RATIO end @cross_road_ratio = val end @cross_road_ratio end + def force_room_count + params[:force_room_count] + end + def divide_queue @divide_queue ||= [] @divide_queue end def done_queue @done_queue ||= [] @done_queue end def queue_size divide_queue.size + done_queue.size end def finish? return true if divide_queue.empty? return true if (max_block_count > 0 && queue_size >= max_block_count) false end def dividable_block?(b) # そもそも分割対象ではない => false return false unless b.dividable? # 最大深度の指定がない => true return true if max_depth <= 0 # 最大深度に達したら分割しない b.depth >= max_depth ? false : true end def divide # 再帰処理 loop do break if finish? tb = divide_queue.shift break unless tb list = tb.divide unless list # 分割できなかったので、元をdone_queueへ done_queue << tb break end list.each do |b| if dividable_block?(b) divide_queue << b else done_queue << b end end end # queueをまとめる divide_queue.each{|b| done_queue << b} + + # 作成した結果、まだdividableのものがあり、数が足りないなら分割 + if min_block_count > 0 && done_queue.size < min_block_count + (min_block_count - queue_size).times do + tb = done_queue.select{|b| b.dividable_size?}.shuffle.shift + break unless tb + done_queue.delete(tb) + tb.divide.each{|b| done_queue << b} + end + end + end + + def create_room_normal + # 部屋と交差点を分ける + room_blocks = [] + cross_blocks = [] + force_room_blocks = [] + + param = { + :room => (10 - cross_road_ratio), + :cross => cross_road_ratio + } + + blocks.each do |b| + # 初回分割のBlockは行き止まりになるので避ける + if b.depth < 2 + force_room_blocks << b + next + end + + r = select_rand(param) + case r + when :room + room_blocks << b + when :cross + cross_blocks << b + end + end + + room_count = room_blocks.size + force_room_blocks.size + if max_room_count > 0 && room_count > max_room_count + # 超えた分だけ移動する + (room_count - max_room_count).times do + break if room_blocks.size + force_room_blocks.size <= 1 + break if room_blocks.empty? + b = room_blocks.pickup! + cross_blocks << b if b + end + end + + room_count = room_blocks.size + force_room_blocks.size + if room_count < min_room_count + # 足りない分を移動する + (min_room_count - room_count).times do + break if cross_blocks.empty? + b = cross_blocks.pickup! + room_blocks << b if b + end + end + + # それぞれのblockを処理 + [room_blocks, force_room_blocks].flatten.each do |b| + b.create_room(:min => min_room_size, :max => max_room_size) + end + cross_blocks.each{|b| b.create_cross_point} + end + + def create_room_force + blocks.shuffle.each.with_index do |b, i| + if (i+1) <= force_room_count.to_i + b.create_room(:min => min_room_size, :max => max_room_size) + else + b.create_cross_point + end + end end # ------------------------------------------------------------- def recursive_road_create(target) # 全部道がつながったら終了 return if blocks.all?{|b| b.has_road?} # まだ道の処理をしてない、接しているblockを探す yet_block = blocks.reject{|b| b.road_created?} cling_list = create_cling_list(target, yet_block) # 行き止まり => 終了 return if cling_list.size <= 0 # 接しているblockに道を作る next_block = connect_cling_blocks(target, cling_list) # 作成完了 target.road_created # 次を再帰的呼び出し recursive_road_create(next_block) end def connect_cling_block_has_road # 道がない部屋を探す remains = blocks.select{|b| b.has_room? && ! b.has_road?} return if remains.empty? # すでに完了しているblockの数を確認 done_count = blocks.select{|b| b.has_room? && b.has_road?}.size remains.each do |target| # min_room_countを満たすならランダム if done_count >= min_room_count next unless bool_rand end # 接しているblockに道があるならつなぐ c_list = create_cling_list(target, blocks.select{|b| b.has_road?}).flatten return if c_list.empty? target.create_road_to(c_list.pickup!) c_list.each{|b| target.add_remain_cling_blocks(b)} done_count += 1 end end def move_room_and_connect # 完了してしたblockの数を確認し、min_room_countを満たしていたら終わり done_count = blocks.select{|b| b.has_room? && b.has_road?}.size return if done_count >= min_room_count # まだ道がない部屋を探す remains = blocks.select{|b| b.has_room? && ! b.has_road?} return if remains.empty? remains.each do |target| # 元の部屋等の削除 target.remove_all # 改めて部屋を作る先を決める enable_blocks = blocks.select{|b| b.has_remain_cling_blocks?} next if enable_blocks.empty? org_block = enable_blocks.choice room_block = org_block.remain_cling_blocks.pickup! # 部屋作成 room_block.create_room(:min => min_room_size, :max => max_room_size) # 接続 room_block.create_road_to(org_block) end end def create_cling_list(block, list) top_list = collect_cling_block(block, list,:top) bottom_list = collect_cling_block(block, list, :bottom) left_list = collect_cling_block(block, list, :left) right_list = collect_cling_block(block, list, :right) [top_list, bottom_list, left_list, right_list].select{|a| a.size > 0} end def collect_cling_block(block, list, direction) case direction when :top list.select{|b| block.cling_to_top?(b)} when :bottom list.select{|b| block.cling_to_bottom?(b)} when :left list.select{|b| block.cling_to_left?(b)} when :right list.select{|b| block.cling_to_right?(b)} end end def connect_cling_blocks(target, cling_list) return unless cling_list return if cling_list.size <= 0 # 4方向で選択可能なblock配列から一つ選ぶ direction_list = cling_list.pickup! next_block = direction_list.pickup! # ブロックに道をつなぐ target.create_road_to(next_block) # その方向の残りを接しているblockとして記録 direction_list.each{|b| target.add_remain_cling_blocks(b)} # 残りの方向もランダムにつなぐ cling_list.each do |d_list| bl = d_list.pickup! if bool_rand target.create_road_to(bl) if bl d_list.each{|b| target.add_remain_cling_blocks(b)} end # 次の対象返却 next_block end def add_road_for_dead_end deadends = blocks.select{|b| b.dead_end?} return if deadends.empty? deadends.each do |target| # まだ作成していない方向に何か接しているか? c_list = [] block_list = blocks.select{|b| b.has_road?} target.remain_direction.each do |d| ret = collect_cling_block(target, block_list, d) c_list += ret.flatten end next if c_list.empty? target.create_road_to(c_list.pickup!) end end end end end diff --git a/spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb b/spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb index bbd6cdc..b044511 100644 --- a/spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb +++ b/spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb @@ -1,224 +1,260 @@ # coding: UTF-8 require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') include RDGC::Map include RDGC::Maker describe RDGC::Maker::DivideDungeonMaker, 'is divide block by recursive' do describe "each acceptable params" do it "min_room_size, max_room_size" do maker = DivideDungeonMaker.new maker.min_room_size.should be_nil maker.max_room_size.should be_nil maker.params[:min_room_size] = 5 maker.params[:max_room_size] = 20 maker.min_room_size.should == 5 maker.max_room_size.should == 20 end it "min_block_size" do # デフォルト maker = DivideDungeonMaker.new maker.min_block_size.should == Util::Config.min_block_size # デフォルトより小さいとデフォルト maker = DivideDungeonMaker.new maker.params[:min_block_size] = 1 maker.min_block_size.should == Util::Config.min_block_size maker = DivideDungeonMaker.new maker.params[:min_block_size] = 10 maker.min_block_size.should == 10 # 一度読むと書き換えできない maker.params[:min_block_size] = 20 maker.min_block_size.should == 10 # min_room_sizeが存在し、min_block_sizeが存在しない場合、影響を受ける maker = DivideDungeonMaker.new maker.params[:min_room_size] = 5 maker.min_block_size.should == 8 end it "min_room_count" do # デフォルトは2 maker = DivideDungeonMaker.new maker.min_room_count.should == 2 # 値は一度だけセットできる maker = DivideDungeonMaker.new maker.params[:min_room_count] = 3 maker.min_room_count.should == 3 maker.params[:min_room_count] = 5 maker.min_room_count.should == 3 - # 明示的に1を指定すると1 + # 2以下ならデフォルト + # force_room_countを指定しないと1部屋は作れない maker = DivideDungeonMaker.new maker.params[:min_room_count] = 1 - maker.min_room_count.should == 1 + maker.min_room_count.should == 2 - # 0以下ならデフォルト maker = DivideDungeonMaker.new maker.params[:min_room_count] = 0 maker.min_room_count.should == 2 end it "max_room_count" do maker = DivideDungeonMaker.new maker.max_room_count.should == 0 maker.params[:max_room_count] = 8 maker.max_room_count.should == 8 end it "max_depth" do maker = DivideDungeonMaker.new maker.max_depth.should == 0 maker.params[:max_depth] = 3 maker.max_depth.should == 3 end it "cross_road_ratio" do # デフォルトは2 maker = DivideDungeonMaker.new maker.cross_road_ratio.should == DivideDungeonMaker::DEFAULT_CROSS_ROAD_RATIO # 値は一度だけセットできる maker = DivideDungeonMaker.new maker.params[:cross_road_ratio] = 3 maker.cross_road_ratio.should == 3 maker.params[:cross_road_ratio] = 5 maker.cross_road_ratio.should == 3 # 0未満ならデフォルト maker = DivideDungeonMaker.new maker.params[:cross_road_ratio] = -1 maker.cross_road_ratio.should == 2 # 0はセット可能 maker = DivideDungeonMaker.new maker.params[:cross_road_ratio] = 0 maker.cross_road_ratio.should == 0 # 9を超えるならデフォルト maker = DivideDungeonMaker.new maker.params[:cross_road_ratio] = 10 maker.cross_road_ratio.should == 2 end + it "force_room_count" do + maker = DivideDungeonMaker.new + maker.force_room_count.should be_nil + # force_room_countを指定すると、min_room_countに影響する + maker.min_room_count.should == 2 + + maker.params[:force_room_count] = 1 + maker.force_room_count.should == 1 + maker.min_room_count.should == 1 + + maker.params[:force_room_count] = 0 + maker.force_room_count.should == 0 + maker.min_room_count.should == 0 + end + end describe "divide whole_block" do it "divide_queue store dividable block, and done_queue store divided block" do maker = DivideDungeonMaker.new maker.queue_size.should == 0 maker.divide_queue << DivideTempBlock.create_whole_block(20, 20) maker.divide_queue.size.should == 1 maker.queue_size.should == 1 maker.done_queue << DivideTempBlock.create_whole_block(20, 20) maker.done_queue.size.should == 1 maker.queue_size.should == 2 end it "#finish? will check divide end" do maker = DivideDungeonMaker.new maker.finish?.should be_true maker.done_queue << DivideTempBlock.create_whole_block(20, 20) maker.finish?.should be_true maker.divide_queue << DivideTempBlock.create_whole_block(20, 20) maker.finish?.should be_false maker.params[:max_block_count] = 3 maker.finish?.should be_false maker.done_queue << DivideTempBlock.create_whole_block(20, 20) maker.finish?.should be_true end it "#dividable_block? check block dividable" do # max_depthの指定がない場合 maker = DivideDungeonMaker.new b = DivideTempBlock.create_whole_block(20, 20) maker.dividable_block?(b).should be_false b.dividable maker.dividable_block?(b).should be_true # max_depthが指定されている場合 maker = DivideDungeonMaker.new maker.params[:max_depth] = 3 b = DivideTempBlock.create_whole_block(20, 20) b.dividable maker.dividable_block?(b).should be_true b.depth = 3 maker.dividable_block?(b).should be_false end it "create_whole_block" do maker = DivideDungeonMaker.new tb = maker.create_whole_block(30, 40) tb.should be_an_instance_of(DivideTempBlock) tb.width.should == 30 tb.height.should == 40 tb.min_size.should == Util::Config.min_block_size tb.dividable?.should be_true end it "divide block" do each_create_block do |b| b.should be_an_instance_of(DivideTempBlock) end end it "min_block_size/max_block_count/max_depth affect divide as possible" do 10.times do each_create_block(:min_block_size, 6) do |b| b.should be_an_instance_of(DivideTempBlock) b.width.should >= 6 b.height.should >= 6 end end 10.times do count = 0 each_create_block(:max_block_count, 5) do |b| b.should be_an_instance_of(DivideTempBlock) - count += 0 + count += 1 end count.should <= 5 end 10.times do count = 0 each_create_block(:max_depth, 3) do |b| b.should be_an_instance_of(DivideTempBlock) - b.depth <= 3 + b.depth.should <= 3 count += 1 end count.should <= 8 end end + it "min_block_count affect divide as possible" do + (8..20).each do |ts| + 10.times do + count = 0 + remain = 0 + each_create_block(:min_block_count, ts) do |b| + b.should be_an_instance_of(DivideTempBlock) + remain += 1 if b.dividable_size? + count += 1 + end + + if count >= ts + count.should >= ts # always OK + else + # min_block_countを満たせない場合に、分割がもう限界であるか? + remain.should <= 0 + end + end + end + end + def each_create_block(name = nil, val = nil) maker = DivideDungeonMaker.new maker.params[name] = val if name && val tb = maker.create_whole_block(40, 40) bl = maker.make_blocks(tb) bl.each{|b| yield(b)} end end end diff --git a/spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb b/spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb index b534df4..ec2b1ea 100644 --- a/spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb +++ b/spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb @@ -1,244 +1,293 @@ # coding: UTF-8 require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') include RDGC::Map include RDGC::Maker describe RDGC::Maker::DivideDungeonMaker, 'create room/road for each block' do describe "create room" do it "create_room by default" do 10.times do maker = create_maker_with_blocks maker.create_room maker.blocks.each do |b| rsl_room = b.has_room? rsl_cross = b.has_cross_point? (rsl_room || rsl_cross).should be_true (rsl_room && rsl_cross).should be_false end maker.blocks.select{|b| b.has_room?}.size.should >= 2 end end it "min_room_size/max_room_size affect room size" do val = 5 10.times do maker = create_maker_with_blocks(:min_room_size => val) maker.create_room maker.blocks.select{|b| b.has_room?}.map{|b| b.room}.each do |r| r.width.should >= val r.height.should >= val end end 10.times do maker = create_maker_with_blocks(:max_room_size => val) maker.create_room maker.blocks.select{|b| b.has_room?}.map{|b| b.room}.each do |r| r.width.should <= val r.height.should <= val end end end it "min_room_count/max_room_count affect room count" do 10.times do maker = create_maker_with_blocks(:min_room_count => 3) maker.create_room maker.blocks.select{|b| b.has_room?}.size.should >= 3 end 10.times do maker = create_maker_with_blocks(:max_room_count => 3) maker.create_room maker.blocks.select{|b| b.has_room?}.size.should <= 3 end + # min_room_count = 1でも2部屋できる (from ver2.2) 10.times do maker = create_maker_with_blocks(:min_room_count => 1, :max_room_count => 1) maker.create_room - maker.blocks.select{|b| b.has_room?}.size.should == 1 + maker.blocks.select{|b| b.has_room?}.size.should == 2 end end it "cross_road_ratio affect room create" do 10.times do maker = create_maker_with_blocks(:cross_road_ratio => 9) maker.create_room all_size = maker.blocks.size maker.blocks.select{|b| b.has_room?}.size.should >= 2 maker.blocks.select{|b| b.has_cross_point?}.size.should <= all_size - 2 end 10.times do maker = create_maker_with_blocks(:cross_road_ratio => 0) maker.create_room all_size = maker.blocks.size maker.blocks.select{|b| b.has_room?}.size.should == all_size maker.blocks.select{|b| b.has_cross_point?}.size.should == 0 end end + it "fixed count rooms create, if force_room_count exists" do + # force_room_countを指定すれば、1部屋や部屋なしも作れる + (0..2).each do |force_size| + 10.times do + maker = create_maker_with_blocks(:force_room_count => force_size) + maker.create_room + + max = maker.blocks.size + expect = (max > force_size ? force_size : max) + maker.blocks.select{|b| b.has_room?}.size.should == expect + end + end + end + end describe "create road" do it "room block should has roads, if min_room_count too big" do 10.times do maker = create_maker_with_blocks(:min_room_count => 99) maker.create_room maker.create_road maker.blocks.select{|b| b.has_room?}.each do |b| b.has_road?.should be_true end end end it "no create road if only one block" do maker = create_maker_with_blocks(:min_block_size => 99) maker.create_room maker.blocks.size.should == 1 maker.create_road maker.blocks.select{|b| b.has_road?}.should be_empty end it "#move_room_and_connect spec" do b1 = DivideTempBlock.create(0, 10, 0, 10) b2 = DivideTempBlock.create(0, 10, 11, 20) b3 = DivideTempBlock.create(0, 10, 21, 30) b4 = DivideTempBlock.create(0, 10, 31, 40) b1.create_room b2.create_room b4.create_room b1.create_road_to(b2) b2.add_remain_cling_blocks(b3) maker = DivideDungeonMaker.new maker.instance_eval do @params = {:min_room_count => 10} @blocks = [b1, b2, b3, b4] end maker.move_room_and_connect b3.has_room?.should be_true b3.has_road?.should be_true b4.has_room?.should be_false b4.has_road?.should be_false end end describe "make all" do it "create provide complete board" do board = DivideDungeonMaker.create(40, 40) board.should be_an_instance_of(Map::Board) board.blocks.select{|b| b.has_room?}.each do |b| b.should be_an_instance_of(Block) b.should_not be_an_instance_of(DivideTempBlock) b.has_road?.should be_true end end it "create accept params" do params = {} params[:min_room_size] = 5 params[:max_room_size] = 10 + params[:min_block_size] = 4 params[:min_block_size] = 8 params[:min_room_count] = 3 params[:max_room_count] = 8 params[:max_depth] = 4 params[:cross_road_ratio] = 4 10.times do board = DivideDungeonMaker.create(80, 80, params) board.should be_an_instance_of(Map::Board) board.blocks.size.should <= 16 # depth room_count = 0 board.blocks.each do |b| b.should be_an_instance_of(Block) b.should_not be_an_instance_of(DivideTempBlock) b.width.should >= params[:min_block_size] b.height.should >= params[:min_block_size] next unless b.has_room? room = b.room room.width.should >= params[:min_room_size] room.width.should <= params[:max_room_size] room.height.should >= params[:min_room_size] room.height.should <= params[:max_room_size] room_count += 1 end - room_count.should >= params[:min_room_count] + + if board.blocks.size <= 2 + room_count.should == 2 + else + room_count.should >= params[:min_room_count] + end room_count.should <= params[:max_room_count] end end - it "only one block board" do + it "only one big block board" do + # min_block_sizeの指定が大きいので、min_room_count/max_room_countが影響しない params = {} - params[:min_room_count] = 1 - params[:max_room_count] = 1 + params[:min_room_count] = 2 + params[:max_room_count] = 5 params[:min_block_size] = 99 10.times do board = DivideDungeonMaker.create(40, 40, params) board.should be_an_instance_of(Map::Board) board.blocks.size.should == 1 board.blocks.map(&:room).size.should == 1 board.blocks.inject([]){|l, b| l + b.roads}.should be_empty end end it "only room board" do 10.times do board = DivideDungeonMaker.create(40, 40, :cross_road_ratio => 0) board.should be_an_instance_of(Map::Board) board.blocks.each do |b| b.has_room?.should be_true b.has_road?.should be_true b.has_cross_point?.should be_false end end end + it "fixed room count board" do + (0..2).each do |force_size| + 10.times do + board = DivideDungeonMaker.create(40, 40, :force_room_count => force_size) + board.should be_an_instance_of(Map::Board) + + max = board.blocks.size + expect = (max > force_size ? force_size : max) + board.blocks.select{|b| b.has_room?}.size.should == expect + end + end + end + + it "create no blocks if one big block and force no room" do + params = {} + params[:force_room_count] = 0 + params[:min_block_size] = 99 + + 10.times do + board = DivideDungeonMaker.create(40, 40, params) + board.should be_an_instance_of(Map::Board) + + board.blocks.size.should == 0 + board.blocks.map(&:room).size.should == 0 + end + end + end def create_maker_with_blocks(params = nil) maker = DivideDungeonMaker.new maker.instance_eval do @params = params end tb = maker.create_whole_block(40, 40) bl = maker.make_blocks(tb) bl.each do |b| maker.blocks << b end maker end end
parrot-studio/rdgc-dm
bfa90b0ec431d5f082114672936f545bfe8147da
rdocの生成オプションを追加
diff --git a/Rakefile b/Rakefile index 8bb3534..302bf0d 100644 --- a/Rakefile +++ b/Rakefile @@ -1,49 +1,50 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "rdgc-dm" gem.summary = %Q{Random Dungeon Maker from RDGC} gem.description = <<-TXT This gem is part of RDGC - Ruby(Random) Dungeon Game Core. RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. TXT gem.email = "[email protected]" gem.homepage = "http://github.com/parrot-studio/rdgc-dm" gem.authors = ["parrot_studio"] gem.required_ruby_version = ">= 1.8.7" #gem.add_development_dependency "rspec", ">= 1.2.9" # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end task :spec => :check_dependencies task :default => :spec require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "rdgc-dm #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') + rdoc.options << '-S' << '-N' << '-c UTF8' end
parrot-studio/rdgc-dm
a756d26c6c95bb185dc5d3f911f884e2a8c9a5b7
Version bump to 0.2.2
diff --git a/VERSION b/VERSION index 0c62199..f477849 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.2.1 +0.2.2 \ No newline at end of file
parrot-studio/rdgc-dm
0c9da4057d9099cc75dc5788468a9d9b5036c7e4
for 0.2.1 release
diff --git a/rdgc-dm.gemspec b/rdgc-dm.gemspec index 6b24686..6fa26e1 100644 --- a/rdgc-dm.gemspec +++ b/rdgc-dm.gemspec @@ -1,96 +1,96 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{rdgc-dm} - s.version = "0.2.0" + s.version = "0.2.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["parrot_studio"] - s.date = %q{2010-05-13} + s.date = %q{2010-09-22} s.description = %q{ This gem is part of RDGC - Ruby(Random) Dungeon Game Core. RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. } s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "lib/rdgc-dm.rb", "lib/rdgc/maker/divide_dungeon_maker.rb", "lib/rdgc/maker/divide_temp_block.rb", "lib/rdgc/maker/dungeon_maker.rb", "lib/rdgc/maker/temp_block.rb", "lib/rdgc/map/area.rb", "lib/rdgc/map/blind_area.rb", "lib/rdgc/map/block.rb", "lib/rdgc/map/board.rb", "lib/rdgc/map/direction.rb", "lib/rdgc/map/road.rb", "lib/rdgc/map/room.rb", "lib/rdgc/map/tile.rb", "lib/rdgc/map/tile_type.rb", "lib/rdgc/util/config.rb", "lib/rdgc/util/random_util.rb", "rdgc-dm.gemspec", "spec/rdgc/maker/01_temp_block_spec.rb", "spec/rdgc/maker/02_divide_temp_block_spec.rb", "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb", "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", "spec/rdgc/map/01_tile_spec.rb", "spec/rdgc/map/02_area_spec.rb", "spec/rdgc/map/03_road_spec.rb", "spec/rdgc/map/04_room_spec.rb", "spec/rdgc/map/05_block_spec.rb", "spec/rdgc/map/06_board_spec.rb", "spec/rdgc/map/07_direction_spec.rb", "spec/rdgc/map/08_blind_area_spec.rb", "spec/rdgc/util/01_config_spec.rb", "spec/rdgc/util/02_random_util_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/parrot-studio/rdgc-dm} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") - s.rubygems_version = %q{1.3.6} + s.rubygems_version = %q{1.3.7} s.summary = %q{Random Dungeon Maker from RDGC} s.test_files = [ "spec/spec_helper.rb", "spec/rdgc/util/02_random_util_spec.rb", "spec/rdgc/util/01_config_spec.rb", "spec/rdgc/map/04_room_spec.rb", "spec/rdgc/map/06_board_spec.rb", "spec/rdgc/map/01_tile_spec.rb", "spec/rdgc/map/03_road_spec.rb", "spec/rdgc/map/08_blind_area_spec.rb", "spec/rdgc/map/07_direction_spec.rb", "spec/rdgc/map/05_block_spec.rb", "spec/rdgc/map/02_area_spec.rb", "spec/rdgc/maker/02_divide_temp_block_spec.rb", "spec/rdgc/maker/01_temp_block_spec.rb", "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 - if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then + if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
parrot-studio/rdgc-dm
5789a6e0d0e8fbff1d5734b89ee0b8504010c82c
Version bump to 0.2.1
diff --git a/VERSION b/VERSION index 0ea3a94..0c62199 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.2.0 +0.2.1
parrot-studio/rdgc-dm
47fae857ea2b01838bb01c15c9ee0d1d0e1aad30
backport from RDGC0.2
diff --git a/lib/rdgc/map/area.rb b/lib/rdgc/map/area.rb index 7f083f9..da6fd9e 100644 --- a/lib/rdgc/map/area.rb +++ b/lib/rdgc/map/area.rb @@ -1,103 +1,105 @@ # coding: UTF-8 module RDGC module Map class Area include TileType attr_accessor :top, :bottom, :left, :right def self.create(top, bottom, left, right) b = self.new b.top = top b.bottom = bottom b.left = left b.right = right b end def coordinates "t:#{top} b:#{bottom} l:#{left} r:#{right} / w:#{width} h:#{height}" end alias :to_co :coordinates def height bottom - top + 1 end def width right - left + 1 end def has_xy?(x, y) return false if x < left return false if x > right return false if y < top return false if y > bottom true end def random_point [range_rand(left, right), range_rand(top, bottom)] end def each return to_enum(:each) unless block_given? each_x do |x| each_y do |y| yield(x, y) end end end def each_x return to_enum(:each_x) unless block_given? (left..right).each do |x| yield(x) end end def each_y return to_enum(:each_y) unless block_given? (top..bottom).each do |y| yield(y) end end def each_tile return to_enum(:each_tile) unless block_given? each do |x, y| yield(x, y, tile(x, y)) end end def fill # need override end def fill_tile(tile) each do |x, y| set_tile(x, y, tile) end + + self end def set_tile(x, y, tile) return unless has_xy?(x, y) tile_data[x][y] = tile end def tile(x, y) return unless has_xy?(x, y) tile_data[x][y] end private def tile_data @tile_data ||= Hash.new{|hash, key| hash[key] = {}} @tile_data end end end end \ No newline at end of file diff --git a/lib/rdgc/map/blind_area.rb b/lib/rdgc/map/blind_area.rb index e3647c3..671b3bf 100644 --- a/lib/rdgc/map/blind_area.rb +++ b/lib/rdgc/map/blind_area.rb @@ -1,183 +1,205 @@ # coding: UTF-8 module RDGC module Map class Area def blind_level @blind_level end def set_blind(level) return unless [:none, :open, :blind, :dark].include?(level) @blind_level = level + self end def blind_level_none? blind_level == :none ? true : false end def blind_level_open? blind_level == :open ? true : false end def blind_level_blind? blind_level == :blind ? true : false end def blind_level_dark? blind_level == :dark ? true : false end end # Area class Board BLIND_MODE_NONE = :none BLIND_MODE_NORMAL = :normal BLIND_MODE_BLIND = :blind # override def blind_level # do nothing end # override def set_blind(level) # do nothing end def set_blind_mode(mode = nil) @blind_mode = mode @blind_mode ||= BLIND_MODE_NORMAL init_blind + self end def blind_mode @blind_mode end def blind_mode? @blind_mode ? true : false end def fill_blind areas.each do |r| case when r.blind_level_none? target = :none when r.blind_level_dark? target = :dark else target = :blind end r.each do |x, y| blind_data[x][y] = target end end + + self end def visible?(x, y) - return false unless has_xy?(x, y) + return false unless has_xy?(x, y) return true unless blind_mode? v = blind_data[x][y] return false unless v v == :none ? true : false end def invisible?(x, y) ! visible?(x, y) end def dark?(x, y) - return false unless has_xy?(x, y) + return false unless has_xy?(x, y) blind_data[x][y] == :dark ? true : false end def open_blind(sx, sy, range) return unless movable?(sx, sy) # 先にdarkのエリアを塗りつぶす fill_dark_before_cancel # 再帰処理で解除 open_list = [] cancel_blind(sx, sy, open_list, range) # :openのareaを全解除 return if open_list.empty? open_list.uniq.each do |a| a.each do |x, y| blind_data[x][y] = :none end end - end - def blind_data - @blind_data ||= Hash.new{|hash, key| hash[key] = {}} - @blind_data + self end def init_blind case blind_mode when BLIND_MODE_NONE init_blind_all(:none) when BLIND_MODE_BLIND init_blind_all(:blind) when BLIND_MODE_NORMAL init_blind_normal end + + self end def init_blind_all(level) areas.each do |r| r.set_blind(level) end + + self end def init_blind_normal rooms.each do |r| r.set_blind(:open) end roads.each do |r| r.set_blind(:blind) end + + self + end + + def blind_state(x, y) + return unless has_xy?(x, y) + blind_data[x][y] + end + + def set_blind_state(x, y, state) + return unless has_xy?(x, y) + blind_data[x][y] = state end private + def blind_data + @blind_data ||= Hash.new{|hash, key| hash[key] = {}} + @blind_data + end + def fill_dark_before_cancel areas.select{|r| r.blind_level_dark?}.each do |r| r.each do |x, y| blind_data[x][y] = :dark end end end def cancel_blind(sx, sy, open_list, range, r=0) return unless movable?(sx, sy) return if r > range # 今のポイントを可視に blind_data[sx][sy] = :none # 今の座標が:openならareaを可視に areas_for(sx, sy).each do |a| next unless a.blind_level_open? open_list << a unless open_list.include?(a) end # 再帰的に処理 Direction.each do |dir| nx = sx + dir.x ny = sy + dir.y cancel_blind(nx, ny, open_list, range, r+1) end end end # Board end end diff --git a/lib/rdgc/map/block.rb b/lib/rdgc/map/block.rb index 9adca17..f943951 100644 --- a/lib/rdgc/map/block.rb +++ b/lib/rdgc/map/block.rb @@ -1,155 +1,162 @@ # coding: UTF-8 module RDGC module Map class Block < Area def self.create(top, bottom, left, right) # fillはしない super(top, bottom, left, right) end def fill # 初期化 fill_tile TileType::WALL fill_room fill_roads + + self end def fill_room return unless has_room? room.each_tile do |x, y, t| set_tile(x, y, t) end + + self end def fill_roads return unless has_road? roads.each do |r| r.each_tile do |x, y, t| set_tile(x, y, t) end end + + self end def room @room end def room=(r) @room = r end def remove_room @room = nil end def has_room? @room ? true : false end def create_room(opt = nil) @room = Room.create_from_block(self, opt) @room end def roads @roads ||= [] @roads end def add_road(road) @roads ||= [] @roads << road end def remove_roads @roads = [] end def has_road? roads.empty? ? false : true end def cross_point @cross_point end def remove_cross_point @cross_point = nil end def has_cross_point? @cross_point ? true : false end def create_cross_point # 右と下は接線を引くので余計に空ける x_min = self.left + 1 x_max = self.right - 2 y_min = self.top + 1 y_max = self.bottom - 2 x = range_rand(x_min, x_max) y = range_rand(y_min, y_max) @cross_point = [x, y] @cross_point end def remove_all remove_room remove_roads remove_cross_point + self end def empty? return false if has_room? return false if has_road? true end def cling_to_top?(b) return false unless top == b.bottom+1 return false if left > b.right return false if right < b.left true end def cling_to_bottom?(b) return false unless bottom == b.top-1 return false if left > b.right return false if right < b.left true end def cling_to_left?(b) return false unless left == b.right+1 return false if top > b.bottom return false if bottom < b.top true end def cling_to_right?(b) return false unless right == b.left-1 return false if top > b.bottom return false if bottom < b.top true end def cling_direction_to(b) case when cling_to_top?(b) :top when cling_to_bottom?(b) :bottom when cling_to_left?(b) :left when cling_to_right?(b) :right end end end end end diff --git a/lib/rdgc/map/board.rb b/lib/rdgc/map/board.rb index 9596d8c..f9ebbff 100644 --- a/lib/rdgc/map/board.rb +++ b/lib/rdgc/map/board.rb @@ -1,89 +1,95 @@ # coding: UTF-8 module RDGC module Map class Board < Area def self.create_from_blocks(blocks) d = self.new d.init(blocks) d end def init(list) return unless list return if list.empty? @blocks = list @rooms = blocks.map(&:room).compact @roads = blocks.map(&:roads).flatten.compact set_coordinates fill + + self end def set_coordinates return unless blocks self.top = blocks.map(&:top).min self.bottom = blocks.map(&:bottom).max self.left = blocks.map(&:left).min self.right = blocks.map(&:right).max + + self end def fill # 初期化 fill_tile TileType::WALL rooms.each do |r| r.each_tile do |x, y, t| set_tile(x, y, t) end end roads.each do |r| r.each_tile do |x, y, t| set_tile(x, y, t) end end + + self end def blocks @blocks ||= [] @blocks end def rooms @rooms ||= [] @rooms end def roads @roads ||= [] @roads end def areas [rooms, roads].flatten end def areas_for(x, y) areas.select{|a| a.has_xy?(x, y)} end def movable?(x, y) return false unless has_xy?(x, y) tile(x, y).movable? end def room?(x, y) return false unless has_xy?(x, y) tile(x, y).room? end def road?(x, y) return false unless has_xy?(x, y) tile(x, y).road? end end end end diff --git a/lib/rdgc/map/direction.rb b/lib/rdgc/map/direction.rb index cba0193..ab0166f 100644 --- a/lib/rdgc/map/direction.rb +++ b/lib/rdgc/map/direction.rb @@ -1,58 +1,58 @@ -# -*- coding: UTF-8 -*- +# coding: UTF-8 module RDGC module Map class Direction attr_reader :x, :y private def self.create(x, y) obj = self.new obj.instance_eval do @x = x @y = y end obj.freeze obj end public SELF = self.create(0, 0) LEFT = self.create(-1, 0) RIGHT = self.create(1, 0) UPPER = self.create(0, -1) BOTTOM = self.create(0, 1) def self.each return to_enum(:each) unless block_given? self.all.each do |d| yield(d) end end def self.all [LEFT, UPPER, RIGHT, BOTTOM] end def opposite case self when LEFT RIGHT when RIGHT LEFT when UPPER BOTTOM when BOTTOM UPPER when SELF SELF end end end end end \ No newline at end of file diff --git a/lib/rdgc/map/road.rb b/lib/rdgc/map/road.rb index c37e463..e9c178c 100644 --- a/lib/rdgc/map/road.rb +++ b/lib/rdgc/map/road.rb @@ -1,18 +1,19 @@ # coding: UTF-8 module RDGC module Map class Road < Area def self.create(top, bottom, left, right) road = super(top, bottom, left, right) road.fill road end def fill fill_tile TileType::ROAD + self end end end end diff --git a/lib/rdgc/map/room.rb b/lib/rdgc/map/room.rb index d806203..d8868be 100644 --- a/lib/rdgc/map/room.rb +++ b/lib/rdgc/map/room.rb @@ -1,69 +1,70 @@ # coding: UTF-8 module RDGC module Map class Room < Area def self.create(top, bottom, left, right) room = super(top, bottom, left, right) room.fill room end def self.create_from_block(b, opt = nil) room_w = room_size(b.width, opt) room_h = room_size(b.height, opt) return if (room_w <= 0 || room_h <= 0) l_point = b.left+1 + room_point(b.width, room_w) t_point = b.top+1 + room_point(b.height, room_h) self.create(t_point, t_point + room_h - 1, l_point, l_point + room_w - 1) end def fill fill_tile TileType::ROOM + self end private def self.room_size(val, opt = nil) opt ||= {} # 部屋の最大サイズ = ブロックサイズ-壁1*2-通路1 base = val - 3 return 0 if base < Util::Config.min_room_size # 最小値・最大値判定 min = min_size(base, opt[:min]) max = max_size(base, opt[:max]) min = max if min > max range_rand(min, max) end def self.min_size(base, min) min_room_size = Util::Config.min_room_size return min_room_size unless min min = min.to_i return base if base < min return min_room_size if min < min_room_size min end def self.max_size(base, max) return base unless max max = max.to_i return base if max > base return Util::Config.min_room_size if max < Util::Config.min_room_size max end def self.room_point(block_size, room_size) # 右と下は余分に空ける => 結ぶ通路は左と上が担当 range_rand(0, block_size - 3 - room_size) end end end end diff --git a/lib/rdgc/util/config.rb b/lib/rdgc/util/config.rb index 1fece00..48e1f7e 100644 --- a/lib/rdgc/util/config.rb +++ b/lib/rdgc/util/config.rb @@ -1,74 +1,51 @@ # coding: UTF-8 module RDGC module Util class Config DEFAULT_CONFIG = { - :min_room_size => 4, - :act_max_count => 200 + :min_room_size => 4 } - self.class.class_eval do - @config_hash = DEFAULT_CONFIG - end - - def self.set(hash) - return if seted? + class << self - default = nil - self.class.class_eval do - default = @config_hash - end + def set(hash) + return if seted? - hash = default.merge(hash) - - self.class.class_eval do + hash = DEFAULT_CONFIG.merge(hash) @config_hash = hash @seted = true - end - true - end - - def self.min_room_size - self.get(:min_room_size) - end - - def self.min_block_size - # デフォルトのblock最小値 = 最小部屋サイズ+上下空き2+接線通路分1 - self.min_room_size + 3 - end - - def self.act_max_count - self.get(:act_max_count) - end + true + end - def self.seted? - ret = false - self.class.class_eval do - ret = @seted + def get(key) + @config_hash ||= DEFAULT_CONFIG + @config_hash[key] end - ret - end - def self.get(key) - val = nil - self.class.class_eval do - val = @config_hash[key] + def seted? + @seted ? true : false end - val - end - def self.reset! - self.class.class_eval do + def reset! @config_hash = DEFAULT_CONFIG @seted = false + true + end + + def min_room_size + get(:min_room_size) + end + + def min_block_size + # デフォルトのblock最小値 = 最小部屋サイズ+上下空き2+接線通路分1 + min_room_size + 3 end - true end end end end diff --git a/lib/rdgc/util/random_util.rb b/lib/rdgc/util/random_util.rb index 4f9a4c7..af6b359 100644 --- a/lib/rdgc/util/random_util.rb +++ b/lib/rdgc/util/random_util.rb @@ -1,104 +1,110 @@ # coding: UTF-8 module RDGC module Util module RandomUtil + module_function + def bool_rand case rand(2) when 1 true when 0 false end end def range_rand(s_val, e_val) return s_val if e_val <= s_val s_val + rand((e_val - s_val)+1) end def select_rand(hash) return unless hash return if hash.empty? range_list = [] count = 0 hash.each do |k, v| range = count...(count + v) range_list << [range, k] count += v end return if count <= 0 val = rand(count) ret = nil range_list.each do |r| if r.first.include?(val) ret = r.last break end end ret end def dice(n, max) ret = 0 n.times{ret += range_rand(1, max)} ret end - module_function :bool_rand, :range_rand, :select_rand, :dice - end end end class Integer def dice(max) RDGC::Util::RandomUtil.dice(self, max) end alias :d :dice def method_missing(name, *args) try_define_dice(name, args) ? (__send__ name) : super end def d4 self.dice(4) end def d6 self.dice(6) end def d10 self.dice(10) end private def try_define_dice(name, args) return false if args.size > 0 m = name.to_s.match(/^[d|D](\d+)$/) return false unless m return false if m[1].to_i <= 0 self.class.module_eval("def #{name};self.dice(#{m[1]});end") true end end class Array def pickup! ret = self.choice self.delete(ret) ret end -end + if RUBY_VERSION >= '1.9.1' + def choice + self.sample + end + end + +end \ No newline at end of file diff --git a/spec/rdgc/map/08_blind_area_spec.rb b/spec/rdgc/map/08_blind_area_spec.rb index b99925d..5c99f72 100644 --- a/spec/rdgc/map/08_blind_area_spec.rb +++ b/spec/rdgc/map/08_blind_area_spec.rb @@ -1,336 +1,341 @@ # coding: UTF-8 require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') include RDGC::Map describe "blind mode" do describe RDGC::Map::Area, "with blind" do before do @area = Area.new end it "level none" do @area.set_blind(:none) @area.blind_level.should == :none @area.blind_level_none?.should be_true @area.blind_level_open?.should be_false @area.blind_level_blind?.should be_false @area.blind_level_dark?.should be_false end it "level open" do @area.set_blind(:open) @area.blind_level.should == :open @area.blind_level_none?.should be_false @area.blind_level_open?.should be_true @area.blind_level_blind?.should be_false @area.blind_level_dark?.should be_false end it "level blind" do @area.set_blind(:blind) @area.blind_level.should == :blind @area.blind_level_none?.should be_false @area.blind_level_open?.should be_false @area.blind_level_blind?.should be_true @area.blind_level_dark?.should be_false end it "level dark" do @area.set_blind(:dark) @area.blind_level.should == :dark @area.blind_level_none?.should be_false @area.blind_level_open?.should be_false @area.blind_level_blind?.should be_false @area.blind_level_dark?.should be_true end it "unexpected level" do @area.set_blind(:hoge) @area.blind_level.should be_nil @area.blind_level_none?.should be_false @area.blind_level_open?.should be_false @area.blind_level_blind?.should be_false @area.blind_level_dark?.should be_false end end describe RDGC::Map::Board, "with blind" do before do @board = Board.create(0, 20, 0, 20) @room = Room.create(5, 15, 5, 15) @road1 = Road.create(0, 4, 10, 10) @road2 = Road.create(16, 20, 12, 12) @board.rooms << @room @board.roads << @road1 @board.roads << @road2 @board.fill end it "#blind_level/#set_blind is disable" do [:none, :open, :blind, :dark].each do |lv| @board.set_blind(lv) @board.blind_level.should be_nil @board.blind_level_none?.should be_false @board.blind_level_open?.should be_false @board.blind_level_blind?.should be_false @board.blind_level_dark?.should be_false end end it "#init_blind_all will set :blind to all rooms/roads" do @board.init_blind_all(:none) @board.areas.each do |a| a.blind_level_none?.should be_true end @board.init_blind_all(:blind) @board.areas.each do |a| a.blind_level_blind?.should be_true end end it "#init_blind_normal will set :blind to roads, :open to rooms" do @board.init_blind_normal @room.blind_level_open?.should be_true @road1.blind_level_blind?.should be_true @road2.blind_level_blind?.should be_true end it "#init_blind will set blind_level each rooms/roads as blind_mode" do @board.instance_eval do @blind_mode = Board::BLIND_MODE_NONE end @board.init_blind @room.blind_level_none?.should be_true @road1.blind_level_none?.should be_true @road2.blind_level_none?.should be_true @board.instance_eval do @blind_mode = Board::BLIND_MODE_NORMAL end @board.init_blind @room.blind_level_open?.should be_true @road1.blind_level_blind?.should be_true @road2.blind_level_blind?.should be_true @board.instance_eval do @blind_mode = Board::BLIND_MODE_BLIND end @board.init_blind @room.blind_level_blind?.should be_true @road1.blind_level_blind?.should be_true @road2.blind_level_blind?.should be_true end it "#set_blind_mode will set blind_mode, and init_blind" do @board.blind_mode?.should be_false @board.set_blind_mode(Board::BLIND_MODE_NONE) @board.blind_mode.should == Board::BLIND_MODE_NONE @board.blind_mode?.should be_true @room.blind_level_none?.should be_true @road1.blind_level_none?.should be_true @road2.blind_level_none?.should be_true @board.set_blind_mode(Board::BLIND_MODE_NORMAL) @board.blind_mode.should == Board::BLIND_MODE_NORMAL @board.blind_mode?.should be_true @room.blind_level_open?.should be_true @road1.blind_level_blind?.should be_true @road2.blind_level_blind?.should be_true @board.set_blind_mode(Board::BLIND_MODE_BLIND) @board.blind_mode.should == Board::BLIND_MODE_BLIND @board.blind_mode?.should be_true @room.blind_level_blind?.should be_true @road1.blind_level_blind?.should be_true @road2.blind_level_blind?.should be_true @board.set_blind_mode @board.blind_mode.should == Board::BLIND_MODE_NORMAL @board.blind_mode?.should be_true @room.blind_level_open?.should be_true @road1.blind_level_blind?.should be_true @road2.blind_level_blind?.should be_true end + it "#blind_state/#set_blind_state will get/set blind_state" do + @board.set_blind_state(10, 9, :blind) + @board.blind_state(10, 9).should == :blind + end + it "#fill_blind will fill blind_data as each area's blind_level" do @board.set_blind_mode @board.fill_blind @board.areas.each do |r| r.each do |x, y| - @board.blind_data[x][y].should == :blind + @board.blind_state(x, y).should == :blind end end @board.set_blind_mode(:none) @board.fill_blind @board.areas.each do |r| r.each do |x, y| - @board.blind_data[x][y].should == :none + @board.blind_state(x, y).should == :none end end end it "#dark? judge this point is :dark now" do @board.set_blind_mode @room.set_blind(:dark) @room.blind_level_dark?.should be_true @board.fill_blind @room.each.all?{|x, y| @board.dark?(x, y)}.should be_true tx, ty = @room.random_point - @board.blind_data[tx][ty] = :none + @board.set_blind_state(tx, ty, :none) @board.dark?(tx, ty).should be_false end it "#fill_dark_before_cancel" do @board.set_blind_mode @room.set_blind(:dark) @room.blind_level_dark?.should be_true @board.fill_blind 5.times do tx, ty = @room.random_point - @board.blind_data[tx][ty] = :none + @board.set_blind_state(tx, ty, :none) end @room.each.all?{|x, y| @board.dark?(x, y)}.should be_false @board.instance_eval do fill_dark_before_cancel end @room.each.all?{|x, y| @board.dark?(x, y)}.should be_true end it "#open_blind will clear blind stat recursive" do @board.set_blind_mode(Board::BLIND_MODE_BLIND) @board.fill_blind @board.open_blind(10, 4, 0) - @board.blind_data[10][4].should == :none - @board.blind_data[10][3].should == :blind - @board.blind_data[10][5].should == :blind + @board.blind_state(10, 4).should == :none + @board.blind_state(10, 3).should == :blind + @board.blind_state(10, 5).should == :blind @board.open_blind(10, 4, 1) - @board.blind_data[10][4].should == :none - @board.blind_data[10][3].should == :none - @board.blind_data[10][5].should == :none - @board.blind_data[10][2].should == :blind - @board.blind_data[10][6].should == :blind + @board.blind_state(10, 4).should == :none + @board.blind_state(10, 3).should == :none + @board.blind_state(10, 5).should == :none + @board.blind_state(10, 2).should == :blind + @board.blind_state(10, 6).should == :blind @board.open_blind(10, 4, 2) - @board.blind_data[10][4].should == :none - @board.blind_data[10][3].should == :none - @board.blind_data[10][2].should == :none - @board.blind_data[10][1].should == :blind - - @board.blind_data[10][5].should == :none - @board.blind_data[9][5].should == :none - @board.blind_data[10][6].should == :none - @board.blind_data[11][5].should == :none - - @board.blind_data[8][5].should == :blind - @board.blind_data[12][5].should == :blind - @board.blind_data[9][6].should == :blind - @board.blind_data[11][6].should == :blind - @board.blind_data[10][7].should == :blind + @board.blind_state(10, 4).should == :none + @board.blind_state(10, 3).should == :none + @board.blind_state(10, 2).should == :none + @board.blind_state(10, 1).should == :blind + + @board.blind_state(10, 5).should == :none + @board.blind_state(9, 5).should == :none + @board.blind_state(10, 6).should == :none + @board.blind_state(11, 5).should == :none + + @board.blind_state(8, 5).should == :blind + @board.blind_state(12, 5).should == :blind + @board.blind_state(9, 6).should == :blind + @board.blind_state(11, 6).should == :blind + @board.blind_state(10, 7).should == :blind end it "#open_blind will clear blind all of area for :open" do @board.set_blind_mode @board.fill_blind @board.open_blind(10, 4, 1) - @board.blind_data[10][4].should == :none - @board.blind_data[10][3].should == :none - @board.blind_data[10][5].should == :none - @board.blind_data[10][2].should == :blind + @board.blind_state(10, 4).should == :none + @board.blind_state(10, 3).should == :none + @board.blind_state(10, 5).should == :none + @board.blind_state(10, 2).should == :blind @room.each do |x, y| - @board.blind_data[x][y].should == :none + @board.blind_state(x, y).should == :none end end it "#open_blind will clear blind, and turn to dark for opened point" do @board.set_blind_mode @room.set_blind(:dark) @board.fill_blind # 1歩目 @board.open_blind(10, 5, 1) - @board.blind_data[10][4].should == :none + @board.blind_state(10, 4).should == :none - @board.blind_data[10][5].should == :none - @board.blind_data[9][5].should == :none - @board.blind_data[11][5].should == :none - @board.blind_data[10][6].should == :none + @board.blind_state(10, 5).should == :none + @board.blind_state(9, 5).should == :none + @board.blind_state(11, 5).should == :none + @board.blind_state(10, 6).should == :none # 2歩目 @board.open_blind(10, 6, 1) - @board.blind_data[10][4].should == :none + @board.blind_state(10, 4).should == :none - @board.blind_data[10][6].should == :none - @board.blind_data[9][6].should == :none - @board.blind_data[11][6].should == :none - @board.blind_data[10][5].should == :none - @board.blind_data[10][7].should == :none + @board.blind_state(10, 6).should == :none + @board.blind_state(9, 6).should == :none + @board.blind_state(11, 6).should == :none + @board.blind_state(10, 5).should == :none + @board.blind_state(10, 7).should == :none - @board.blind_data[9][5].should == :dark - @board.blind_data[11][5].should == :dark + @board.blind_state(9, 5).should == :dark + @board.blind_state(11, 5).should == :dark end it "#visible?/#invisible?" do @board.set_blind_mode @road2.set_blind(:dark) @board.fill_blind @board.open_blind(10, 4, 1) @board.visible?(10, 4).should be_true @board.visible?(10, 3).should be_true @board.visible?(10, 5).should be_true @board.visible?(10, 2).should be_false @board.invisible?(10, 2).should be_true @room.each do |x, y| @board.visible?(x, y).should be_true @board.invisible?(x, y).should be_false end # dark tx, ty = @road2.random_point @board.visible?(tx, ty).should be_false @board.invisible?(tx, ty).should be_true # out of range @board.visible?(30, 30).should be_false @board.invisible?(30, 30).should be_true end end end diff --git a/spec/rdgc/util/01_config_spec.rb b/spec/rdgc/util/01_config_spec.rb index acc2b7b..f163d49 100644 --- a/spec/rdgc/util/01_config_spec.rb +++ b/spec/rdgc/util/01_config_spec.rb @@ -1,44 +1,37 @@ # coding: UTF-8 require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') include RDGC::Util describe RDGC::Util::Config do it "default value" do Util::Config.min_room_size.should == 4 Util::Config.min_block_size.should == 7 - Util::Config.act_max_count.should == 200 end it "value change only once, and #reset! will force change default value" do val1 = { - :min_room_size => 5, - :act_max_count => 100 + :min_room_size => 5 } Util::Config.set(val1).should be_true Util::Config.min_room_size.should == 5 - Util::Config.act_max_count.should == 100 val2 = { - :min_room_size => 10, - :act_max_count => 80 + :min_room_size => 10 } Util::Config.set(val2).should be_false Util::Config.min_room_size.should == 5 - Util::Config.act_max_count.should == 100 Util::Config.reset!.should be_true Util::Config.min_room_size.should == 4 - Util::Config.act_max_count.should == 200 Util::Config.set(val2).should be_true Util::Config.min_room_size.should == 10 - Util::Config.act_max_count.should == 80 Util::Config.reset!.should be_true end end
parrot-studio/rdgc-dm
f4fe0571ad28a45131680bef26797802888716c8
rdgc-dmとrdgc-dm-blindを統合
diff --git a/README.rdoc b/README.rdoc index 172f67a..8ce9f48 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,215 +1,211 @@ = rdgc-dm Author:: parrot_studio <parrot *at* users.sourceforge.jp> License:: The MIT License * 要求されたサイズのランダムダンジョンを生成 * ダンジョンは部屋と道で構成される == Install gem install gemcutter # インストール済みなら不要 gem install rdgc-dm == Usage require 'rubygems' require 'rdgc-dm' include RDGC::Maker board = DivideDungeonMaker.create(30, 40) # width=30, height=40のMap::Boardを作る場合 board = DivideDungeonMaker.create(30, 40, :min_room_count = 4) # パラメータ指定(4つ以上の部屋数を期待) board.each do |x, y| # each で各座標を順に処理 t = board.tile(x, y) # Tileオブジェクト取得 case when t.wall? # 壁 ... when t.room? # 部屋 ... when t.road? # 道 ... end end board.each_tile do |x, y, t| # each_tileで座標とTileを一緒に取得 ... end rooms = board.rooms # Map::Roomオブジェクトの配列取得 roads = board.roads # Map::Roadオブジェクトの配列取得 r = rooms.choice x, y = r.random_point # あるエリアのランダムな座標を取得 board.room?(2, 3) # 指定座標(x, y)が部屋か判定 board.road?(2, 3) # 指定座標(x, y)が道か判定 board.movable?(2, 3) # 指定座標(x, y)が移動可能(=部屋or道)か判定 # その他、Map::Areaに定義されたメソッドは全て使える # RDGC::Util::RandomUtilで定義され、top-levelにinclude済みのメソッド # 数値は全て整数を指定すること bool_rand # trueかfalseを返す range_rand(min, max) # minからmaxまでのどれかの整数値を返す select_rand(:a => 3, :b => 2, :c => 1) # :aを3/(3+2+1)、:bを2/(3+2+1)...の確率で返す dice(5, 10) # 10面のサイコロを5回振った合計を返す 5.dice(10) # Integer#dice(max)が定義済みで、この場合はdice(5, 10)と同じ 5.d10 # TRPGプレイヤーにおなじみの書き方 # その他、細かなメソッドはソースやspec等参照 == Create Parameters 前提として、生成パラメータは努力目標 できるだけ指定を満たそうとはするが、ランダムなので保証はできない まず全体を一つのBlockとして定義し、それを再帰的に分割した後、 各Blockに部屋か交差点を作るため、Blockとは1:1の関係になる * :min_block_size => 分割Blockの最低サイズ * :max_block_count => Blockの最大生成数 * :min_room_size => 部屋の最低サイズ(デフォルトは4で、4以下は強制的に4) * :max_room_size => 部屋の最大サイズ * :min_room_count => 部屋の最低生成数(デフォルトは2) * :max_room_count => 部屋の最大生成数 * :max_depth => 分割再帰の深さ max_depth=nのとき、Blockの最大数は2^nになる * :cross_road_ratio => 交差点生成率(0 <= x <= 9) == Blind Area(from 0.2) Boardが保持する座標系について、座標ごとの可視・不可視を制御する仕組み あくまで状態の管理であり、描画時にその情報を元にした処理を行わないと意味がない サンプル実装である"RO"gueの動作を参考に http://sourceforge.jp/projects/rdgc/ require 'rubygems' - # rdgc-dm-blindにrdgc-dmは含まれる - #require 'rgdc-dm' - require 'rdgc-dm-blind' - - include RDGC::Maker + require 'rdgc-dm' - board = DivideDungeonMaker.create(30, 40) + board = RDGC::Maker::DivideDungeonMaker.create(30, 40) # Boardを作っただけでは可視制御は有効にならない board.blind_mode? #=> false # 1. Board#set_blind_modeで可視制御を有効にする board.set_blind_mode # :none/:normal/:blind 省略時は:normal # 2. 必要ならばArea#set_blindでArea単位の個別指定をする board.rooms.choice.set_blind(:dark) # 3. Board#fill_blindで可視状態を初期化する # 2.と3.の手順が逆転すると正常に動かない board.fill_blind # 4. Board#open_blind(x, y, view_range)で不可視状態を可視状態にする # playerが(5, 10)に存在し、見える範囲が2 view_range = 2 board.open_blind(5, 10, view_range) # 5. Board#visible?/invisible?/dark?で可視性をチェックし、描画に使う board.visible?(5, 10) #=> true board.visible?(3, 10) #=> true board.visible?(2, 10) #=> false # 実際には移動可能範囲のみが可視状態になる(壁があればそこは処理されない) # ... # playerが(6, 10)に移動した board.open_blind(6, 10, view_range) board.visible?(6, 10) #=> true board.visible?(5, 10) #=> true # 一度歩いた場所は見えるようになっている board.visible?(3, 10) #=> true === Area#set_blindに指定できるレベル * :none => Area内は最初から全て可視 * :open => 最初は全体が不可視だが、Area内の座標に対してopen_blindされると、Area全体が可視状態になる * :blind => 最初は全体が不可視で、open_blindされた場所だけが可視状態 * :dark => open_blind時にArea内の状態が一度初期化され、常にopen_blindされた領域しか見えない(ダークゾーン) === Board#set_blind_modeに指定できるレベル * :normal => Roomが全て:open、Roadが全て:blind(デフォルト) * :none => Room/Road共に:none * :blind => Room/Road共に:blind Board全体を:darkに指定するオプションは定義されていない 必要ならば手動で行う board.areas.each{|a| a.blind_level(:dark)} == FAQ === パラメータが適用されない パラメータには適用優先順位があります 1. min_block_size 2. max_block_count 3. max_depth 4. min_room_count 5. max_room_count 6. cross_road_ratio 7. max_room_size 8. min_room_size 上位のパラメータに対し、下位のパラメータが矛盾した場合、 無視はしませんが、保証はされません === max_room_count=1なのに部屋が2個できる min_room_countのデフォルト値が2なので、 上記の優先順位に従い、部屋が2個できます (デフォルトが2個なのは、スタート地点とゴール地点を作るためです) 明示的にmin_room_count=1をあわせて指定すると、一つだけできるはずです === 道に(部屋でない)行き止まりができる 仕様です それで片付けるのもあれなので補足すると、 つなげられそうな交差点を、できるだけつなぐようにしているものの、 周囲に残りBlockがない等、どうしようもない場合に行き止まりができます あまりたくさんできると問題ですが、 たまにあるくらいはゲームとしていいんじゃないかと === 最大分割深度(max_depth)って何? DivideDungeonMakerは最初のBlockを起点にして、再帰的な分割をしようとします この分割回数の最大値がmax_depthの指定で、これを小さくすることで、 小さいBlockだらけになるのを防げます max_depth=nの時、作られるBlockの最大値は2^nです === イベントやBOSS用に、広い部屋が1つだけ欲しい min_room_sizeをx/y以上にしたうえで、 min_block_sizeをx/y以上にするか、max_block_count=1を指定してください 全体が1Blockになり、限界までRoomを大きくしようとします === スタートとゴール(階段)って無いの? rdgc-dmはあくまで部屋と道(の座標系)を作るための仕組みです スタートやゴールの概念は各ゲームによって異なるため、 rdgc-dmには含んでいません(RDGCとしては存在します) Area#ramdom_pointで各Areaのランダムな座標が取れますので、 それを使ってスタートやゴールや障害を配置してください === 自分でロジックを書きたい * RDGC::Maker::DungeonMakerをincludeしたクラス * RDGC::Maker::TempBlockを継承したクラス これらを組み合わせると自分のロジックが書けます 詳しくはDivideDungeonMaker/DivideTempBlockのソースを見てください == Copyright Copyright (c) 2010 parrot_studio. See LICENSE for details \ No newline at end of file diff --git a/lib/rdgc-dm-blind.rb b/lib/rdgc-dm-blind.rb deleted file mode 100644 index 91b1288..0000000 --- a/lib/rdgc-dm-blind.rb +++ /dev/null @@ -1,3 +0,0 @@ -# coding: UTF-8 -require 'rdgc-dm' -require 'rdgc/map/blind_area' diff --git a/lib/rdgc-dm.rb b/lib/rdgc-dm.rb index e33591f..df3b467 100644 --- a/lib/rdgc-dm.rb +++ b/lib/rdgc-dm.rb @@ -1,18 +1,19 @@ # coding: UTF-8 require 'rdgc/util/config' require 'rdgc/util/random_util' include RDGC::Util::RandomUtil require 'rdgc/map/tile' require 'rdgc/map/tile_type' require 'rdgc/map/area' require 'rdgc/map/block' require 'rdgc/map/room' require 'rdgc/map/road' require 'rdgc/map/board' require 'rdgc/map/direction' +require 'rdgc/map/blind_area' require 'rdgc/maker/temp_block' require 'rdgc/maker/dungeon_maker' require 'rdgc/maker/divide_temp_block' require 'rdgc/maker/divide_dungeon_maker' diff --git a/rdgc-dm.gemspec b/rdgc-dm.gemspec index f3fe0cb..6b24686 100644 --- a/rdgc-dm.gemspec +++ b/rdgc-dm.gemspec @@ -1,93 +1,96 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{rdgc-dm} - s.version = "0.1.0" + s.version = "0.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["parrot_studio"] - s.date = %q{2010-04-01} + s.date = %q{2010-05-13} s.description = %q{ This gem is part of RDGC - Ruby(Random) Dungeon Game Core. RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. } s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "lib/rdgc-dm.rb", "lib/rdgc/maker/divide_dungeon_maker.rb", "lib/rdgc/maker/divide_temp_block.rb", "lib/rdgc/maker/dungeon_maker.rb", "lib/rdgc/maker/temp_block.rb", "lib/rdgc/map/area.rb", + "lib/rdgc/map/blind_area.rb", "lib/rdgc/map/block.rb", "lib/rdgc/map/board.rb", + "lib/rdgc/map/direction.rb", "lib/rdgc/map/road.rb", "lib/rdgc/map/room.rb", "lib/rdgc/map/tile.rb", "lib/rdgc/map/tile_type.rb", "lib/rdgc/util/config.rb", "lib/rdgc/util/random_util.rb", "rdgc-dm.gemspec", "spec/rdgc/maker/01_temp_block_spec.rb", "spec/rdgc/maker/02_divide_temp_block_spec.rb", "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb", "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", "spec/rdgc/map/01_tile_spec.rb", "spec/rdgc/map/02_area_spec.rb", "spec/rdgc/map/03_road_spec.rb", "spec/rdgc/map/04_room_spec.rb", "spec/rdgc/map/05_block_spec.rb", "spec/rdgc/map/06_board_spec.rb", + "spec/rdgc/map/07_direction_spec.rb", + "spec/rdgc/map/08_blind_area_spec.rb", "spec/rdgc/util/01_config_spec.rb", "spec/rdgc/util/02_random_util_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/parrot-studio/rdgc-dm} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") s.rubygems_version = %q{1.3.6} s.summary = %q{Random Dungeon Maker from RDGC} s.test_files = [ "spec/spec_helper.rb", "spec/rdgc/util/02_random_util_spec.rb", "spec/rdgc/util/01_config_spec.rb", "spec/rdgc/map/04_room_spec.rb", "spec/rdgc/map/06_board_spec.rb", "spec/rdgc/map/01_tile_spec.rb", "spec/rdgc/map/03_road_spec.rb", + "spec/rdgc/map/08_blind_area_spec.rb", + "spec/rdgc/map/07_direction_spec.rb", "spec/rdgc/map/05_block_spec.rb", "spec/rdgc/map/02_area_spec.rb", "spec/rdgc/maker/02_divide_temp_block_spec.rb", "spec/rdgc/maker/01_temp_block_spec.rb", "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) else - s.add_dependency(%q<rspec>, [">= 1.2.9"]) end else - s.add_dependency(%q<rspec>, [">= 1.2.9"]) end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index f786f2c..dd0ec27 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,11 +1,11 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) -require 'rdgc-dm-blind' +require 'rdgc-dm' require 'spec' require 'spec/autorun' include RDGC Spec::Runner.configure do |config| end
parrot-studio/rdgc-dm
dc6beb3f9c65087141fcfadbaf6fc36fae70ba90
rewrite README.rdoc for 0.2.0
diff --git a/README.rdoc b/README.rdoc index 0d4a111..172f67a 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,148 +1,215 @@ = rdgc-dm Author:: parrot_studio <parrot *at* users.sourceforge.jp> License:: The MIT License * 要求されたサイズのランダムダンジョンを生成 * ダンジョンは部屋と道で構成される == Install gem install gemcutter # インストール済みなら不要 gem install rdgc-dm == Usage require 'rubygems' require 'rdgc-dm' include RDGC::Maker board = DivideDungeonMaker.create(30, 40) # width=30, height=40のMap::Boardを作る場合 board = DivideDungeonMaker.create(30, 40, :min_room_count = 4) # パラメータ指定(4つ以上の部屋数を期待) board.each do |x, y| # each で各座標を順に処理 t = board.tile(x, y) # Tileオブジェクト取得 case when t.wall? # 壁 ... when t.room? # 部屋 ... when t.road? # 道 ... end end board.each_tile do |x, y, t| # each_tileで座標とTileを一緒に取得 ... end rooms = board.rooms # Map::Roomオブジェクトの配列取得 roads = board.roads # Map::Roadオブジェクトの配列取得 r = rooms.choice x, y = r.random_point # あるエリアのランダムな座標を取得 board.room?(2, 3) # 指定座標(x, y)が部屋か判定 board.road?(2, 3) # 指定座標(x, y)が道か判定 board.movable?(2, 3) # 指定座標(x, y)が移動可能(=部屋or道)か判定 # その他、Map::Areaに定義されたメソッドは全て使える # RDGC::Util::RandomUtilで定義され、top-levelにinclude済みのメソッド # 数値は全て整数を指定すること bool_rand # trueかfalseを返す range_rand(min, max) # minからmaxまでのどれかの整数値を返す select_rand(:a => 3, :b => 2, :c => 1) # :aを3/(3+2+1)、:bを2/(3+2+1)...の確率で返す dice(5, 10) # 10面のサイコロを5回振った合計を返す 5.dice(10) # Integer#dice(max)が定義済みで、この場合はdice(5, 10)と同じ 5.d10 # TRPGプレイヤーにおなじみの書き方 # その他、細かなメソッドはソースやspec等参照 == Create Parameters 前提として、生成パラメータは努力目標 できるだけ指定を満たそうとはするが、ランダムなので保証はできない まず全体を一つのBlockとして定義し、それを再帰的に分割した後、 各Blockに部屋か交差点を作るため、Blockとは1:1の関係になる * :min_block_size => 分割Blockの最低サイズ * :max_block_count => Blockの最大生成数 * :min_room_size => 部屋の最低サイズ(デフォルトは4で、4以下は強制的に4) * :max_room_size => 部屋の最大サイズ * :min_room_count => 部屋の最低生成数(デフォルトは2) * :max_room_count => 部屋の最大生成数 * :max_depth => 分割再帰の深さ max_depth=nのとき、Blockの最大数は2^nになる * :cross_road_ratio => 交差点生成率(0 <= x <= 9) +== Blind Area(from 0.2) + + Boardが保持する座標系について、座標ごとの可視・不可視を制御する仕組み + あくまで状態の管理であり、描画時にその情報を元にした処理を行わないと意味がない + サンプル実装である"RO"gueの動作を参考に + http://sourceforge.jp/projects/rdgc/ + + + require 'rubygems' + # rdgc-dm-blindにrdgc-dmは含まれる + #require 'rgdc-dm' + require 'rdgc-dm-blind' + + include RDGC::Maker + + board = DivideDungeonMaker.create(30, 40) + # Boardを作っただけでは可視制御は有効にならない + board.blind_mode? #=> false + + # 1. Board#set_blind_modeで可視制御を有効にする + board.set_blind_mode # :none/:normal/:blind 省略時は:normal + + # 2. 必要ならばArea#set_blindでArea単位の個別指定をする + board.rooms.choice.set_blind(:dark) + + # 3. Board#fill_blindで可視状態を初期化する + # 2.と3.の手順が逆転すると正常に動かない + board.fill_blind + + # 4. Board#open_blind(x, y, view_range)で不可視状態を可視状態にする + # playerが(5, 10)に存在し、見える範囲が2 + view_range = 2 + board.open_blind(5, 10, view_range) + + # 5. Board#visible?/invisible?/dark?で可視性をチェックし、描画に使う + board.visible?(5, 10) #=> true + board.visible?(3, 10) #=> true + board.visible?(2, 10) #=> false + # 実際には移動可能範囲のみが可視状態になる(壁があればそこは処理されない) + + # ... + + # playerが(6, 10)に移動した + board.open_blind(6, 10, view_range) + board.visible?(6, 10) #=> true + board.visible?(5, 10) #=> true + # 一度歩いた場所は見えるようになっている + board.visible?(3, 10) #=> true + +=== Area#set_blindに指定できるレベル + + * :none => Area内は最初から全て可視 + * :open => 最初は全体が不可視だが、Area内の座標に対してopen_blindされると、Area全体が可視状態になる + * :blind => 最初は全体が不可視で、open_blindされた場所だけが可視状態 + * :dark => open_blind時にArea内の状態が一度初期化され、常にopen_blindされた領域しか見えない(ダークゾーン) + +=== Board#set_blind_modeに指定できるレベル + + * :normal => Roomが全て:open、Roadが全て:blind(デフォルト) + * :none => Room/Road共に:none + * :blind => Room/Road共に:blind + + Board全体を:darkに指定するオプションは定義されていない + 必要ならば手動で行う + + board.areas.each{|a| a.blind_level(:dark)} + == FAQ === パラメータが適用されない パラメータには適用優先順位があります 1. min_block_size 2. max_block_count 3. max_depth 4. min_room_count 5. max_room_count 6. cross_road_ratio 7. max_room_size 8. min_room_size 上位のパラメータに対し、下位のパラメータが矛盾した場合、 無視はしませんが、保証はされません === max_room_count=1なのに部屋が2個できる min_room_countのデフォルト値が2なので、 上記の優先順位に従い、部屋が2個できます (デフォルトが2個なのは、スタート地点とゴール地点を作るためです) 明示的にmin_room_count=1をあわせて指定すると、一つだけできるはずです === 道に(部屋でない)行き止まりができる 仕様です それで片付けるのもあれなので補足すると、 つなげられそうな交差点を、できるだけつなぐようにしているものの、 周囲に残りBlockがない等、どうしようもない場合に行き止まりができます あまりたくさんできると問題ですが、 たまにあるくらいはゲームとしていいんじゃないかと === 最大分割深度(max_depth)って何? DivideDungeonMakerは最初のBlockを起点にして、再帰的な分割をしようとします この分割回数の最大値がmax_depthの指定で、これを小さくすることで、 小さいBlockだらけになるのを防げます max_depth=nの時、作られるBlockの最大値は2^nです === イベントやBOSS用に、広い部屋が1つだけ欲しい min_room_sizeをx/y以上にしたうえで、 min_block_sizeをx/y以上にするか、max_block_count=1を指定してください 全体が1Blockになり、限界までRoomを大きくしようとします === スタートとゴール(階段)って無いの? rdgc-dmはあくまで部屋と道(の座標系)を作るための仕組みです スタートやゴールの概念は各ゲームによって異なるため、 rdgc-dmには含んでいません(RDGCとしては存在します) Area#ramdom_pointで各Areaのランダムな座標が取れますので、 - それを使ってスタートやゴールやモンスターを配置してください + それを使ってスタートやゴールや障害を配置してください === 自分でロジックを書きたい * RDGC::Maker::DungeonMakerをincludeしたクラス * RDGC::Maker::TempBlockを継承したクラス これらを組み合わせると自分のロジックが書けます 詳しくはDivideDungeonMaker/DivideTempBlockのソースを見てください == Copyright Copyright (c) 2010 parrot_studio. See LICENSE for details \ No newline at end of file
parrot-studio/rdgc-dm
ef04db478df20fcba95894ea967bcab23fb59f0b
remove rspec dependency
diff --git a/Rakefile b/Rakefile index 955c4e3..8bb3534 100644 --- a/Rakefile +++ b/Rakefile @@ -1,49 +1,49 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "rdgc-dm" gem.summary = %Q{Random Dungeon Maker from RDGC} gem.description = <<-TXT This gem is part of RDGC - Ruby(Random) Dungeon Game Core. RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. TXT gem.email = "[email protected]" gem.homepage = "http://github.com/parrot-studio/rdgc-dm" gem.authors = ["parrot_studio"] gem.required_ruby_version = ">= 1.8.7" - gem.add_development_dependency "rspec", ">= 1.2.9" + #gem.add_development_dependency "rspec", ">= 1.2.9" # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end task :spec => :check_dependencies task :default => :spec require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "rdgc-dm #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end
parrot-studio/rdgc-dm
7d1bdc36dc975711ae6f0321b0a8e591f3a1e050
Version bump to 0.2.0
diff --git a/VERSION b/VERSION index 7ecf123..0ea3a94 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.0 +0.2.0
parrot-studio/rdgc-dm
9e94be9c7ec68e322fac3fbd905aa9be41de13c3
spec_helperのinclude対象をrdgc-dm-blindに変更
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index dd0ec27..f786f2c 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,11 +1,11 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) -require 'rdgc-dm' +require 'rdgc-dm-blind' require 'spec' require 'spec/autorun' include RDGC Spec::Runner.configure do |config| end
parrot-studio/rdgc-dm
8c1246136e4e6a871a075ed8fe31ab3c6c2805a4
add blind_area
diff --git a/lib/rdgc-dm-blind.rb b/lib/rdgc-dm-blind.rb new file mode 100644 index 0000000..91b1288 --- /dev/null +++ b/lib/rdgc-dm-blind.rb @@ -0,0 +1,3 @@ +# coding: UTF-8 +require 'rdgc-dm' +require 'rdgc/map/blind_area' diff --git a/lib/rdgc/map/blind_area.rb b/lib/rdgc/map/blind_area.rb new file mode 100644 index 0000000..e3647c3 --- /dev/null +++ b/lib/rdgc/map/blind_area.rb @@ -0,0 +1,183 @@ +# coding: UTF-8 +module RDGC + module Map + + class Area + + def blind_level + @blind_level + end + + def set_blind(level) + return unless [:none, :open, :blind, :dark].include?(level) + @blind_level = level + end + + def blind_level_none? + blind_level == :none ? true : false + end + + def blind_level_open? + blind_level == :open ? true : false + end + + def blind_level_blind? + blind_level == :blind ? true : false + end + + def blind_level_dark? + blind_level == :dark ? true : false + end + + end # Area + + class Board + + BLIND_MODE_NONE = :none + BLIND_MODE_NORMAL = :normal + BLIND_MODE_BLIND = :blind + + # override + def blind_level + # do nothing + end + + # override + def set_blind(level) + # do nothing + end + + def set_blind_mode(mode = nil) + @blind_mode = mode + @blind_mode ||= BLIND_MODE_NORMAL + init_blind + end + + def blind_mode + @blind_mode + end + + def blind_mode? + @blind_mode ? true : false + end + + def fill_blind + areas.each do |r| + case + when r.blind_level_none? + target = :none + when r.blind_level_dark? + target = :dark + else + target = :blind + end + + r.each do |x, y| + blind_data[x][y] = target + end + end + end + + def visible?(x, y) + return false unless has_xy?(x, y) + return true unless blind_mode? + v = blind_data[x][y] + return false unless v + v == :none ? true : false + end + + def invisible?(x, y) + ! visible?(x, y) + end + + def dark?(x, y) + return false unless has_xy?(x, y) + blind_data[x][y] == :dark ? true : false + end + + def open_blind(sx, sy, range) + return unless movable?(sx, sy) + + # 先にdarkのエリアを塗りつぶす + fill_dark_before_cancel + + # 再帰処理で解除 + open_list = [] + cancel_blind(sx, sy, open_list, range) + + # :openのareaを全解除 + return if open_list.empty? + open_list.uniq.each do |a| + a.each do |x, y| + blind_data[x][y] = :none + end + end + end + + def blind_data + @blind_data ||= Hash.new{|hash, key| hash[key] = {}} + @blind_data + end + + def init_blind + case blind_mode + when BLIND_MODE_NONE + init_blind_all(:none) + when BLIND_MODE_BLIND + init_blind_all(:blind) + when BLIND_MODE_NORMAL + init_blind_normal + end + end + + def init_blind_all(level) + areas.each do |r| + r.set_blind(level) + end + end + + def init_blind_normal + rooms.each do |r| + r.set_blind(:open) + end + + roads.each do |r| + r.set_blind(:blind) + end + end + + private + + def fill_dark_before_cancel + areas.select{|r| r.blind_level_dark?}.each do |r| + r.each do |x, y| + blind_data[x][y] = :dark + end + end + end + + def cancel_blind(sx, sy, open_list, range, r=0) + return unless movable?(sx, sy) + return if r > range + + # 今のポイントを可視に + blind_data[sx][sy] = :none + + # 今の座標が:openならareaを可視に + areas_for(sx, sy).each do |a| + next unless a.blind_level_open? + open_list << a unless open_list.include?(a) + end + + # 再帰的に処理 + Direction.each do |dir| + nx = sx + dir.x + ny = sy + dir.y + cancel_blind(nx, ny, open_list, range, r+1) + end + end + + end # Board + + end +end diff --git a/spec/rdgc/map/08_blind_area_spec.rb b/spec/rdgc/map/08_blind_area_spec.rb new file mode 100644 index 0000000..b99925d --- /dev/null +++ b/spec/rdgc/map/08_blind_area_spec.rb @@ -0,0 +1,336 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map + +describe "blind mode" do + + describe RDGC::Map::Area, "with blind" do + + before do + @area = Area.new + end + + it "level none" do + @area.set_blind(:none) + + @area.blind_level.should == :none + @area.blind_level_none?.should be_true + @area.blind_level_open?.should be_false + @area.blind_level_blind?.should be_false + @area.blind_level_dark?.should be_false + end + + it "level open" do + @area.set_blind(:open) + + @area.blind_level.should == :open + @area.blind_level_none?.should be_false + @area.blind_level_open?.should be_true + @area.blind_level_blind?.should be_false + @area.blind_level_dark?.should be_false + end + + it "level blind" do + @area.set_blind(:blind) + + @area.blind_level.should == :blind + @area.blind_level_none?.should be_false + @area.blind_level_open?.should be_false + @area.blind_level_blind?.should be_true + @area.blind_level_dark?.should be_false + end + + it "level dark" do + @area.set_blind(:dark) + + @area.blind_level.should == :dark + @area.blind_level_none?.should be_false + @area.blind_level_open?.should be_false + @area.blind_level_blind?.should be_false + @area.blind_level_dark?.should be_true + end + + it "unexpected level" do + @area.set_blind(:hoge) + + @area.blind_level.should be_nil + @area.blind_level_none?.should be_false + @area.blind_level_open?.should be_false + @area.blind_level_blind?.should be_false + @area.blind_level_dark?.should be_false + end + + end + + describe RDGC::Map::Board, "with blind" do + + before do + @board = Board.create(0, 20, 0, 20) + + @room = Room.create(5, 15, 5, 15) + @road1 = Road.create(0, 4, 10, 10) + @road2 = Road.create(16, 20, 12, 12) + + @board.rooms << @room + @board.roads << @road1 + @board.roads << @road2 + @board.fill + end + + it "#blind_level/#set_blind is disable" do + [:none, :open, :blind, :dark].each do |lv| + @board.set_blind(lv) + + @board.blind_level.should be_nil + @board.blind_level_none?.should be_false + @board.blind_level_open?.should be_false + @board.blind_level_blind?.should be_false + @board.blind_level_dark?.should be_false + end + end + + it "#init_blind_all will set :blind to all rooms/roads" do + @board.init_blind_all(:none) + @board.areas.each do |a| + a.blind_level_none?.should be_true + end + + @board.init_blind_all(:blind) + @board.areas.each do |a| + a.blind_level_blind?.should be_true + end + end + + it "#init_blind_normal will set :blind to roads, :open to rooms" do + @board.init_blind_normal + + @room.blind_level_open?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + end + + it "#init_blind will set blind_level each rooms/roads as blind_mode" do + @board.instance_eval do + @blind_mode = Board::BLIND_MODE_NONE + end + @board.init_blind + + @room.blind_level_none?.should be_true + @road1.blind_level_none?.should be_true + @road2.blind_level_none?.should be_true + + @board.instance_eval do + @blind_mode = Board::BLIND_MODE_NORMAL + end + @board.init_blind + + @room.blind_level_open?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + + @board.instance_eval do + @blind_mode = Board::BLIND_MODE_BLIND + end + @board.init_blind + + @room.blind_level_blind?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + end + + it "#set_blind_mode will set blind_mode, and init_blind" do + @board.blind_mode?.should be_false + + @board.set_blind_mode(Board::BLIND_MODE_NONE) + @board.blind_mode.should == Board::BLIND_MODE_NONE + @board.blind_mode?.should be_true + + @room.blind_level_none?.should be_true + @road1.blind_level_none?.should be_true + @road2.blind_level_none?.should be_true + + @board.set_blind_mode(Board::BLIND_MODE_NORMAL) + @board.blind_mode.should == Board::BLIND_MODE_NORMAL + @board.blind_mode?.should be_true + + @room.blind_level_open?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + + @board.set_blind_mode(Board::BLIND_MODE_BLIND) + @board.blind_mode.should == Board::BLIND_MODE_BLIND + @board.blind_mode?.should be_true + + @room.blind_level_blind?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + + @board.set_blind_mode + @board.blind_mode.should == Board::BLIND_MODE_NORMAL + @board.blind_mode?.should be_true + + @room.blind_level_open?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + end + + it "#fill_blind will fill blind_data as each area's blind_level" do + @board.set_blind_mode + @board.fill_blind + + @board.areas.each do |r| + r.each do |x, y| + @board.blind_data[x][y].should == :blind + end + end + + @board.set_blind_mode(:none) + @board.fill_blind + + @board.areas.each do |r| + r.each do |x, y| + @board.blind_data[x][y].should == :none + end + end + end + + it "#dark? judge this point is :dark now" do + @board.set_blind_mode + @room.set_blind(:dark) + @room.blind_level_dark?.should be_true + @board.fill_blind + + @room.each.all?{|x, y| @board.dark?(x, y)}.should be_true + + tx, ty = @room.random_point + @board.blind_data[tx][ty] = :none + @board.dark?(tx, ty).should be_false + end + + it "#fill_dark_before_cancel" do + @board.set_blind_mode + @room.set_blind(:dark) + @room.blind_level_dark?.should be_true + @board.fill_blind + + 5.times do + tx, ty = @room.random_point + @board.blind_data[tx][ty] = :none + end + @room.each.all?{|x, y| @board.dark?(x, y)}.should be_false + + @board.instance_eval do + fill_dark_before_cancel + end + @room.each.all?{|x, y| @board.dark?(x, y)}.should be_true + end + + it "#open_blind will clear blind stat recursive" do + @board.set_blind_mode(Board::BLIND_MODE_BLIND) + @board.fill_blind + + @board.open_blind(10, 4, 0) + @board.blind_data[10][4].should == :none + @board.blind_data[10][3].should == :blind + @board.blind_data[10][5].should == :blind + + @board.open_blind(10, 4, 1) + @board.blind_data[10][4].should == :none + @board.blind_data[10][3].should == :none + @board.blind_data[10][5].should == :none + @board.blind_data[10][2].should == :blind + @board.blind_data[10][6].should == :blind + + @board.open_blind(10, 4, 2) + @board.blind_data[10][4].should == :none + @board.blind_data[10][3].should == :none + @board.blind_data[10][2].should == :none + @board.blind_data[10][1].should == :blind + + @board.blind_data[10][5].should == :none + @board.blind_data[9][5].should == :none + @board.blind_data[10][6].should == :none + @board.blind_data[11][5].should == :none + + @board.blind_data[8][5].should == :blind + @board.blind_data[12][5].should == :blind + @board.blind_data[9][6].should == :blind + @board.blind_data[11][6].should == :blind + @board.blind_data[10][7].should == :blind + end + + it "#open_blind will clear blind all of area for :open" do + @board.set_blind_mode + @board.fill_blind + + @board.open_blind(10, 4, 1) + @board.blind_data[10][4].should == :none + @board.blind_data[10][3].should == :none + @board.blind_data[10][5].should == :none + @board.blind_data[10][2].should == :blind + + @room.each do |x, y| + @board.blind_data[x][y].should == :none + end + end + + it "#open_blind will clear blind, and turn to dark for opened point" do + @board.set_blind_mode + @room.set_blind(:dark) + @board.fill_blind + + # 1歩目 + @board.open_blind(10, 5, 1) + + @board.blind_data[10][4].should == :none + + @board.blind_data[10][5].should == :none + @board.blind_data[9][5].should == :none + @board.blind_data[11][5].should == :none + @board.blind_data[10][6].should == :none + + # 2歩目 + @board.open_blind(10, 6, 1) + @board.blind_data[10][4].should == :none + + @board.blind_data[10][6].should == :none + @board.blind_data[9][6].should == :none + @board.blind_data[11][6].should == :none + @board.blind_data[10][5].should == :none + @board.blind_data[10][7].should == :none + + @board.blind_data[9][5].should == :dark + @board.blind_data[11][5].should == :dark + end + + it "#visible?/#invisible?" do + @board.set_blind_mode + @road2.set_blind(:dark) + @board.fill_blind + + @board.open_blind(10, 4, 1) + @board.visible?(10, 4).should be_true + @board.visible?(10, 3).should be_true + @board.visible?(10, 5).should be_true + @board.visible?(10, 2).should be_false + @board.invisible?(10, 2).should be_true + + @room.each do |x, y| + @board.visible?(x, y).should be_true + @board.invisible?(x, y).should be_false + end + + # dark + tx, ty = @road2.random_point + @board.visible?(tx, ty).should be_false + @board.invisible?(tx, ty).should be_true + + # out of range + @board.visible?(30, 30).should be_false + @board.invisible?(30, 30).should be_true + end + + end + +end
parrot-studio/rdgc-dm
d974f811a7391c956664f907da2b2a7719a64a68
remove rspec dependency
diff --git a/Rakefile b/Rakefile index 955c4e3..8bb3534 100644 --- a/Rakefile +++ b/Rakefile @@ -1,49 +1,49 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "rdgc-dm" gem.summary = %Q{Random Dungeon Maker from RDGC} gem.description = <<-TXT This gem is part of RDGC - Ruby(Random) Dungeon Game Core. RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. TXT gem.email = "[email protected]" gem.homepage = "http://github.com/parrot-studio/rdgc-dm" gem.authors = ["parrot_studio"] gem.required_ruby_version = ">= 1.8.7" - gem.add_development_dependency "rspec", ">= 1.2.9" + #gem.add_development_dependency "rspec", ">= 1.2.9" # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end task :spec => :check_dependencies task :default => :spec require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "rdgc-dm #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end
parrot-studio/rdgc-dm
20fbc06c91b1f7d0a451cf4038a00591a0ca5ea6
Version bump to 0.2.0
diff --git a/VERSION b/VERSION index 7ecf123..0ea3a94 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.0 +0.2.0
parrot-studio/rdgc-dm
fe190d6eac3330d25353d00de10d87c54ca4837f
add blind_area
diff --git a/lib/rdgc/map/blind_area.rb b/lib/rdgc/map/blind_area.rb new file mode 100644 index 0000000..e3647c3 --- /dev/null +++ b/lib/rdgc/map/blind_area.rb @@ -0,0 +1,183 @@ +# coding: UTF-8 +module RDGC + module Map + + class Area + + def blind_level + @blind_level + end + + def set_blind(level) + return unless [:none, :open, :blind, :dark].include?(level) + @blind_level = level + end + + def blind_level_none? + blind_level == :none ? true : false + end + + def blind_level_open? + blind_level == :open ? true : false + end + + def blind_level_blind? + blind_level == :blind ? true : false + end + + def blind_level_dark? + blind_level == :dark ? true : false + end + + end # Area + + class Board + + BLIND_MODE_NONE = :none + BLIND_MODE_NORMAL = :normal + BLIND_MODE_BLIND = :blind + + # override + def blind_level + # do nothing + end + + # override + def set_blind(level) + # do nothing + end + + def set_blind_mode(mode = nil) + @blind_mode = mode + @blind_mode ||= BLIND_MODE_NORMAL + init_blind + end + + def blind_mode + @blind_mode + end + + def blind_mode? + @blind_mode ? true : false + end + + def fill_blind + areas.each do |r| + case + when r.blind_level_none? + target = :none + when r.blind_level_dark? + target = :dark + else + target = :blind + end + + r.each do |x, y| + blind_data[x][y] = target + end + end + end + + def visible?(x, y) + return false unless has_xy?(x, y) + return true unless blind_mode? + v = blind_data[x][y] + return false unless v + v == :none ? true : false + end + + def invisible?(x, y) + ! visible?(x, y) + end + + def dark?(x, y) + return false unless has_xy?(x, y) + blind_data[x][y] == :dark ? true : false + end + + def open_blind(sx, sy, range) + return unless movable?(sx, sy) + + # 先にdarkのエリアを塗りつぶす + fill_dark_before_cancel + + # 再帰処理で解除 + open_list = [] + cancel_blind(sx, sy, open_list, range) + + # :openのareaを全解除 + return if open_list.empty? + open_list.uniq.each do |a| + a.each do |x, y| + blind_data[x][y] = :none + end + end + end + + def blind_data + @blind_data ||= Hash.new{|hash, key| hash[key] = {}} + @blind_data + end + + def init_blind + case blind_mode + when BLIND_MODE_NONE + init_blind_all(:none) + when BLIND_MODE_BLIND + init_blind_all(:blind) + when BLIND_MODE_NORMAL + init_blind_normal + end + end + + def init_blind_all(level) + areas.each do |r| + r.set_blind(level) + end + end + + def init_blind_normal + rooms.each do |r| + r.set_blind(:open) + end + + roads.each do |r| + r.set_blind(:blind) + end + end + + private + + def fill_dark_before_cancel + areas.select{|r| r.blind_level_dark?}.each do |r| + r.each do |x, y| + blind_data[x][y] = :dark + end + end + end + + def cancel_blind(sx, sy, open_list, range, r=0) + return unless movable?(sx, sy) + return if r > range + + # 今のポイントを可視に + blind_data[sx][sy] = :none + + # 今の座標が:openならareaを可視に + areas_for(sx, sy).each do |a| + next unless a.blind_level_open? + open_list << a unless open_list.include?(a) + end + + # 再帰的に処理 + Direction.each do |dir| + nx = sx + dir.x + ny = sy + dir.y + cancel_blind(nx, ny, open_list, range, r+1) + end + end + + end # Board + + end +end diff --git a/spec/rdgc/map/08_blind_area_spec.rb b/spec/rdgc/map/08_blind_area_spec.rb new file mode 100644 index 0000000..b99925d --- /dev/null +++ b/spec/rdgc/map/08_blind_area_spec.rb @@ -0,0 +1,336 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map + +describe "blind mode" do + + describe RDGC::Map::Area, "with blind" do + + before do + @area = Area.new + end + + it "level none" do + @area.set_blind(:none) + + @area.blind_level.should == :none + @area.blind_level_none?.should be_true + @area.blind_level_open?.should be_false + @area.blind_level_blind?.should be_false + @area.blind_level_dark?.should be_false + end + + it "level open" do + @area.set_blind(:open) + + @area.blind_level.should == :open + @area.blind_level_none?.should be_false + @area.blind_level_open?.should be_true + @area.blind_level_blind?.should be_false + @area.blind_level_dark?.should be_false + end + + it "level blind" do + @area.set_blind(:blind) + + @area.blind_level.should == :blind + @area.blind_level_none?.should be_false + @area.blind_level_open?.should be_false + @area.blind_level_blind?.should be_true + @area.blind_level_dark?.should be_false + end + + it "level dark" do + @area.set_blind(:dark) + + @area.blind_level.should == :dark + @area.blind_level_none?.should be_false + @area.blind_level_open?.should be_false + @area.blind_level_blind?.should be_false + @area.blind_level_dark?.should be_true + end + + it "unexpected level" do + @area.set_blind(:hoge) + + @area.blind_level.should be_nil + @area.blind_level_none?.should be_false + @area.blind_level_open?.should be_false + @area.blind_level_blind?.should be_false + @area.blind_level_dark?.should be_false + end + + end + + describe RDGC::Map::Board, "with blind" do + + before do + @board = Board.create(0, 20, 0, 20) + + @room = Room.create(5, 15, 5, 15) + @road1 = Road.create(0, 4, 10, 10) + @road2 = Road.create(16, 20, 12, 12) + + @board.rooms << @room + @board.roads << @road1 + @board.roads << @road2 + @board.fill + end + + it "#blind_level/#set_blind is disable" do + [:none, :open, :blind, :dark].each do |lv| + @board.set_blind(lv) + + @board.blind_level.should be_nil + @board.blind_level_none?.should be_false + @board.blind_level_open?.should be_false + @board.blind_level_blind?.should be_false + @board.blind_level_dark?.should be_false + end + end + + it "#init_blind_all will set :blind to all rooms/roads" do + @board.init_blind_all(:none) + @board.areas.each do |a| + a.blind_level_none?.should be_true + end + + @board.init_blind_all(:blind) + @board.areas.each do |a| + a.blind_level_blind?.should be_true + end + end + + it "#init_blind_normal will set :blind to roads, :open to rooms" do + @board.init_blind_normal + + @room.blind_level_open?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + end + + it "#init_blind will set blind_level each rooms/roads as blind_mode" do + @board.instance_eval do + @blind_mode = Board::BLIND_MODE_NONE + end + @board.init_blind + + @room.blind_level_none?.should be_true + @road1.blind_level_none?.should be_true + @road2.blind_level_none?.should be_true + + @board.instance_eval do + @blind_mode = Board::BLIND_MODE_NORMAL + end + @board.init_blind + + @room.blind_level_open?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + + @board.instance_eval do + @blind_mode = Board::BLIND_MODE_BLIND + end + @board.init_blind + + @room.blind_level_blind?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + end + + it "#set_blind_mode will set blind_mode, and init_blind" do + @board.blind_mode?.should be_false + + @board.set_blind_mode(Board::BLIND_MODE_NONE) + @board.blind_mode.should == Board::BLIND_MODE_NONE + @board.blind_mode?.should be_true + + @room.blind_level_none?.should be_true + @road1.blind_level_none?.should be_true + @road2.blind_level_none?.should be_true + + @board.set_blind_mode(Board::BLIND_MODE_NORMAL) + @board.blind_mode.should == Board::BLIND_MODE_NORMAL + @board.blind_mode?.should be_true + + @room.blind_level_open?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + + @board.set_blind_mode(Board::BLIND_MODE_BLIND) + @board.blind_mode.should == Board::BLIND_MODE_BLIND + @board.blind_mode?.should be_true + + @room.blind_level_blind?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + + @board.set_blind_mode + @board.blind_mode.should == Board::BLIND_MODE_NORMAL + @board.blind_mode?.should be_true + + @room.blind_level_open?.should be_true + @road1.blind_level_blind?.should be_true + @road2.blind_level_blind?.should be_true + end + + it "#fill_blind will fill blind_data as each area's blind_level" do + @board.set_blind_mode + @board.fill_blind + + @board.areas.each do |r| + r.each do |x, y| + @board.blind_data[x][y].should == :blind + end + end + + @board.set_blind_mode(:none) + @board.fill_blind + + @board.areas.each do |r| + r.each do |x, y| + @board.blind_data[x][y].should == :none + end + end + end + + it "#dark? judge this point is :dark now" do + @board.set_blind_mode + @room.set_blind(:dark) + @room.blind_level_dark?.should be_true + @board.fill_blind + + @room.each.all?{|x, y| @board.dark?(x, y)}.should be_true + + tx, ty = @room.random_point + @board.blind_data[tx][ty] = :none + @board.dark?(tx, ty).should be_false + end + + it "#fill_dark_before_cancel" do + @board.set_blind_mode + @room.set_blind(:dark) + @room.blind_level_dark?.should be_true + @board.fill_blind + + 5.times do + tx, ty = @room.random_point + @board.blind_data[tx][ty] = :none + end + @room.each.all?{|x, y| @board.dark?(x, y)}.should be_false + + @board.instance_eval do + fill_dark_before_cancel + end + @room.each.all?{|x, y| @board.dark?(x, y)}.should be_true + end + + it "#open_blind will clear blind stat recursive" do + @board.set_blind_mode(Board::BLIND_MODE_BLIND) + @board.fill_blind + + @board.open_blind(10, 4, 0) + @board.blind_data[10][4].should == :none + @board.blind_data[10][3].should == :blind + @board.blind_data[10][5].should == :blind + + @board.open_blind(10, 4, 1) + @board.blind_data[10][4].should == :none + @board.blind_data[10][3].should == :none + @board.blind_data[10][5].should == :none + @board.blind_data[10][2].should == :blind + @board.blind_data[10][6].should == :blind + + @board.open_blind(10, 4, 2) + @board.blind_data[10][4].should == :none + @board.blind_data[10][3].should == :none + @board.blind_data[10][2].should == :none + @board.blind_data[10][1].should == :blind + + @board.blind_data[10][5].should == :none + @board.blind_data[9][5].should == :none + @board.blind_data[10][6].should == :none + @board.blind_data[11][5].should == :none + + @board.blind_data[8][5].should == :blind + @board.blind_data[12][5].should == :blind + @board.blind_data[9][6].should == :blind + @board.blind_data[11][6].should == :blind + @board.blind_data[10][7].should == :blind + end + + it "#open_blind will clear blind all of area for :open" do + @board.set_blind_mode + @board.fill_blind + + @board.open_blind(10, 4, 1) + @board.blind_data[10][4].should == :none + @board.blind_data[10][3].should == :none + @board.blind_data[10][5].should == :none + @board.blind_data[10][2].should == :blind + + @room.each do |x, y| + @board.blind_data[x][y].should == :none + end + end + + it "#open_blind will clear blind, and turn to dark for opened point" do + @board.set_blind_mode + @room.set_blind(:dark) + @board.fill_blind + + # 1歩目 + @board.open_blind(10, 5, 1) + + @board.blind_data[10][4].should == :none + + @board.blind_data[10][5].should == :none + @board.blind_data[9][5].should == :none + @board.blind_data[11][5].should == :none + @board.blind_data[10][6].should == :none + + # 2歩目 + @board.open_blind(10, 6, 1) + @board.blind_data[10][4].should == :none + + @board.blind_data[10][6].should == :none + @board.blind_data[9][6].should == :none + @board.blind_data[11][6].should == :none + @board.blind_data[10][5].should == :none + @board.blind_data[10][7].should == :none + + @board.blind_data[9][5].should == :dark + @board.blind_data[11][5].should == :dark + end + + it "#visible?/#invisible?" do + @board.set_blind_mode + @road2.set_blind(:dark) + @board.fill_blind + + @board.open_blind(10, 4, 1) + @board.visible?(10, 4).should be_true + @board.visible?(10, 3).should be_true + @board.visible?(10, 5).should be_true + @board.visible?(10, 2).should be_false + @board.invisible?(10, 2).should be_true + + @room.each do |x, y| + @board.visible?(x, y).should be_true + @board.invisible?(x, y).should be_false + end + + # dark + tx, ty = @road2.random_point + @board.visible?(tx, ty).should be_false + @board.invisible?(tx, ty).should be_true + + # out of range + @board.visible?(30, 30).should be_false + @board.invisible?(30, 30).should be_true + end + + end + +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index dd0ec27..f786f2c 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,11 +1,11 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) -require 'rdgc-dm' +require 'rdgc-dm-blind' require 'spec' require 'spec/autorun' include RDGC Spec::Runner.configure do |config| end
parrot-studio/rdgc-dm
b5db2af10465d40d5403588f06d315216229f80d
add Map::Direction
diff --git a/lib/rdgc-dm.rb b/lib/rdgc-dm.rb index 1a3a071..e33591f 100644 --- a/lib/rdgc-dm.rb +++ b/lib/rdgc-dm.rb @@ -1,17 +1,18 @@ # coding: UTF-8 require 'rdgc/util/config' require 'rdgc/util/random_util' include RDGC::Util::RandomUtil require 'rdgc/map/tile' require 'rdgc/map/tile_type' require 'rdgc/map/area' require 'rdgc/map/block' require 'rdgc/map/room' require 'rdgc/map/road' require 'rdgc/map/board' +require 'rdgc/map/direction' require 'rdgc/maker/temp_block' require 'rdgc/maker/dungeon_maker' require 'rdgc/maker/divide_temp_block' require 'rdgc/maker/divide_dungeon_maker' diff --git a/lib/rdgc/map/direction.rb b/lib/rdgc/map/direction.rb new file mode 100644 index 0000000..cba0193 --- /dev/null +++ b/lib/rdgc/map/direction.rb @@ -0,0 +1,58 @@ +# -*- coding: UTF-8 -*- +module RDGC + module Map + class Direction + + attr_reader :x, :y + + private + + def self.create(x, y) + obj = self.new + + obj.instance_eval do + @x = x + @y = y + end + + obj.freeze + obj + end + + public + + SELF = self.create(0, 0) + LEFT = self.create(-1, 0) + RIGHT = self.create(1, 0) + UPPER = self.create(0, -1) + BOTTOM = self.create(0, 1) + + def self.each + return to_enum(:each) unless block_given? + self.all.each do |d| + yield(d) + end + end + + def self.all + [LEFT, UPPER, RIGHT, BOTTOM] + end + + def opposite + case self + when LEFT + RIGHT + when RIGHT + LEFT + when UPPER + BOTTOM + when BOTTOM + UPPER + when SELF + SELF + end + end + + end + end +end \ No newline at end of file diff --git a/spec/rdgc/map/07_direction_spec.rb b/spec/rdgc/map/07_direction_spec.rb new file mode 100644 index 0000000..fd55153 --- /dev/null +++ b/spec/rdgc/map/07_direction_spec.rb @@ -0,0 +1,56 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map + +describe RDGC::Map::Direction do + + it "SELF is point itself" do + Direction::SELF.x.should == 0 + Direction::SELF.y.should == 0 + + Direction::SELF.opposite.should equal(Direction::SELF) + end + + it "UPPER is upper of point" do + Direction::UPPER.x.should == 0 + Direction::UPPER.y.should == -1 + + Direction::UPPER.opposite.should equal(Direction::BOTTOM) + end + + it "BOTTOM is bottom of point" do + Direction::BOTTOM.x.should == 0 + Direction::BOTTOM.y.should == 1 + + Direction::BOTTOM.opposite.should equal(Direction::UPPER) + end + + it "LEFT is left of point" do + Direction::LEFT.x.should == -1 + Direction::LEFT.y.should == 0 + + Direction::LEFT.opposite.should equal(Direction::RIGHT) + end + + it "RIGHT is right of point" do + Direction::RIGHT.x.should == 1 + Direction::RIGHT.y.should == 0 + + Direction::RIGHT.opposite.should equal(Direction::LEFT) + end + + it "all provides all Direction at clockwise" do + dirs = [Direction::LEFT, Direction::UPPER, Direction::RIGHT, Direction::BOTTOM] + Direction.all.should == dirs + end + + it "each provides each Direction at clockwise" do + dirs = [Direction::LEFT, Direction::UPPER, Direction::RIGHT, Direction::BOTTOM] + + Direction.each.with_index do |d, i| + d.should equal(dirs[i]) + end + end + +end
parrot-studio/rdgc-dm
2e123eac8543d5da66024bbe531ec7c41701c3ab
add Board#areas/areas_for
diff --git a/lib/rdgc/map/board.rb b/lib/rdgc/map/board.rb index 73ac6fd..9596d8c 100644 --- a/lib/rdgc/map/board.rb +++ b/lib/rdgc/map/board.rb @@ -1,81 +1,89 @@ # coding: UTF-8 module RDGC module Map class Board < Area def self.create_from_blocks(blocks) d = self.new d.init(blocks) d end def init(list) return unless list return if list.empty? @blocks = list @rooms = blocks.map(&:room).compact @roads = blocks.map(&:roads).flatten.compact set_coordinates fill end def set_coordinates return unless blocks self.top = blocks.map(&:top).min self.bottom = blocks.map(&:bottom).max self.left = blocks.map(&:left).min self.right = blocks.map(&:right).max end def fill # 初期化 fill_tile TileType::WALL rooms.each do |r| r.each_tile do |x, y, t| set_tile(x, y, t) end end roads.each do |r| r.each_tile do |x, y, t| set_tile(x, y, t) end end end def blocks @blocks ||= [] @blocks end def rooms @rooms ||= [] @rooms end def roads @roads ||= [] @roads end + def areas + [rooms, roads].flatten + end + + def areas_for(x, y) + areas.select{|a| a.has_xy?(x, y)} + end + def movable?(x, y) return false unless has_xy?(x, y) tile(x, y).movable? end def room?(x, y) return false unless has_xy?(x, y) tile(x, y).room? end def road?(x, y) return false unless has_xy?(x, y) tile(x, y).road? end end end end diff --git a/spec/rdgc/map/06_board_spec.rb b/spec/rdgc/map/06_board_spec.rb index 35913e9..58e7ff5 100644 --- a/spec/rdgc/map/06_board_spec.rb +++ b/spec/rdgc/map/06_board_spec.rb @@ -1,132 +1,164 @@ # coding: UTF-8 require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') include RDGC::Map describe RDGC::Map::Board, 'has rooms and roads from Blocks' do it "#set_coordinates will set self coordinates from blocks coordinates" do b = Board.create(1, 1, 1, 1) b.should be_an_instance_of(Board) b.width.should == 1 b.height.should == 1 b.blocks << Block.create(0, 20, 10, 30) b.blocks << Block.create(10, 30, 20, 40) b.set_coordinates b.top.should == 0 b.bottom.should == 30 b.left.should == 10 b.right.should == 40 end + it "#areas provides rooms and roads list" do + b = Board.create(0, 20, 0, 20) + + room = Room.create(5, 15, 5, 15) + road1 = Road.create(0, 4, 10, 10) + road2 = Road.create(16, 20, 12, 12) + + b.rooms << room + b.roads << road1 + b.roads << road2 + + b.areas.each do |a| + [room, road1, road2].should be_include(a) + end + end + + it "#areas_for provide rooms/roads list at (x, y)" do + b = Board.create(0, 20, 0, 20) + + room = Room.create(5, 15, 5, 15) + road1 = Road.create(0, 4, 10, 10) + road2 = Road.create(16, 20, 12, 12) + + b.rooms << room + b.roads << road1 + b.roads << road2 + + b.areas_for(10, 10).should be_include(room) + b.areas_for(10, 2).should be_include(road1) + b.areas_for(12, 20).should be_include(road2) + end + it "#fill will fill room/road, and fill at wall other coordinates" do b = Board.create(0, 20, 0, 20) room = Room.create(5, 15, 5, 15) road1 = Road.create(0, 4, 10, 10) road2 = Road.create(16, 20, 12, 12) b.rooms << room b.roads << road1 b.roads << road2 b.fill b.each_tile do |x, y, t| case t when TileType::WALL room.has_xy?(x, y).should be_false road1.has_xy?(x, y).should be_false road2.has_xy?(x, y).should be_false b.movable?(x, y).should be_false b.room?(x, y).should be_false b.road?(x, y).should be_false when TileType::ROOM room.has_xy?(x, y).should be_true road1.has_xy?(x, y).should be_false road2.has_xy?(x, y).should be_false b.movable?(x, y).should be_true b.room?(x, y).should be_true b.road?(x, y).should be_false when TileType::ROAD room.has_xy?(x, y).should be_false [road1, road2].map{|r| r.has_xy?(x, y)}.any?.should be_true b.movable?(x, y).should be_true b.room?(x, y).should be_false b.road?(x, y).should be_true end end end it "#init will initialize self from blocks, and create_from_blocks will provides init Board" do block1 = Block.create(0, 20, 0, 20) room1 = Room.create(5, 15, 5, 15) road1 = Road.create(0, 4, 10, 10) road2 = Road.create(16, 20, 12, 12) block1.room = room1 block1.add_road(road1) block1.add_road(road2) block2 = Block.create(21, 40, 0, 20) room2 = Room.create(25, 35, 25, 35) road3 = Road.create(21, 24, 12, 12) block2.room = room2 block2.add_road(road3) b1 = Board.create(1, 1, 1, 1) b1.init([block1, block2]) b2 = Board.create_from_blocks([block1, block2]) b2.should be_an_instance_of(Board) [b1, b2].each do |b| b.blocks.should be_include(block1) b.blocks.should be_include(block2) b.rooms.should be_include(room1) b.rooms.should be_include(room2) b.roads.should be_include(road1) b.roads.should be_include(road2) b.roads.should be_include(road3) # set_coordinates b.top.should == 0 b.bottom.should == 40 b.left.should == 0 b.right.should == 20 # fill b.each_tile do |x, y, t| case t when TileType::WALL [room1, room2].map{|r| r.has_xy?(x, y)}.any?.should be_false [road1, road2, road3].map{|r| r.has_xy?(x, y)}.any?.should be_false b.movable?(x, y).should be_false b.room?(x, y).should be_false b.road?(x, y).should be_false when TileType::ROOM [room1, room2].map{|r| r.has_xy?(x, y)}.any?.should be_true [road1, road2, road3].map{|r| r.has_xy?(x, y)}.any?.should be_false b.movable?(x, y).should be_true b.room?(x, y).should be_true b.road?(x, y).should be_false when TileType::ROAD [room1, room2].map{|r| r.has_xy?(x, y)}.any?.should be_false [road1, road2, road3].map{|r| r.has_xy?(x, y)}.any?.should be_true b.movable?(x, y).should be_true b.room?(x, y).should be_false b.road?(x, y).should be_true end end end end end \ No newline at end of file
parrot-studio/rdgc-dm
e9c48e06b9853f7294a0bded538b1354a3524f57
ミスタイプを修正
diff --git a/Rakefile b/Rakefile index e9b37ad..955c4e3 100644 --- a/Rakefile +++ b/Rakefile @@ -1,49 +1,49 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "rdgc-dm" gem.summary = %Q{Random Dungeon Maker from RDGC} gem.description = <<-TXT This gem is part of RDGC - Ruby(Random) Dungeon Game Core. - RDGC is core of random dungeon game (like rogue), make dungeon, manage mnsters etc. + RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. TXT gem.email = "[email protected]" gem.homepage = "http://github.com/parrot-studio/rdgc-dm" gem.authors = ["parrot_studio"] gem.required_ruby_version = ">= 1.8.7" gem.add_development_dependency "rspec", ">= 1.2.9" # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end require 'spec/rake/spectask' Spec::Rake::SpecTask.new(:spec) do |spec| spec.libs << 'lib' << 'spec' spec.spec_files = FileList['spec/**/*_spec.rb'] end Spec::Rake::SpecTask.new(:rcov) do |spec| spec.libs << 'lib' << 'spec' spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end task :spec => :check_dependencies task :default => :spec require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "rdgc-dm #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end diff --git a/rdgc-dm.gemspec b/rdgc-dm.gemspec index 3498643..f3fe0cb 100644 --- a/rdgc-dm.gemspec +++ b/rdgc-dm.gemspec @@ -1,92 +1,93 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{rdgc-dm} s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["parrot_studio"] s.date = %q{2010-04-01} s.description = %q{ This gem is part of RDGC - Ruby(Random) Dungeon Game Core. - RDGC is core of random dungeon game (like rogue), make dungeon, manage mnsters etc. + RDGC is core of random dungeon game (like rogue), make dungeon, manage monsters etc. } s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "lib/rdgc-dm.rb", "lib/rdgc/maker/divide_dungeon_maker.rb", "lib/rdgc/maker/divide_temp_block.rb", "lib/rdgc/maker/dungeon_maker.rb", "lib/rdgc/maker/temp_block.rb", "lib/rdgc/map/area.rb", "lib/rdgc/map/block.rb", "lib/rdgc/map/board.rb", "lib/rdgc/map/road.rb", "lib/rdgc/map/room.rb", "lib/rdgc/map/tile.rb", "lib/rdgc/map/tile_type.rb", "lib/rdgc/util/config.rb", "lib/rdgc/util/random_util.rb", + "rdgc-dm.gemspec", "spec/rdgc/maker/01_temp_block_spec.rb", "spec/rdgc/maker/02_divide_temp_block_spec.rb", "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb", "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", "spec/rdgc/map/01_tile_spec.rb", "spec/rdgc/map/02_area_spec.rb", "spec/rdgc/map/03_road_spec.rb", "spec/rdgc/map/04_room_spec.rb", "spec/rdgc/map/05_block_spec.rb", "spec/rdgc/map/06_board_spec.rb", "spec/rdgc/util/01_config_spec.rb", "spec/rdgc/util/02_random_util_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/parrot-studio/rdgc-dm} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") s.rubygems_version = %q{1.3.6} s.summary = %q{Random Dungeon Maker from RDGC} s.test_files = [ "spec/spec_helper.rb", "spec/rdgc/util/02_random_util_spec.rb", "spec/rdgc/util/01_config_spec.rb", "spec/rdgc/map/04_room_spec.rb", "spec/rdgc/map/06_board_spec.rb", "spec/rdgc/map/01_tile_spec.rb", "spec/rdgc/map/03_road_spec.rb", "spec/rdgc/map/05_block_spec.rb", "spec/rdgc/map/02_area_spec.rb", "spec/rdgc/maker/02_divide_temp_block_spec.rb", "spec/rdgc/maker/01_temp_block_spec.rb", "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) else s.add_dependency(%q<rspec>, [">= 1.2.9"]) end else s.add_dependency(%q<rspec>, [">= 1.2.9"]) end end
parrot-studio/rdgc-dm
f65d21947d4738eef44345ad0d5f333399385514
rdocを再修正
diff --git a/README.rdoc b/README.rdoc index d7f8764..0d4a111 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,148 +1,148 @@ = rdgc-dm Author:: parrot_studio <parrot *at* users.sourceforge.jp> License:: The MIT License * 要求されたサイズのランダムダンジョンを生成 * ダンジョンは部屋と道で構成される == Install gem install gemcutter # インストール済みなら不要 gem install rdgc-dm == Usage -require 'rubygems' -require 'rdgc-dm' - -include RDGC::Maker - -board = DivideDungeonMaker.create(30, 40) # width=30, height=40のMap::Boardを作る場合 -board = DivideDungeonMaker.create(30, 40, :min_room_count = 4) # パラメータ指定(4つ以上の部屋数を期待) - -board.each do |x, y| # each で各座標を順に処理 - t = board.tile(x, y) # Tileオブジェクト取得 - case - when t.wall? # 壁 - ... - when t.room? # 部屋 - ... - when t.road? # 道 - ... - end -end - -board.each_tile do |x, y, t| # each_tileで座標とTileを一緒に取得 - ... -end - -rooms = board.rooms # Map::Roomオブジェクトの配列取得 -roads = board.roads # Map::Roadオブジェクトの配列取得 - -r = rooms.choice -x, y = r.random_point # あるエリアのランダムな座標を取得 - -board.room?(2, 3) # 指定座標(x, y)が部屋か判定 -board.road?(2, 3) # 指定座標(x, y)が道か判定 -board.movable?(2, 3) # 指定座標(x, y)が移動可能(部屋or道)か判定 - -# その他、Map::Areaに定義されたメソッドは全て使える - -# RDGC::Util::RandomUtilで定義され、top-levelにinclude済みのメソッド -# 数値は全て整数を指定すること - -bool_rand # trueかfalseを返す -range_rand(min, max) # minからmaxまでのどれかの整数値を返す -select_rand(:a => 3, :b => 2, :c => 1) # :aを3/(3+2+1)、:bを2/(3+2+1)...の確率で返す - -dice(5, 10) # 10面のサイコロを5回振った合計を返す -5.dice(10) # Integer#dice(max)が定義済みで、この場合はdice(5, 10)と同じ -5.d10 # TRPGプレイヤーにおなじみの書き方 - -# その他、細かなメソッドはソースやspec等参照 + require 'rubygems' + require 'rdgc-dm' + + include RDGC::Maker + + board = DivideDungeonMaker.create(30, 40) # width=30, height=40のMap::Boardを作る場合 + board = DivideDungeonMaker.create(30, 40, :min_room_count = 4) # パラメータ指定(4つ以上の部屋数を期待) + + board.each do |x, y| # each で各座標を順に処理 + t = board.tile(x, y) # Tileオブジェクト取得 + case + when t.wall? # 壁 + ... + when t.room? # 部屋 + ... + when t.road? # 道 + ... + end + end + + board.each_tile do |x, y, t| # each_tileで座標とTileを一緒に取得 + ... + end + + rooms = board.rooms # Map::Roomオブジェクトの配列取得 + roads = board.roads # Map::Roadオブジェクトの配列取得 + + r = rooms.choice + x, y = r.random_point # あるエリアのランダムな座標を取得 + + board.room?(2, 3) # 指定座標(x, y)が部屋か判定 + board.road?(2, 3) # 指定座標(x, y)が道か判定 + board.movable?(2, 3) # 指定座標(x, y)が移動可能(=部屋or道)か判定 + + # その他、Map::Areaに定義されたメソッドは全て使える + + # RDGC::Util::RandomUtilで定義され、top-levelにinclude済みのメソッド + # 数値は全て整数を指定すること + + bool_rand # trueかfalseを返す + range_rand(min, max) # minからmaxまでのどれかの整数値を返す + select_rand(:a => 3, :b => 2, :c => 1) # :aを3/(3+2+1)、:bを2/(3+2+1)...の確率で返す + + dice(5, 10) # 10面のサイコロを5回振った合計を返す + 5.dice(10) # Integer#dice(max)が定義済みで、この場合はdice(5, 10)と同じ + 5.d10 # TRPGプレイヤーにおなじみの書き方 + + # その他、細かなメソッドはソースやspec等参照 == Create Parameters -前提として、生成パラメータは努力目標 -できるだけ指定を満たそうとはするが、ランダムなので保証はできない - -まず全体を一つのBlockとして定義し、それを再帰的に分割した後、 -各Blockに部屋か交差点を作るため、Blockとは1:1の関係になる + 前提として、生成パラメータは努力目標 + できるだけ指定を満たそうとはするが、ランダムなので保証はできない + + まず全体を一つのBlockとして定義し、それを再帰的に分割した後、 + 各Blockに部屋か交差点を作るため、Blockとは1:1の関係になる * :min_block_size => 分割Blockの最低サイズ * :max_block_count => Blockの最大生成数 * :min_room_size => 部屋の最低サイズ(デフォルトは4で、4以下は強制的に4) * :max_room_size => 部屋の最大サイズ * :min_room_count => 部屋の最低生成数(デフォルトは2) * :max_room_count => 部屋の最大生成数 * :max_depth => 分割再帰の深さ max_depth=nのとき、Blockの最大数は2^nになる * :cross_road_ratio => 交差点生成率(0 <= x <= 9) == FAQ === パラメータが適用されない -パラメータには適用優先順位があります + パラメータには適用優先順位があります 1. min_block_size 2. max_block_count 3. max_depth 4. min_room_count 5. max_room_count 6. cross_road_ratio 7. max_room_size 8. min_room_size -上位のパラメータに対し、下位のパラメータが矛盾した場合、 -無視はしませんが、保証はされません + 上位のパラメータに対し、下位のパラメータが矛盾した場合、 + 無視はしませんが、保証はされません === max_room_count=1なのに部屋が2個できる -min_room_countのデフォルト値が2なので、 -上記の優先順位に従い、部屋が2個できます -(デフォルトが2個なのは、スタート地点とゴール地点を作るためです) -明示的にmin_room_count=1をあわせて指定すると、一つだけできるはずです + min_room_countのデフォルト値が2なので、 + 上記の優先順位に従い、部屋が2個できます + (デフォルトが2個なのは、スタート地点とゴール地点を作るためです) + 明示的にmin_room_count=1をあわせて指定すると、一つだけできるはずです === 道に(部屋でない)行き止まりができる -仕様です - -それで片付けるのもあれなので補足すると、 -つなげられそうな交差点を、できるだけつなぐようにしているものの、 -周囲にもうBlockがない等、どうしようもない場合に行き止まりができます - -あまりたくさんできると問題ですが、 -たまにあるくらいはゲームとしていいんじゃないかと + 仕様です + + それで片付けるのもあれなので補足すると、 + つなげられそうな交差点を、できるだけつなぐようにしているものの、 + 周囲に残りBlockがない等、どうしようもない場合に行き止まりができます + + あまりたくさんできると問題ですが、 + たまにあるくらいはゲームとしていいんじゃないかと === 最大分割深度(max_depth)って何? -DivideDungeonMakerは最初のBlockを起点にして、再帰的な分割をしようとします - -この分割回数の最大値がmax_depthの指定で、これを小さくすることで、 -小さいBlockだらけになるのを防げます -max_depth=nの時、作られるBlockの最大値は2^nです + DivideDungeonMakerは最初のBlockを起点にして、再帰的な分割をしようとします + + この分割回数の最大値がmax_depthの指定で、これを小さくすることで、 + 小さいBlockだらけになるのを防げます + max_depth=nの時、作られるBlockの最大値は2^nです === イベントやBOSS用に、広い部屋が1つだけ欲しい -min_room_sizeをx/y以上にしたうえで、 -min_block_sizeをx/y以上にするか、max_block_count=1を指定してください -全体が1Blockになり、限界までRoomを大きくしようとします + min_room_sizeをx/y以上にしたうえで、 + min_block_sizeをx/y以上にするか、max_block_count=1を指定してください + 全体が1Blockになり、限界までRoomを大きくしようとします === スタートとゴール(階段)って無いの? -rdgc-dmはあくまで部屋と道(の座標系)を作るための仕組みです -スタートやゴールの概念は各ゲームによって異なるため、 -rdgc-dmには含んでいません(RDGCとしては存在します) - -Area#ramdom_pointで各Areaのランダムな座標が取れますので、 -それを使ってスタートやゴールやモンスターを配置してください + rdgc-dmはあくまで部屋と道(の座標系)を作るための仕組みです + スタートやゴールの概念は各ゲームによって異なるため、 + rdgc-dmには含んでいません(RDGCとしては存在します) + + Area#ramdom_pointで各Areaのランダムな座標が取れますので、 + それを使ってスタートやゴールやモンスターを配置してください === 自分でロジックを書きたい * RDGC::Maker::DungeonMakerをincludeしたクラス * RDGC::Maker::TempBlockを継承したクラス -これらを組み合わせると自分のロジックが書けます -詳しくはDivideDungeonMaker/DivideTempBlockのソースを見てください + これらを組み合わせると自分のロジックが書けます + 詳しくはDivideDungeonMaker/DivideTempBlockのソースを見てください == Copyright -Copyright (c) 2010 parrot_studio. See LICENSE for details. +Copyright (c) 2010 parrot_studio. See LICENSE for details \ No newline at end of file
parrot-studio/rdgc-dm
77cb40bb4be1d457c749e34e72fbbdcd2964a4b1
rdocを修正
diff --git a/README.rdoc b/README.rdoc index 4194551..d7f8764 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,148 +1,148 @@ = rdgc-dm Author:: parrot_studio <parrot *at* users.sourceforge.jp> License:: The MIT License * 要求されたサイズのランダムダンジョンを生成 * ダンジョンは部屋と道で構成される == Install gem install gemcutter # インストール済みなら不要 gem install rdgc-dm == Usage - require 'rubygems' - require 'rdgc-dm' - - include RDGC::Maker - - board = DivideDungeonMaker.create(30, 40) # width=30, height=40のMap::Boardを作る場合 - board = DivideDungeonMaker.create(30, 40, :min_room_count = 4) # パラメータ指定(4つ以上の部屋数を期待) - - board.each do |x, y| # each で各座標を順に処理 - t = board.tile(x, y) # Tileオブジェクト取得 - case - when t.wall? # 壁 - ... - when t.room? # 部屋 - ... - when t.road? # 道 - ... - end - end - - board.each_tile do |x, y, t| # each_tileで座標とTileを一緒に取得 - ... - end - - rooms = board.rooms # Map::Roomオブジェクトの配列取得 - roads = board.roads # Map::Roadオブジェクトの配列取得 - - r = rooms.choice - x, y = r.random_point # あるエリアのランダムな座標を取得 - - board.room?(2, 3) # 指定座標(x, y)が部屋か判定 - board.road?(2, 3) # 指定座標(x, y)が部屋か判定 - board.movable?(2, 3) # 指定座標(x, y)が移動可能か判定 - - # その他、Map::Areaに定義されたメソッドは全て使える - - # RDGC::Util::RandomUtilで定義され、top-levelにinclude済みのメソッド - # 数値は全て整数を指定すること - - bool_rand # trueかfalseを返す - range_rand(min, max) # minからmaxまでのどれかの整数値を返す - select_rand(:a => 3, :b => 2, :c => 1) # :aを3/(3+2+1)、:bを2/(3+2+1)...の確率で返す - - dice(5, 10) # 10面のサイコロを5回振った合計を返す - 5.dice(10) # Integer#dice(max)が定義済みで、この場合はdice(5, 10)と同じ - 5.d10 # TRPGプレイヤーにおなじみの書き方 - - # その他、細かなメソッドはソースやspec等参照 +require 'rubygems' +require 'rdgc-dm' + +include RDGC::Maker + +board = DivideDungeonMaker.create(30, 40) # width=30, height=40のMap::Boardを作る場合 +board = DivideDungeonMaker.create(30, 40, :min_room_count = 4) # パラメータ指定(4つ以上の部屋数を期待) + +board.each do |x, y| # each で各座標を順に処理 + t = board.tile(x, y) # Tileオブジェクト取得 + case + when t.wall? # 壁 + ... + when t.room? # 部屋 + ... + when t.road? # 道 + ... + end +end + +board.each_tile do |x, y, t| # each_tileで座標とTileを一緒に取得 + ... +end + +rooms = board.rooms # Map::Roomオブジェクトの配列取得 +roads = board.roads # Map::Roadオブジェクトの配列取得 + +r = rooms.choice +x, y = r.random_point # あるエリアのランダムな座標を取得 + +board.room?(2, 3) # 指定座標(x, y)が部屋か判定 +board.road?(2, 3) # 指定座標(x, y)が道か判定 +board.movable?(2, 3) # 指定座標(x, y)が移動可能(部屋or道)か判定 + +# その他、Map::Areaに定義されたメソッドは全て使える + +# RDGC::Util::RandomUtilで定義され、top-levelにinclude済みのメソッド +# 数値は全て整数を指定すること + +bool_rand # trueかfalseを返す +range_rand(min, max) # minからmaxまでのどれかの整数値を返す +select_rand(:a => 3, :b => 2, :c => 1) # :aを3/(3+2+1)、:bを2/(3+2+1)...の確率で返す + +dice(5, 10) # 10面のサイコロを5回振った合計を返す +5.dice(10) # Integer#dice(max)が定義済みで、この場合はdice(5, 10)と同じ +5.d10 # TRPGプレイヤーにおなじみの書き方 + +# その他、細かなメソッドはソースやspec等参照 == Create Parameters - 前提として、生成パラメータは努力目標 - できるだけ指定を満たそうとはするが、ランダムなので保証はできない - - まず全体を一つのBlockとして定義し、それを再帰的に分割した後、 - 各Blockに部屋か交差点を作るため、Blockとは1:1の関係になる +前提として、生成パラメータは努力目標 +できるだけ指定を満たそうとはするが、ランダムなので保証はできない + +まず全体を一つのBlockとして定義し、それを再帰的に分割した後、 +各Blockに部屋か交差点を作るため、Blockとは1:1の関係になる * :min_block_size => 分割Blockの最低サイズ * :max_block_count => Blockの最大生成数 * :min_room_size => 部屋の最低サイズ(デフォルトは4で、4以下は強制的に4) * :max_room_size => 部屋の最大サイズ * :min_room_count => 部屋の最低生成数(デフォルトは2) * :max_room_count => 部屋の最大生成数 * :max_depth => 分割再帰の深さ max_depth=nのとき、Blockの最大数は2^nになる * :cross_road_ratio => 交差点生成率(0 <= x <= 9) == FAQ === パラメータが適用されない - パラメータには適用優先順位があります +パラメータには適用優先順位があります 1. min_block_size 2. max_block_count 3. max_depth 4. min_room_count 5. max_room_count 6. cross_road_ratio 7. max_room_size 8. min_room_size - 上位のパラメータに対し、下位のパラメータが矛盾した場合、 - 無視はしませんが、保証はされません +上位のパラメータに対し、下位のパラメータが矛盾した場合、 +無視はしませんが、保証はされません === max_room_count=1なのに部屋が2個できる - min_room_countのデフォルト値が2なので、 - 上記の優先順位に従い、部屋が2個できます - (デフォルトが2個なのは、スタート地点とゴール地点を作るためです) - 明示的にmin_room_count=1をあわせて指定すると、一つだけできるはずです +min_room_countのデフォルト値が2なので、 +上記の優先順位に従い、部屋が2個できます +(デフォルトが2個なのは、スタート地点とゴール地点を作るためです) +明示的にmin_room_count=1をあわせて指定すると、一つだけできるはずです === 道に(部屋でない)行き止まりができる - 仕様です - - それで片付けるのもあれなので補足すると、 - つなげられそうな交差点を、できるだけつなぐようにしているものの、 - 周囲に残りBlockがない等、どうしようもない場合に行き止まりができます - - あまりたくさんできると問題ですが、 - たまにあるくらいはゲームとしていいんじゃないかと +仕様です + +それで片付けるのもあれなので補足すると、 +つなげられそうな交差点を、できるだけつなぐようにしているものの、 +周囲にもうBlockがない等、どうしようもない場合に行き止まりができます + +あまりたくさんできると問題ですが、 +たまにあるくらいはゲームとしていいんじゃないかと === 最大分割深度(max_depth)って何? - DivideDungeonMakerは最初のBlockを起点にして、再帰的な分割をしようとします - - この分割回数の最大値がmax_depthの指定で、これを小さくすることで、 - 小さいBlockだらけになるのを防げます - max_depth=nの時、作られるBlockの最大値は2^nです +DivideDungeonMakerは最初のBlockを起点にして、再帰的な分割をしようとします + +この分割回数の最大値がmax_depthの指定で、これを小さくすることで、 +小さいBlockだらけになるのを防げます +max_depth=nの時、作られるBlockの最大値は2^nです === イベントやBOSS用に、広い部屋が1つだけ欲しい - min_room_sizeをx/y以上にしたうえで、 - min_block_sizeをx/y以上にするか、max_block_count=1を指定してください - 全体が1Blockになり、限界までRoomを大きくしようとします +min_room_sizeをx/y以上にしたうえで、 +min_block_sizeをx/y以上にするか、max_block_count=1を指定してください +全体が1Blockになり、限界までRoomを大きくしようとします === スタートとゴール(階段)って無いの? - rdgc-dmはあくまで部屋と道(の座標系)を作るための仕組みです - スタートやゴールの概念は各ゲームによって異なるため、 - rdgc-dmには含んでいません(RDGCとしては存在します) - - Area#ramdom_pointで各Areaのランダムな座標が取れますので、 - それを使ってスタートやゴールやモンスターを配置してください +rdgc-dmはあくまで部屋と道(の座標系)を作るための仕組みです +スタートやゴールの概念は各ゲームによって異なるため、 +rdgc-dmには含んでいません(RDGCとしては存在します) + +Area#ramdom_pointで各Areaのランダムな座標が取れますので、 +それを使ってスタートやゴールやモンスターを配置してください === 自分でロジックを書きたい * RDGC::Maker::DungeonMakerをincludeしたクラス * RDGC::Maker::TempBlockを継承したクラス - これらを組み合わせると自分のロジックが書けます - 詳しくはDivideDungeonMaker/DivideTempBlockのソースを見てください +これらを組み合わせると自分のロジックが書けます +詳しくはDivideDungeonMaker/DivideTempBlockのソースを見てください == Copyright Copyright (c) 2010 parrot_studio. See LICENSE for details.
parrot-studio/rdgc-dm
353eed9ffad6fa0070ac4cfbf48159811bf60024
rdoc rewrite
diff --git a/README.rdoc b/README.rdoc index fac6dbc..4194551 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,148 +1,148 @@ = rdgc-dm Author:: parrot_studio <parrot *at* users.sourceforge.jp> License:: The MIT License * 要求されたサイズのランダムダンジョンを生成 * ダンジョンは部屋と道で構成される == Install gem install gemcutter # インストール済みなら不要 gem install rdgc-dm == Usage -require 'rubygems' -require 'rdgc-dm' - -include RDGC::Maker - -board = DivideDungeonMaker.create(30, 40) # width=30, height=40のMap::Boardを作る場合 -board = DivideDungeonMaker.create(30, 40, :min_room_count = 4) # パラメータ指定(4つ以上の部屋数を期待) - -board.each do |x, y| # each で各座標を順に処理 - t = board.tile(x, y) # Tileオブジェクト取得 - case - when t.wall? # 壁 - ... - when t.room? # 部屋 - ... - when t.road? # 道 - ... - end -end - -board.each_tile do |x, y, t| # each_tileで座標とTileを一緒に取得 - ... -end - -rooms = board.rooms # Map::Roomオブジェクトの配列取得 -roads = board.roads # Map::Roadオブジェクトの配列取得 - -r = rooms.choice -x, y = r.random_point # あるエリアのランダムな座標を取得 - -board.room?(2, 3) # 指定座標(x, y)が部屋か判定 -board.road?(2, 3) # 指定座標(x, y)が部屋か判定 -board.movable?(2, 3) # 指定座標(x, y)が移動可能か判定 - -# その他、Map::Areaに定義されたメソッドは全て使える - -# RDGC::Util::RandomUtilで定義され、top-levelにinclude済みのメソッド -# 数値は全て整数を指定すること - -bool_rand # trueかfalseを返す -range_rand(min, max) # minからmaxまでのどれかの整数値を返す -select_rand(:a => 3, :b => 2, :c => 1) # :aを3/(3+2+1)、:bを2/(3+2+1)...の確率で返す - -dice(5, 10) # 10面のサイコロを5回振った合計を返す -5.dice(10) # Integer#dice(max)が定義済みで、この場合はdice(5, 10)と同じ -5.d10 # TRPGプレイヤーにおなじみの書き方 - -# その他、細かなメソッドはソースやspec等参照 + require 'rubygems' + require 'rdgc-dm' + + include RDGC::Maker + + board = DivideDungeonMaker.create(30, 40) # width=30, height=40のMap::Boardを作る場合 + board = DivideDungeonMaker.create(30, 40, :min_room_count = 4) # パラメータ指定(4つ以上の部屋数を期待) + + board.each do |x, y| # each で各座標を順に処理 + t = board.tile(x, y) # Tileオブジェクト取得 + case + when t.wall? # 壁 + ... + when t.room? # 部屋 + ... + when t.road? # 道 + ... + end + end + + board.each_tile do |x, y, t| # each_tileで座標とTileを一緒に取得 + ... + end + + rooms = board.rooms # Map::Roomオブジェクトの配列取得 + roads = board.roads # Map::Roadオブジェクトの配列取得 + + r = rooms.choice + x, y = r.random_point # あるエリアのランダムな座標を取得 + + board.room?(2, 3) # 指定座標(x, y)が部屋か判定 + board.road?(2, 3) # 指定座標(x, y)が部屋か判定 + board.movable?(2, 3) # 指定座標(x, y)が移動可能か判定 + + # その他、Map::Areaに定義されたメソッドは全て使える + + # RDGC::Util::RandomUtilで定義され、top-levelにinclude済みのメソッド + # 数値は全て整数を指定すること + + bool_rand # trueかfalseを返す + range_rand(min, max) # minからmaxまでのどれかの整数値を返す + select_rand(:a => 3, :b => 2, :c => 1) # :aを3/(3+2+1)、:bを2/(3+2+1)...の確率で返す + + dice(5, 10) # 10面のサイコロを5回振った合計を返す + 5.dice(10) # Integer#dice(max)が定義済みで、この場合はdice(5, 10)と同じ + 5.d10 # TRPGプレイヤーにおなじみの書き方 + + # その他、細かなメソッドはソースやspec等参照 == Create Parameters -前提として、生成パラメータは努力目標 -できるだけ指定を満たそうとはするが、ランダムなので保証はできない - -まず全体を一つのBlockとして定義し、それを再帰的に分割した後、 -各Blockに部屋か交差点を作るため、Blockとは1:1の関係になる + 前提として、生成パラメータは努力目標 + できるだけ指定を満たそうとはするが、ランダムなので保証はできない + + まず全体を一つのBlockとして定義し、それを再帰的に分割した後、 + 各Blockに部屋か交差点を作るため、Blockとは1:1の関係になる * :min_block_size => 分割Blockの最低サイズ * :max_block_count => Blockの最大生成数 * :min_room_size => 部屋の最低サイズ(デフォルトは4で、4以下は強制的に4) * :max_room_size => 部屋の最大サイズ * :min_room_count => 部屋の最低生成数(デフォルトは2) * :max_room_count => 部屋の最大生成数 * :max_depth => 分割再帰の深さ max_depth=nのとき、Blockの最大数は2^nになる * :cross_road_ratio => 交差点生成率(0 <= x <= 9) == FAQ === パラメータが適用されない -パラメータには適用優先順位があります + パラメータには適用優先順位があります 1. min_block_size 2. max_block_count 3. max_depth 4. min_room_count 5. max_room_count 6. cross_road_ratio 7. max_room_size 8. min_room_size -上位のパラメータに対し、下位のパラメータが矛盾した場合、 -無視はしませんが、保証はされません + 上位のパラメータに対し、下位のパラメータが矛盾した場合、 + 無視はしませんが、保証はされません === max_room_count=1なのに部屋が2個できる -min_room_countのデフォルト値が2なので、 -上記の優先順位に従い、部屋が2個できます -(デフォルトが2個なのは、スタート地点とゴール地点を作るためです) -明示的にmin_room_count=1をあわせて指定すると、一つだけできるはずです + min_room_countのデフォルト値が2なので、 + 上記の優先順位に従い、部屋が2個できます + (デフォルトが2個なのは、スタート地点とゴール地点を作るためです) + 明示的にmin_room_count=1をあわせて指定すると、一つだけできるはずです === 道に(部屋でない)行き止まりができる -仕様です - -それで片付けるのもあれなので補足すると、 -つなげられそうな交差点を、できるだけつなぐようにしているものの、 -周囲にもうBlockがない等、どうしようもない場合に行き止まりができます - -あまりたくさんできると問題ですが、 -たまにあるくらいはゲームとしていいんじゃないかと + 仕様です + + それで片付けるのもあれなので補足すると、 + つなげられそうな交差点を、できるだけつなぐようにしているものの、 + 周囲に残りBlockがない等、どうしようもない場合に行き止まりができます + + あまりたくさんできると問題ですが、 + たまにあるくらいはゲームとしていいんじゃないかと === 最大分割深度(max_depth)って何? -DivideDungeonMakerは最初のBlockを起点にして、再帰的な分割をしようとします - -この分割回数の最大値がmax_depthの指定で、これを小さくすることで、 -小さいBlockだらけになるのを防げます -max_depth=nの時、作られるBlockの最大値は2^nです + DivideDungeonMakerは最初のBlockを起点にして、再帰的な分割をしようとします + + この分割回数の最大値がmax_depthの指定で、これを小さくすることで、 + 小さいBlockだらけになるのを防げます + max_depth=nの時、作られるBlockの最大値は2^nです === イベントやBOSS用に、広い部屋が1つだけ欲しい -min_room_sizeをx/y以上にしたうえで、 -min_block_sizeをx/y以上にするか、max_block_count=1を指定してください -全体が1Blockになり、限界までRoomを大きくしようとします + min_room_sizeをx/y以上にしたうえで、 + min_block_sizeをx/y以上にするか、max_block_count=1を指定してください + 全体が1Blockになり、限界までRoomを大きくしようとします === スタートとゴール(階段)って無いの? -rdgc-dmはあくまで部屋と道(の座標系)を作るための仕組みです -スタートやゴールの概念は各ゲームによって異なるため、 -rdgc-dmには含んでいません(RDGCとしては存在します) - -Area#ramdom_pointで各Areaのランダムな座標が取れますので、 -それを使ってスタートやゴールやモンスターを配置してください + rdgc-dmはあくまで部屋と道(の座標系)を作るための仕組みです + スタートやゴールの概念は各ゲームによって異なるため、 + rdgc-dmには含んでいません(RDGCとしては存在します) + + Area#ramdom_pointで各Areaのランダムな座標が取れますので、 + それを使ってスタートやゴールやモンスターを配置してください === 自分でロジックを書きたい * RDGC::Maker::DungeonMakerをincludeしたクラス * RDGC::Maker::TempBlockを継承したクラス -これらを組み合わせると自分のロジックが書けます -詳しくはDivideDungeonMaker/DivideTempBlockのソースを見てください + これらを組み合わせると自分のロジックが書けます + 詳しくはDivideDungeonMaker/DivideTempBlockのソースを見てください == Copyright Copyright (c) 2010 parrot_studio. See LICENSE for details.
parrot-studio/rdgc-dm
f01db55f46ae51c8d0f0a6b72fb0c47817f7cb96
add gemspec
diff --git a/rdgc-dm.gemspec b/rdgc-dm.gemspec new file mode 100644 index 0000000..3498643 --- /dev/null +++ b/rdgc-dm.gemspec @@ -0,0 +1,92 @@ +# Generated by jeweler +# DO NOT EDIT THIS FILE DIRECTLY +# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command +# -*- encoding: utf-8 -*- + +Gem::Specification.new do |s| + s.name = %q{rdgc-dm} + s.version = "0.1.0" + + s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.authors = ["parrot_studio"] + s.date = %q{2010-04-01} + s.description = %q{ This gem is part of RDGC - Ruby(Random) Dungeon Game Core. + RDGC is core of random dungeon game (like rogue), make dungeon, manage mnsters etc. +} + s.email = %q{[email protected]} + s.extra_rdoc_files = [ + "LICENSE", + "README.rdoc" + ] + s.files = [ + ".document", + ".gitignore", + "LICENSE", + "README.rdoc", + "Rakefile", + "VERSION", + "lib/rdgc-dm.rb", + "lib/rdgc/maker/divide_dungeon_maker.rb", + "lib/rdgc/maker/divide_temp_block.rb", + "lib/rdgc/maker/dungeon_maker.rb", + "lib/rdgc/maker/temp_block.rb", + "lib/rdgc/map/area.rb", + "lib/rdgc/map/block.rb", + "lib/rdgc/map/board.rb", + "lib/rdgc/map/road.rb", + "lib/rdgc/map/room.rb", + "lib/rdgc/map/tile.rb", + "lib/rdgc/map/tile_type.rb", + "lib/rdgc/util/config.rb", + "lib/rdgc/util/random_util.rb", + "spec/rdgc/maker/01_temp_block_spec.rb", + "spec/rdgc/maker/02_divide_temp_block_spec.rb", + "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb", + "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", + "spec/rdgc/map/01_tile_spec.rb", + "spec/rdgc/map/02_area_spec.rb", + "spec/rdgc/map/03_road_spec.rb", + "spec/rdgc/map/04_room_spec.rb", + "spec/rdgc/map/05_block_spec.rb", + "spec/rdgc/map/06_board_spec.rb", + "spec/rdgc/util/01_config_spec.rb", + "spec/rdgc/util/02_random_util_spec.rb", + "spec/spec.opts", + "spec/spec_helper.rb" + ] + s.homepage = %q{http://github.com/parrot-studio/rdgc-dm} + s.rdoc_options = ["--charset=UTF-8"] + s.require_paths = ["lib"] + s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") + s.rubygems_version = %q{1.3.6} + s.summary = %q{Random Dungeon Maker from RDGC} + s.test_files = [ + "spec/spec_helper.rb", + "spec/rdgc/util/02_random_util_spec.rb", + "spec/rdgc/util/01_config_spec.rb", + "spec/rdgc/map/04_room_spec.rb", + "spec/rdgc/map/06_board_spec.rb", + "spec/rdgc/map/01_tile_spec.rb", + "spec/rdgc/map/03_road_spec.rb", + "spec/rdgc/map/05_block_spec.rb", + "spec/rdgc/map/02_area_spec.rb", + "spec/rdgc/maker/02_divide_temp_block_spec.rb", + "spec/rdgc/maker/01_temp_block_spec.rb", + "spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb", + "spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb" + ] + + if s.respond_to? :specification_version then + current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION + s.specification_version = 3 + + if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then + s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) + else + s.add_dependency(%q<rspec>, [">= 1.2.9"]) + end + else + s.add_dependency(%q<rspec>, [">= 1.2.9"]) + end +end +
parrot-studio/rdgc-dm
b34288767c03df43ac2246da38d1555de01ddc8d
0.1.0 RC2
diff --git a/.document b/.document index ecf3673..b485d47 100644 --- a/.document +++ b/.document @@ -1,5 +1,5 @@ -README.rdoc -lib/**/*.rb -bin/* -features/**/*.feature -LICENSE +README.rdoc +lib/**/*.rb +bin/* +features/**/*.feature +LICENSE diff --git a/.gitignore b/.gitignore index c1e0daf..f013ea7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,21 @@ -## MAC OS -.DS_Store - -## TEXTMATE -*.tmproj -tmtags - -## EMACS -*~ -\#* -.\#* - -## VIM -*.swp - -## PROJECT::GENERAL -coverage -rdoc -pkg - -## PROJECT::SPECIFIC +## MAC OS +.DS_Store + +## TEXTMATE +*.tmproj +tmtags + +## EMACS +*~ +\#* +.\#* + +## VIM +*.swp + +## PROJECT::GENERAL +coverage +rdoc +pkg + +## PROJECT::SPECIFIC diff --git a/LICENSE b/LICENSE index 6102e70..de5a8f7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,22 +1,22 @@ -The MIT License - -Copyright (c) 2010 parrot_studio<parrot *at* users.sourceforge.jp> - -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. +The MIT License + +Copyright (c) 2010 parrot_studio<parrot *at* users.sourceforge.jp> + +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/README.rdoc b/README.rdoc index 371a1a6..fac6dbc 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,17 +1,148 @@ -= rdgc-dm - -Description goes here. - -== Note on Patches/Pull Requests - -* Fork the project. -* Make your feature addition or bug fix. -* Add tests for it. This is important so I don't break it in a - future version unintentionally. -* Commit, do not mess with rakefile, version, or history. - (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) -* Send me a pull request. Bonus points for topic branches. - -== Copyright - -Copyright (c) 2010 parrot_studio. See LICENSE for details. += rdgc-dm +Author:: parrot_studio <parrot *at* users.sourceforge.jp> +License:: The MIT License + +* 要求されたサイズのランダムダンジョンを生成 +* ダンジョンは部屋と道で構成される + +== Install + gem install gemcutter # インストール済みなら不要 + gem install rdgc-dm + +== Usage +require 'rubygems' +require 'rdgc-dm' + +include RDGC::Maker + +board = DivideDungeonMaker.create(30, 40) # width=30, height=40のMap::Boardを作る場合 +board = DivideDungeonMaker.create(30, 40, :min_room_count = 4) # パラメータ指定(4つ以上の部屋数を期待) + +board.each do |x, y| # each で各座標を順に処理 + t = board.tile(x, y) # Tileオブジェクト取得 + case + when t.wall? # 壁 + ... + when t.room? # 部屋 + ... + when t.road? # 道 + ... + end +end + +board.each_tile do |x, y, t| # each_tileで座標とTileを一緒に取得 + ... +end + +rooms = board.rooms # Map::Roomオブジェクトの配列取得 +roads = board.roads # Map::Roadオブジェクトの配列取得 + +r = rooms.choice +x, y = r.random_point # あるエリアのランダムな座標を取得 + +board.room?(2, 3) # 指定座標(x, y)が部屋か判定 +board.road?(2, 3) # 指定座標(x, y)が部屋か判定 +board.movable?(2, 3) # 指定座標(x, y)が移動可能か判定 + +# その他、Map::Areaに定義されたメソッドは全て使える + +# RDGC::Util::RandomUtilで定義され、top-levelにinclude済みのメソッド +# 数値は全て整数を指定すること + +bool_rand # trueかfalseを返す +range_rand(min, max) # minからmaxまでのどれかの整数値を返す +select_rand(:a => 3, :b => 2, :c => 1) # :aを3/(3+2+1)、:bを2/(3+2+1)...の確率で返す + +dice(5, 10) # 10面のサイコロを5回振った合計を返す +5.dice(10) # Integer#dice(max)が定義済みで、この場合はdice(5, 10)と同じ +5.d10 # TRPGプレイヤーにおなじみの書き方 + +# その他、細かなメソッドはソースやspec等参照 + +== Create Parameters + +前提として、生成パラメータは努力目標 +できるだけ指定を満たそうとはするが、ランダムなので保証はできない + +まず全体を一つのBlockとして定義し、それを再帰的に分割した後、 +各Blockに部屋か交差点を作るため、Blockとは1:1の関係になる + +* :min_block_size => 分割Blockの最低サイズ +* :max_block_count => Blockの最大生成数 +* :min_room_size => 部屋の最低サイズ(デフォルトは4で、4以下は強制的に4) +* :max_room_size => 部屋の最大サイズ +* :min_room_count => 部屋の最低生成数(デフォルトは2) +* :max_room_count => 部屋の最大生成数 +* :max_depth => 分割再帰の深さ max_depth=nのとき、Blockの最大数は2^nになる +* :cross_road_ratio => 交差点生成率(0 <= x <= 9) + +== FAQ + +=== パラメータが適用されない + +パラメータには適用優先順位があります + +1. min_block_size +2. max_block_count +3. max_depth +4. min_room_count +5. max_room_count +6. cross_road_ratio +7. max_room_size +8. min_room_size + +上位のパラメータに対し、下位のパラメータが矛盾した場合、 +無視はしませんが、保証はされません + +=== max_room_count=1なのに部屋が2個できる + +min_room_countのデフォルト値が2なので、 +上記の優先順位に従い、部屋が2個できます +(デフォルトが2個なのは、スタート地点とゴール地点を作るためです) +明示的にmin_room_count=1をあわせて指定すると、一つだけできるはずです + +=== 道に(部屋でない)行き止まりができる + +仕様です + +それで片付けるのもあれなので補足すると、 +つなげられそうな交差点を、できるだけつなぐようにしているものの、 +周囲にもうBlockがない等、どうしようもない場合に行き止まりができます + +あまりたくさんできると問題ですが、 +たまにあるくらいはゲームとしていいんじゃないかと + +=== 最大分割深度(max_depth)って何? + +DivideDungeonMakerは最初のBlockを起点にして、再帰的な分割をしようとします + +この分割回数の最大値がmax_depthの指定で、これを小さくすることで、 +小さいBlockだらけになるのを防げます +max_depth=nの時、作られるBlockの最大値は2^nです + +=== イベントやBOSS用に、広い部屋が1つだけ欲しい + +min_room_sizeをx/y以上にしたうえで、 +min_block_sizeをx/y以上にするか、max_block_count=1を指定してください +全体が1Blockになり、限界までRoomを大きくしようとします + +=== スタートとゴール(階段)って無いの? + +rdgc-dmはあくまで部屋と道(の座標系)を作るための仕組みです +スタートやゴールの概念は各ゲームによって異なるため、 +rdgc-dmには含んでいません(RDGCとしては存在します) + +Area#ramdom_pointで各Areaのランダムな座標が取れますので、 +それを使ってスタートやゴールやモンスターを配置してください + +=== 自分でロジックを書きたい + +* RDGC::Maker::DungeonMakerをincludeしたクラス +* RDGC::Maker::TempBlockを継承したクラス + +これらを組み合わせると自分のロジックが書けます +詳しくはDivideDungeonMaker/DivideTempBlockのソースを見てください + +== Copyright + +Copyright (c) 2010 parrot_studio. See LICENSE for details. diff --git a/Rakefile b/Rakefile index ca866d7..e9b37ad 100644 --- a/Rakefile +++ b/Rakefile @@ -1,45 +1,49 @@ -require 'rubygems' -require 'rake' - -begin - require 'jeweler' - Jeweler::Tasks.new do |gem| - gem.name = "rdgc-dm" - gem.summary = %Q{TODO: one-line summary of your gem} - gem.description = %Q{TODO: longer description of your gem} - gem.email = "[email protected]" - gem.homepage = "http://github.com/parrot-studio/rdgc-dm" - gem.authors = ["parrot_studio"] - gem.add_development_dependency "rspec", ">= 1.2.9" - # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings - end - Jeweler::GemcutterTasks.new -rescue LoadError - puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" -end - -require 'spec/rake/spectask' -Spec::Rake::SpecTask.new(:spec) do |spec| - spec.libs << 'lib' << 'spec' - spec.spec_files = FileList['spec/**/*_spec.rb'] -end - -Spec::Rake::SpecTask.new(:rcov) do |spec| - spec.libs << 'lib' << 'spec' - spec.pattern = 'spec/**/*_spec.rb' - spec.rcov = true -end - -task :spec => :check_dependencies - -task :default => :spec - -require 'rake/rdoctask' -Rake::RDocTask.new do |rdoc| - version = File.exist?('VERSION') ? File.read('VERSION') : "" - - rdoc.rdoc_dir = 'rdoc' - rdoc.title = "rdgc-dm #{version}" - rdoc.rdoc_files.include('README*') - rdoc.rdoc_files.include('lib/**/*.rb') -end +require 'rubygems' +require 'rake' + +begin + require 'jeweler' + Jeweler::Tasks.new do |gem| + gem.name = "rdgc-dm" + gem.summary = %Q{Random Dungeon Maker from RDGC} + gem.description = <<-TXT + This gem is part of RDGC - Ruby(Random) Dungeon Game Core. + RDGC is core of random dungeon game (like rogue), make dungeon, manage mnsters etc. + TXT + gem.email = "[email protected]" + gem.homepage = "http://github.com/parrot-studio/rdgc-dm" + gem.authors = ["parrot_studio"] + gem.required_ruby_version = ">= 1.8.7" + gem.add_development_dependency "rspec", ">= 1.2.9" + # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings + end + Jeweler::GemcutterTasks.new +rescue LoadError + puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" +end + +require 'spec/rake/spectask' +Spec::Rake::SpecTask.new(:spec) do |spec| + spec.libs << 'lib' << 'spec' + spec.spec_files = FileList['spec/**/*_spec.rb'] +end + +Spec::Rake::SpecTask.new(:rcov) do |spec| + spec.libs << 'lib' << 'spec' + spec.pattern = 'spec/**/*_spec.rb' + spec.rcov = true +end + +task :spec => :check_dependencies + +task :default => :spec + +require 'rake/rdoctask' +Rake::RDocTask.new do |rdoc| + version = File.exist?('VERSION') ? File.read('VERSION') : "" + + rdoc.rdoc_dir = 'rdoc' + rdoc.title = "rdgc-dm #{version}" + rdoc.rdoc_files.include('README*') + rdoc.rdoc_files.include('lib/**/*.rb') +end diff --git a/VERSION b/VERSION index 6e8bf73..7ecf123 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.0 +0.1.0 diff --git a/spec/rdgc-dm_spec.rb b/spec/rdgc-dm_spec.rb deleted file mode 100644 index 0e3c155..0000000 --- a/spec/rdgc-dm_spec.rb +++ /dev/null @@ -1,7 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/spec_helper') - -describe "RdgcDm" do - it "fails" do - fail "hey buddy, you should probably rename this file and start specing for real" - end -end diff --git a/spec/spec.opts b/spec/spec.opts index 4e1e0d2..bc1b37b 100644 --- a/spec/spec.opts +++ b/spec/spec.opts @@ -1 +1 @@ ---color +--color diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index d4a4775..dd0ec27 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,11 +1,11 @@ -$LOAD_PATH.unshift(File.dirname(__FILE__)) -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) -require 'rdgc-dm' -require 'spec' -require 'spec/autorun' - -include RDGC - -Spec::Runner.configure do |config| - -end +$LOAD_PATH.unshift(File.dirname(__FILE__)) +$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) +require 'rdgc-dm' +require 'spec' +require 'spec/autorun' + +include RDGC + +Spec::Runner.configure do |config| + +end
parrot-studio/rdgc-dm
6a71c4b7253198c7845c16dd0f251fbc85d40700
0.1.0 RC (doc yet)
diff --git a/LICENSE b/LICENSE index dcfeb33..6102e70 100644 --- a/LICENSE +++ b/LICENSE @@ -1,20 +1,22 @@ -Copyright (c) 2009 parrot_studio +The MIT License + +Copyright (c) 2010 parrot_studio<parrot *at* users.sourceforge.jp> 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/lib/rdgc-dm.rb b/lib/rdgc-dm.rb index e69de29..1a3a071 100644 --- a/lib/rdgc-dm.rb +++ b/lib/rdgc-dm.rb @@ -0,0 +1,17 @@ +# coding: UTF-8 +require 'rdgc/util/config' +require 'rdgc/util/random_util' +include RDGC::Util::RandomUtil + +require 'rdgc/map/tile' +require 'rdgc/map/tile_type' +require 'rdgc/map/area' +require 'rdgc/map/block' +require 'rdgc/map/room' +require 'rdgc/map/road' +require 'rdgc/map/board' + +require 'rdgc/maker/temp_block' +require 'rdgc/maker/dungeon_maker' +require 'rdgc/maker/divide_temp_block' +require 'rdgc/maker/divide_dungeon_maker' diff --git a/lib/rdgc/maker/divide_dungeon_maker.rb b/lib/rdgc/maker/divide_dungeon_maker.rb new file mode 100644 index 0000000..db643b1 --- /dev/null +++ b/lib/rdgc/maker/divide_dungeon_maker.rb @@ -0,0 +1,371 @@ +# coding: UTF-8 +module RDGC + module Maker + class DivideDungeonMaker + include DungeonMaker + + def self.create(width, height, params = nil) + dm = self.new + list = dm.make(width, height, params) + Map::Board.create_from_blocks(list) + end + + DEFAULT_CROSS_ROAD_RATIO = 2 + + # override + def create_whole_block(width, height) + tb = DivideTempBlock.create_whole_block(width, height) + tb.min_size = min_block_size + tb.dividable + tb + end + + def make_blocks(tb) + # 分割キューに最初のBlockを入れる + divide_queue << tb + + # 再帰分割 + divide + + # 完了キューの中身を返す + done_queue + end + + # override + def create_room + # 部屋と交差点を分ける + room_blocks = [] + cross_blocks = [] + force_room_blocks = [] + + param = { + :room => (10 - cross_road_ratio), + :cross => cross_road_ratio + } + + blocks.each do |b| + # 初回分割のBlockは行き止まりになるので避ける + if b.depth < 2 + force_room_blocks << b + next + end + + r = select_rand(param) + case r + when :room + room_blocks << b + when :cross + cross_blocks << b + end + end + + room_count = room_blocks.size + force_room_blocks.size + if max_room_count > 0 && room_count > max_room_count + # 超えた分だけ移動する + (room_count - max_room_count).times do + break if room_blocks.size + force_room_blocks.size <= 1 + break if room_blocks.empty? + b = room_blocks.pickup! + cross_blocks << b if b + end + end + + room_count = room_blocks.size + force_room_blocks.size + if room_count < min_room_count + # 足りない分を移動する + (min_room_count - room_count).times do + break if cross_blocks.empty? + b = cross_blocks.pickup! + room_blocks << b if b + end + end + + # それぞれのblockを処理 + [room_blocks, force_room_blocks].flatten.each do |b| + b.create_room(:min => min_room_size, :max => max_room_size) + end + cross_blocks.each{|b| b.create_cross_point} + end + + # override + def create_road + return if blocks.size <= 1 + + # 再帰的に道を作成 + recursive_road_create(blocks.choice) + + # 道がない部屋で、既存と接しているところを処理 + connect_cling_block_has_road + + # 道がなく、孤立した部屋を移動 + move_room_and_connect + + # 行き止まりの交差点を処理 + add_road_for_dead_end + end + + # ------------------------------------------------------------- + + def min_block_size + unless @min_block_size + val = params[:min_block_size] + if val + # 指定がある場合はそれを評価 + val = val.to_i + else + # 指定が無く、min_room_sizeが存在するならそちらに合わせる + val = (min_room_size ? min_room_size + 3 : 0) + end + val = Util::Config.min_block_size if val < Util::Config.min_block_size + @min_block_size = val + end + @min_block_size + end + + def min_room_size + params[:min_room_size] + end + + def max_room_size + params[:max_room_size] + end + + def max_block_count + params[:max_block_count].to_i + end + + def min_room_count + unless @min_room_count + val = params[:min_room_count].to_i + # 明示的に「1」という指定がない限り2部屋は作る + val = 2 if val <= 0 + @min_room_count = val + end + @min_room_count + end + + def max_room_count + params[:max_room_count].to_i + end + + def max_depth + params[:max_depth].to_i + end + + def cross_road_ratio + unless @cross_road_ratio + val = params[:cross_road_ratio] + if val + val = val.to_i + # 交差点生成率は 1<=x<=9 / 10 + val = DEFAULT_CROSS_ROAD_RATIO if (val < 0 || val > 9) + else + # 指定なし => デフォルト + val = DEFAULT_CROSS_ROAD_RATIO + end + @cross_road_ratio = val + end + @cross_road_ratio + end + + def divide_queue + @divide_queue ||= [] + @divide_queue + end + + def done_queue + @done_queue ||= [] + @done_queue + end + + def queue_size + divide_queue.size + done_queue.size + end + + def finish? + return true if divide_queue.empty? + return true if (max_block_count > 0 && queue_size >= max_block_count) + false + end + + def dividable_block?(b) + # そもそも分割対象ではない => false + return false unless b.dividable? + + # 最大深度の指定がない => true + return true if max_depth <= 0 + + # 最大深度に達したら分割しない + b.depth >= max_depth ? false : true + end + + def divide + # 再帰処理 + loop do + break if finish? + + tb = divide_queue.shift + break unless tb + + list = tb.divide + unless list + # 分割できなかったので、元をdone_queueへ + done_queue << tb + break + end + + list.each do |b| + if dividable_block?(b) + divide_queue << b + else + done_queue << b + end + end + end + + # queueをまとめる + divide_queue.each{|b| done_queue << b} + end + + # ------------------------------------------------------------- + + def recursive_road_create(target) + # 全部道がつながったら終了 + return if blocks.all?{|b| b.has_road?} + + # まだ道の処理をしてない、接しているblockを探す + yet_block = blocks.reject{|b| b.road_created?} + cling_list = create_cling_list(target, yet_block) + + # 行き止まり => 終了 + return if cling_list.size <= 0 + + # 接しているblockに道を作る + next_block = connect_cling_blocks(target, cling_list) + + # 作成完了 + target.road_created + + # 次を再帰的呼び出し + recursive_road_create(next_block) + end + + def connect_cling_block_has_road + # 道がない部屋を探す + remains = blocks.select{|b| b.has_room? && ! b.has_road?} + return if remains.empty? + + # すでに完了しているblockの数を確認 + done_count = blocks.select{|b| b.has_room? && b.has_road?}.size + + remains.each do |target| + # min_room_countを満たすならランダム + if done_count >= min_room_count + next unless bool_rand + end + + # 接しているblockに道があるならつなぐ + c_list = create_cling_list(target, blocks.select{|b| b.has_road?}).flatten + return if c_list.empty? + target.create_road_to(c_list.pickup!) + c_list.each{|b| target.add_remain_cling_blocks(b)} + + done_count += 1 + end + end + + def move_room_and_connect + # 完了してしたblockの数を確認し、min_room_countを満たしていたら終わり + done_count = blocks.select{|b| b.has_room? && b.has_road?}.size + return if done_count >= min_room_count + + # まだ道がない部屋を探す + remains = blocks.select{|b| b.has_room? && ! b.has_road?} + return if remains.empty? + + remains.each do |target| + # 元の部屋等の削除 + target.remove_all + + # 改めて部屋を作る先を決める + enable_blocks = blocks.select{|b| b.has_remain_cling_blocks?} + next if enable_blocks.empty? + + org_block = enable_blocks.choice + room_block = org_block.remain_cling_blocks.pickup! + + # 部屋作成 + room_block.create_room(:min => min_room_size, :max => max_room_size) + + # 接続 + room_block.create_road_to(org_block) + end + end + + def create_cling_list(block, list) + top_list = collect_cling_block(block, list,:top) + bottom_list = collect_cling_block(block, list, :bottom) + left_list = collect_cling_block(block, list, :left) + right_list = collect_cling_block(block, list, :right) + + [top_list, bottom_list, left_list, right_list].select{|a| a.size > 0} + end + + def collect_cling_block(block, list, direction) + case direction + when :top + list.select{|b| block.cling_to_top?(b)} + when :bottom + list.select{|b| block.cling_to_bottom?(b)} + when :left + list.select{|b| block.cling_to_left?(b)} + when :right + list.select{|b| block.cling_to_right?(b)} + end + end + + def connect_cling_blocks(target, cling_list) + return unless cling_list + return if cling_list.size <= 0 + + # 4方向で選択可能なblock配列から一つ選ぶ + direction_list = cling_list.pickup! + next_block = direction_list.pickup! + + # ブロックに道をつなぐ + target.create_road_to(next_block) + + # その方向の残りを接しているblockとして記録 + direction_list.each{|b| target.add_remain_cling_blocks(b)} + + # 残りの方向もランダムにつなぐ + cling_list.each do |d_list| + bl = d_list.pickup! if bool_rand + target.create_road_to(bl) if bl + d_list.each{|b| target.add_remain_cling_blocks(b)} + end + + # 次の対象返却 + next_block + end + + def add_road_for_dead_end + deadends = blocks.select{|b| b.dead_end?} + return if deadends.empty? + + deadends.each do |target| + # まだ作成していない方向に何か接しているか? + c_list = [] + block_list = blocks.select{|b| b.has_road?} + target.remain_direction.each do |d| + ret = collect_cling_block(target, block_list, d) + c_list += ret.flatten + end + next if c_list.empty? + target.create_road_to(c_list.pickup!) + end + end + + end + end +end diff --git a/lib/rdgc/maker/divide_temp_block.rb b/lib/rdgc/maker/divide_temp_block.rb new file mode 100644 index 0000000..9edb78c --- /dev/null +++ b/lib/rdgc/maker/divide_temp_block.rb @@ -0,0 +1,269 @@ +# coding: UTF-8 +module RDGC + module Maker + class DivideTempBlock < TempBlock + + attr_accessor :divide_direction + attr_writer :depth, :min_size + + def depth + @depth ||= 0 + @depth + end + + def min_size + @min_size = Util::Config.min_block_size if @min_size.to_i < Util::Config.min_block_size + @min_size + end + + def min_divide_size + min_size * 2 + end + + def opposite_direction + case self.divide_direction + when :horizontal + :vertical + when :vertical + :horizontal + else + nil + end + end + + def dividable_size? + case self.divide_direction + when :horizontal + height >= min_divide_size ? true : false + when :vertical + width >= min_divide_size ? true : false + else + false + end + end + + def dividable(f = true) + @dividable = f + end + + def dividable? + @dividable + end + + def set_dividable + return unless dividable_size? + dividable + end + + def divide_point(val) + range_rand(min_size, val - min_divide_size) + end + + def divide + self.divide_direction ||= select_rand({:horizontal => 1, :vertical => 1}) + return unless dividable_size? + + case self.divide_direction + when :horizontal + divide_horizontal + when :vertical + divide_vertical + end + end + + def divide_horizontal + return unless dividable_size? + + # 分割幅決定 + point = divide_point(height) + + upper = DivideTempBlock.create(top, top + point - 1, left, right) + lower = DivideTempBlock.create(top + point, bottom, left, right) + + set_next_value(upper, lower) + [upper, lower].shuffle + end + + def divide_vertical + return unless dividable_size? + + # 分割点決定 + point = divide_point(width) + + lefter = DivideTempBlock.create(top, bottom, left, left + point - 1) + righter = DivideTempBlock.create(top, bottom, left + point, right) + + set_next_value(lefter, righter) + [lefter, righter].shuffle + end + + def set_next_value(b1, b2) + [b1, b2].each do |b| + b.depth = self.depth + 1 + b.divide_direction = opposite_direction + b.min_size = min_size + end + + if bool_rand + b1.set_dividable + b2.set_dividable if bool_rand + else + b2.set_dividable + b1.set_dividable if bool_rand + end + end + + # for road ---------------------------------------------------- + + def road_created(f = true) + @road_created = f + self + end + + def road_created? + @road_created + end + + def set_road_point(direction, point) + @road_point ||= {} + @road_point[direction] = point + end + + def road_point + @road_point ||= {} + @road_point + end + + def remain_cling_blocks + @remain_cling_blocks ||= [] + @remain_cling_blocks + end + + def add_remain_cling_blocks(b) + return if b.has_room? + remain_cling_blocks << b + end + + def has_remain_cling_blocks? + remain_cling_blocks.empty? ? false : true + end + + def dead_end? + return false if has_room? + return false unless has_cross_point? + road_point.keys.size == 1 ? true : false + end + + def remain_direction + [:top, :bottom, :left, :right] - road_point.keys + end + + def create_road_to(b) + return unless (has_room? || has_cross_point?) + return unless (b.has_room? || b.has_cross_point?) + + # 相手とどこで接しているか調べる + # 接線に向かって道を伸ばす + # 左か上に位置する部屋に接続線を引く + case cling_direction_to(b) + when :top + my_x = create_road_for_direction(:top) + b_x = b.create_road_for_direction(:bottom) + b.create_road_for_adjoin_x(my_x, b_x) + when :bottom + my_x = create_road_for_direction(:bottom) + b_x = b.create_road_for_direction(:top) + create_road_for_adjoin_x(my_x, b_x) + when :left + my_y = create_road_for_direction(:left) + b_y = b.create_road_for_direction(:right) + b.create_road_for_adjoin_y(my_y, b_y) + when :right + my_y = create_road_for_direction(:right) + b_y = b.create_road_for_direction(:left) + create_road_for_adjoin_y(my_y, b_y) + end + end + + def create_road_for_direction(d) + # 道を描くポイントを持っている(すでに道がある)ならそれを返す + val = road_point[d] + return val if val + + # 新しい道を描く + case + when has_room? + val = create_road_from_room(d) + when has_cross_point? + val = create_road_from_point(d) + end + + val + end + + def create_road_from_room(d) + return unless has_room? + return if road_point[d] + + case d + when :top + x = range_rand(room.left, room.right) + set_road_point(:top, x) + add_road(Map::Road.create(top, room.top-1, x, x)) + x + when :bottom + x = range_rand(room.left, room.right) + set_road_point(:bottom, x) + add_road(Map::Road.create(room.bottom+1, bottom, x, x)) + x + when :left + y = range_rand(room.top, room.bottom) + set_road_point(:left, y) + add_road(Map::Road.create(y, y, left, room.left-1)) + y + when :right + y = range_rand(room.top, room.bottom) + set_road_point(:right, y) + add_road(Map::Road.create(y, y, room.right+1, right)) + y + end + end + + def create_road_from_point(d) + return unless has_cross_point? + return if road_point[d] + + x, y = cross_point + case d + when :top + set_road_point(:top, x) + add_road(Map::Road.create(top, y, x, x)) + x + when :bottom + set_road_point(:bottom, x) + add_road(Map::Road.create(y, bottom, x, x)) + x + when :left + set_road_point(:left, y) + add_road(Map::Road.create(y, y, left, x)) + y + when :right + set_road_point(:right, y) + add_road(Map::Road.create(y, y, x, right)) + y + end + end + + def create_road_for_adjoin_x(x1, x2) + p_s, p_e = [x1, x2].sort + add_road(Map::Road.create(bottom, bottom, p_s, p_e)) + end + + def create_road_for_adjoin_y(y1, y2) + p_s, p_e = [y1, y2].sort + add_road(Map::Road.create(p_s, p_e, right, right)) + end + + end + end +end diff --git a/lib/rdgc/maker/dungeon_maker.rb b/lib/rdgc/maker/dungeon_maker.rb new file mode 100644 index 0000000..0ca54c5 --- /dev/null +++ b/lib/rdgc/maker/dungeon_maker.rb @@ -0,0 +1,57 @@ +# coding: UTF-8 +module RDGC + module Maker + module DungeonMaker + + def make(width, height, params = nil) + @params = params + tb = create_whole_block(width, height) + @blocks = make_blocks(tb) + @blocks.freeze + create_room + create_road + clear_block + create_pure_blocks + end + + def params + @params ||= {} + @params + end + + def blocks + @blocks ||= [] + @blocks + end + + def create_whole_block(width, height) + end + + def make_blocks(tb) + end + + def create_room + end + + def create_road + end + + def clear_block + return if blocks.size <= 1 + blocks.each do |b| + next if b.has_road? + b.remove_all + end + end + + def create_pure_blocks + blocks.inject([]) do |l, b| + pb = b.create_pure_block + l << pb if pb + l + end + end + + end + end +end diff --git a/lib/rdgc/maker/temp_block.rb b/lib/rdgc/maker/temp_block.rb new file mode 100644 index 0000000..94f8ed6 --- /dev/null +++ b/lib/rdgc/maker/temp_block.rb @@ -0,0 +1,23 @@ +# coding: UTF-8 +module RDGC + module Maker + class TempBlock < Map::Block + + def self.create_whole_block(width, height) + left = 0 + right = width - 1 + top = 0 + bottom = height - 1 + self.create(top, bottom, left, right) + end + + def create_pure_block + b = Map::Block.create(self.top, self.bottom, self.left, self.right) + b.room = self.room if self.has_room? + self.roads.each{|r| b.add_road(r) if r} + b.empty? ? nil : b + end + + end + end +end \ No newline at end of file diff --git a/lib/rdgc/map/area.rb b/lib/rdgc/map/area.rb new file mode 100644 index 0000000..7f083f9 --- /dev/null +++ b/lib/rdgc/map/area.rb @@ -0,0 +1,103 @@ +# coding: UTF-8 +module RDGC + module Map + class Area + include TileType + + attr_accessor :top, :bottom, :left, :right + + def self.create(top, bottom, left, right) + b = self.new + b.top = top + b.bottom = bottom + b.left = left + b.right = right + b + end + + def coordinates + "t:#{top} b:#{bottom} l:#{left} r:#{right} / w:#{width} h:#{height}" + end + + alias :to_co :coordinates + + def height + bottom - top + 1 + end + + def width + right - left + 1 + end + + def has_xy?(x, y) + return false if x < left + return false if x > right + return false if y < top + return false if y > bottom + true + end + + def random_point + [range_rand(left, right), range_rand(top, bottom)] + end + + def each + return to_enum(:each) unless block_given? + each_x do |x| + each_y do |y| + yield(x, y) + end + end + end + + def each_x + return to_enum(:each_x) unless block_given? + (left..right).each do |x| + yield(x) + end + end + + def each_y + return to_enum(:each_y) unless block_given? + (top..bottom).each do |y| + yield(y) + end + end + + def each_tile + return to_enum(:each_tile) unless block_given? + each do |x, y| + yield(x, y, tile(x, y)) + end + end + + def fill + # need override + end + + def fill_tile(tile) + each do |x, y| + set_tile(x, y, tile) + end + end + + def set_tile(x, y, tile) + return unless has_xy?(x, y) + tile_data[x][y] = tile + end + + def tile(x, y) + return unless has_xy?(x, y) + tile_data[x][y] + end + + private + + def tile_data + @tile_data ||= Hash.new{|hash, key| hash[key] = {}} + @tile_data + end + + end + end +end \ No newline at end of file diff --git a/lib/rdgc/map/block.rb b/lib/rdgc/map/block.rb new file mode 100644 index 0000000..9adca17 --- /dev/null +++ b/lib/rdgc/map/block.rb @@ -0,0 +1,155 @@ +# coding: UTF-8 +module RDGC + module Map + class Block < Area + + def self.create(top, bottom, left, right) + # fillはしない + super(top, bottom, left, right) + end + + def fill + # 初期化 + fill_tile TileType::WALL + + fill_room + fill_roads + end + + def fill_room + return unless has_room? + room.each_tile do |x, y, t| + set_tile(x, y, t) + end + end + + def fill_roads + return unless has_road? + roads.each do |r| + r.each_tile do |x, y, t| + set_tile(x, y, t) + end + end + end + + def room + @room + end + + def room=(r) + @room = r + end + + def remove_room + @room = nil + end + + def has_room? + @room ? true : false + end + + def create_room(opt = nil) + @room = Room.create_from_block(self, opt) + @room + end + + def roads + @roads ||= [] + @roads + end + + def add_road(road) + @roads ||= [] + @roads << road + end + + def remove_roads + @roads = [] + end + + def has_road? + roads.empty? ? false : true + end + + def cross_point + @cross_point + end + + def remove_cross_point + @cross_point = nil + end + + def has_cross_point? + @cross_point ? true : false + end + + def create_cross_point + # 右と下は接線を引くので余計に空ける + x_min = self.left + 1 + x_max = self.right - 2 + y_min = self.top + 1 + y_max = self.bottom - 2 + + x = range_rand(x_min, x_max) + y = range_rand(y_min, y_max) + + @cross_point = [x, y] + @cross_point + end + + def remove_all + remove_room + remove_roads + remove_cross_point + end + + def empty? + return false if has_room? + return false if has_road? + true + end + + def cling_to_top?(b) + return false unless top == b.bottom+1 + return false if left > b.right + return false if right < b.left + true + end + + def cling_to_bottom?(b) + return false unless bottom == b.top-1 + return false if left > b.right + return false if right < b.left + true + end + + def cling_to_left?(b) + return false unless left == b.right+1 + return false if top > b.bottom + return false if bottom < b.top + true + end + + def cling_to_right?(b) + return false unless right == b.left-1 + return false if top > b.bottom + return false if bottom < b.top + true + end + + def cling_direction_to(b) + case + when cling_to_top?(b) + :top + when cling_to_bottom?(b) + :bottom + when cling_to_left?(b) + :left + when cling_to_right?(b) + :right + end + end + + end + end +end diff --git a/lib/rdgc/map/board.rb b/lib/rdgc/map/board.rb new file mode 100644 index 0000000..73ac6fd --- /dev/null +++ b/lib/rdgc/map/board.rb @@ -0,0 +1,81 @@ +# coding: UTF-8 +module RDGC + module Map + class Board < Area + + def self.create_from_blocks(blocks) + d = self.new + d.init(blocks) + d + end + + def init(list) + return unless list + return if list.empty? + + @blocks = list + @rooms = blocks.map(&:room).compact + @roads = blocks.map(&:roads).flatten.compact + + set_coordinates + fill + end + + def set_coordinates + return unless blocks + self.top = blocks.map(&:top).min + self.bottom = blocks.map(&:bottom).max + self.left = blocks.map(&:left).min + self.right = blocks.map(&:right).max + end + + def fill + # 初期化 + fill_tile TileType::WALL + + rooms.each do |r| + r.each_tile do |x, y, t| + set_tile(x, y, t) + end + end + + roads.each do |r| + r.each_tile do |x, y, t| + set_tile(x, y, t) + end + end + end + + def blocks + @blocks ||= [] + @blocks + end + + def rooms + @rooms ||= [] + @rooms + end + + def roads + @roads ||= [] + @roads + end + + def movable?(x, y) + return false unless has_xy?(x, y) + tile(x, y).movable? + end + + def room?(x, y) + return false unless has_xy?(x, y) + tile(x, y).room? + end + + def road?(x, y) + return false unless has_xy?(x, y) + tile(x, y).road? + end + + end + end +end diff --git a/lib/rdgc/map/road.rb b/lib/rdgc/map/road.rb new file mode 100644 index 0000000..c37e463 --- /dev/null +++ b/lib/rdgc/map/road.rb @@ -0,0 +1,18 @@ +# coding: UTF-8 +module RDGC + module Map + class Road < Area + + def self.create(top, bottom, left, right) + road = super(top, bottom, left, right) + road.fill + road + end + + def fill + fill_tile TileType::ROAD + end + + end + end +end diff --git a/lib/rdgc/map/room.rb b/lib/rdgc/map/room.rb new file mode 100644 index 0000000..d806203 --- /dev/null +++ b/lib/rdgc/map/room.rb @@ -0,0 +1,69 @@ +# coding: UTF-8 +module RDGC + module Map + class Room < Area + + def self.create(top, bottom, left, right) + room = super(top, bottom, left, right) + room.fill + room + end + + def self.create_from_block(b, opt = nil) + room_w = room_size(b.width, opt) + room_h = room_size(b.height, opt) + return if (room_w <= 0 || room_h <= 0) + + l_point = b.left+1 + room_point(b.width, room_w) + t_point = b.top+1 + room_point(b.height, room_h) + + self.create(t_point, t_point + room_h - 1, l_point, l_point + room_w - 1) + end + + def fill + fill_tile TileType::ROOM + end + + private + + def self.room_size(val, opt = nil) + opt ||= {} + + # 部屋の最大サイズ = ブロックサイズ-壁1*2-通路1 + base = val - 3 + return 0 if base < Util::Config.min_room_size + + # 最小値・最大値判定 + min = min_size(base, opt[:min]) + max = max_size(base, opt[:max]) + min = max if min > max + + range_rand(min, max) + end + + def self.min_size(base, min) + min_room_size = Util::Config.min_room_size + + return min_room_size unless min + min = min.to_i + return base if base < min + return min_room_size if min < min_room_size + min + end + + def self.max_size(base, max) + return base unless max + max = max.to_i + return base if max > base + return Util::Config.min_room_size if max < Util::Config.min_room_size + max + end + + def self.room_point(block_size, room_size) + # 右と下は余分に空ける => 結ぶ通路は左と上が担当 + range_rand(0, block_size - 3 - room_size) + end + + end + end +end diff --git a/lib/rdgc/map/tile.rb b/lib/rdgc/map/tile.rb new file mode 100644 index 0000000..69fb4c5 --- /dev/null +++ b/lib/rdgc/map/tile.rb @@ -0,0 +1,35 @@ +# coding: UTF-8 +module RDGC + module Map + class Tile + + def initialize(type) + @type = type + @type.freeze + end + + def movable? + return false if out? + return false if wall? + true + end + + def out? + @type == :out ? true : false + end + + def wall? + @type == :wall ? true : false + end + + def room? + @type == :room ? true : false + end + + def road? + @type == :road ? true : false + end + + end + end +end diff --git a/lib/rdgc/map/tile_type.rb b/lib/rdgc/map/tile_type.rb new file mode 100644 index 0000000..3f318f9 --- /dev/null +++ b/lib/rdgc/map/tile_type.rb @@ -0,0 +1,11 @@ +# coding: UTF-8 +module RDGC + module Map + module TileType + OUT = Tile.new(:out).freeze + WALL = Tile.new(:wall).freeze + ROOM = Tile.new(:room).freeze + ROAD = Tile.new(:road).freeze + end + end +end diff --git a/lib/rdgc/util/config.rb b/lib/rdgc/util/config.rb new file mode 100644 index 0000000..1fece00 --- /dev/null +++ b/lib/rdgc/util/config.rb @@ -0,0 +1,74 @@ +# coding: UTF-8 +module RDGC + module Util + class Config + + DEFAULT_CONFIG = { + :min_room_size => 4, + :act_max_count => 200 + } + + self.class.class_eval do + @config_hash = DEFAULT_CONFIG + end + + def self.set(hash) + return if seted? + + default = nil + self.class.class_eval do + default = @config_hash + end + + hash = default.merge(hash) + + self.class.class_eval do + @config_hash = hash + @seted = true + end + + true + end + + def self.min_room_size + self.get(:min_room_size) + end + + def self.min_block_size + # デフォルトのblock最小値 = 最小部屋サイズ+上下空き2+接線通路分1 + self.min_room_size + 3 + end + + def self.act_max_count + self.get(:act_max_count) + end + + def self.seted? + ret = false + self.class.class_eval do + ret = @seted + end + ret + end + + def self.get(key) + val = nil + self.class.class_eval do + val = @config_hash[key] + end + val + end + + def self.reset! + self.class.class_eval do + @config_hash = DEFAULT_CONFIG + @seted = false + end + + true + end + + end + end +end + diff --git a/lib/rdgc/util/random_util.rb b/lib/rdgc/util/random_util.rb new file mode 100644 index 0000000..4f9a4c7 --- /dev/null +++ b/lib/rdgc/util/random_util.rb @@ -0,0 +1,104 @@ +# coding: UTF-8 +module RDGC + module Util + module RandomUtil + + def bool_rand + case rand(2) + when 1 + true + when 0 + false + end + end + + def range_rand(s_val, e_val) + return s_val if e_val <= s_val + s_val + rand((e_val - s_val)+1) + end + + def select_rand(hash) + return unless hash + return if hash.empty? + + range_list = [] + count = 0 + hash.each do |k, v| + range = count...(count + v) + range_list << [range, k] + count += v + end + return if count <= 0 + + val = rand(count) + + ret = nil + range_list.each do |r| + if r.first.include?(val) + ret = r.last + break + end + end + + ret + end + + def dice(n, max) + ret = 0 + n.times{ret += range_rand(1, max)} + ret + end + + module_function :bool_rand, :range_rand, :select_rand, :dice + + end + end +end + +class Integer + + def dice(max) + RDGC::Util::RandomUtil.dice(self, max) + end + alias :d :dice + + def method_missing(name, *args) + try_define_dice(name, args) ? (__send__ name) : super + end + + def d4 + self.dice(4) + end + + def d6 + self.dice(6) + end + + def d10 + self.dice(10) + end + + private + + def try_define_dice(name, args) + return false if args.size > 0 + + m = name.to_s.match(/^[d|D](\d+)$/) + return false unless m + return false if m[1].to_i <= 0 + + self.class.module_eval("def #{name};self.dice(#{m[1]});end") + true + end + +end + +class Array + + def pickup! + ret = self.choice + self.delete(ret) + ret + end + +end diff --git a/spec/rdgc/maker/01_temp_block_spec.rb b/spec/rdgc/maker/01_temp_block_spec.rb new file mode 100644 index 0000000..90114b2 --- /dev/null +++ b/spec/rdgc/maker/01_temp_block_spec.rb @@ -0,0 +1,45 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map +include RDGC::Maker + +describe RDGC::Maker::TempBlock, 'is temp Block for Dungeon make' do + + it "create_whole_block will create from width/height" do + tb = TempBlock.create_whole_block(20, 30) + tb.should be_an_instance_of(TempBlock) + tb.width.should == 20 + tb.height.should == 30 + tb.top.should == 0 + tb.bottom.should == 29 + tb.left.should == 0 + tb.right.should == 19 + end + + it "#create_pure_block provides a pure Block instance from self" do + tb = TempBlock.create(0, 20, 0, 20) + + room = Room.create(5, 15, 5, 15) + road1 = Road.create(0, 4, 10, 10) + road2 = Road.create(16, 20, 12, 12) + + tb.room = room + tb.roads << road1 + tb.roads << road2 + + b = tb.create_pure_block + b.should be_an_instance_of(Block) + b.should_not be_an_instance_of(TempBlock) + b.room.should == room + b.roads.should be_include(road1) + b.roads.should be_include(road2) + end + + it "#create_pure_block will return nil, if has no room and no road" do + tb = TempBlock.create_whole_block(20, 20) + tb.should be_an_instance_of(TempBlock) + tb.create_pure_block.should be_nil + end + +end diff --git a/spec/rdgc/maker/02_divide_temp_block_spec.rb b/spec/rdgc/maker/02_divide_temp_block_spec.rb new file mode 100644 index 0000000..318b50a --- /dev/null +++ b/spec/rdgc/maker/02_divide_temp_block_spec.rb @@ -0,0 +1,241 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map +include RDGC::Maker + +describe RDGC::Maker::DivideTempBlock, 'is TempBlock for divide maker' do + + describe 'block divide' do + + it "#depth default is 0" do + dtb =DivideTempBlock.create(0, 10, 0, 10) + dtb.depth.should == 0 + dtb.depth = 3 + dtb.depth.should == 3 + end + + it "#min_size default is config value, and #min_divide_size provides twice value" do + dtb =DivideTempBlock.create(0, 10, 0, 10) + dtb.min_size.should == Util::Config.min_block_size + dtb.min_divide_size.should == Util::Config.min_block_size * 2 + + dtb.min_size = 1 + dtb.min_size.should == Util::Config.min_block_size + dtb.min_divide_size.should == Util::Config.min_block_size * 2 + + val = Util::Config.min_block_size + 2 + dtb.min_size = val + dtb.min_size.should == val + dtb.min_divide_size.should == val * 2 + end + + it "#opposite_direction provides opposite of divide_direction" do + dtb =DivideTempBlock.create_whole_block(20, 20) + dtb.opposite_direction.should be_nil + dtb.divide_direction = :vertical + dtb.opposite_direction.should == :horizontal + dtb.divide_direction = :horizontal + dtb.opposite_direction.should == :vertical + end + + it "#dividable_size? check self can devidable for divide_direction" do + dtb_h = DivideTempBlock.create_whole_block(5, 30) + dtb_h.dividable_size?.should be_false + dtb_h.divide_direction = :vertical + dtb_h.dividable_size?.should be_false + dtb_h.divide_direction = :horizontal + dtb_h.dividable_size?.should be_true + + dtb_w = DivideTempBlock.create_whole_block(30, 5) + dtb_w.dividable_size?.should be_false + dtb_w.divide_direction = :vertical + dtb_w.dividable_size?.should be_true + dtb_w.divide_direction = :horizontal + dtb_w.dividable_size?.should be_false + end + + it "#set_dividable will set dividable, but reject if enough size" do + dtb =DivideTempBlock.create_whole_block(20, 20) + dtb.divide_direction = :vertical + dtb.dividable_size?.should be_true + + dtb.dividable?.should be_false + dtb.set_dividable + dtb.dividable?.should be_true + + dtb.dividable(false) + dtb.min_size = 99 + dtb.dividable_size?.should be_false + + dtb.dividable?.should be_false + dtb.set_dividable + dtb.dividable?.should be_false + + dtb.dividable + dtb.dividable?.should be_true + end + + it "#divide_point provides random value for divide" do + dtb =DivideTempBlock.create_whole_block(30, 40) + dtb.min_size = 5 + + 10.times do + wval = dtb.divide_point(dtb.width) + wval.should >= dtb.min_size + wval.should <= (dtb.width - dtb.min_divide_size) + + wval = dtb.divide_point(dtb.height) + wval.should >= dtb.min_size + wval.should <= (dtb.height - dtb.min_divide_size) + end + end + + it "#divide provides new twice blocks, seted opposite direction" do + 10.times do + dtb =DivideTempBlock.create_whole_block(40, 40) + dtb.divide_direction = :vertical + + ret = dtb.divide + ret.should_not be_empty + ret.size.should <= 2 + + ret.each do |b| + b.width.should < dtb.width + b.height == dtb.height + b.divide_direction.should == :horizontal + end + + dtb =DivideTempBlock.create_whole_block(40, 40) + dtb.divide_direction = :horizontal + + ret = dtb.divide + ret.should_not be_empty + ret.size.should <= 2 + + ret.each do |b| + b.width.should == dtb.width + b.height < dtb.height + b.divide_direction.should == :vertical + end + end + end + + it "#divide will returen nil, if not enough size" do + dtb =DivideTempBlock.create_whole_block(5, 40) + dtb.divide_direction = :vertical + dtb.divide.should be_nil + end + + end + + describe 'for road create' do + + before(:each) do + @dtb =DivideTempBlock.create_whole_block(40, 40) + end + + it "#road_created is sign for main road created" do + @dtb.road_created?.should be_false + @dtb.road_created + @dtb.road_created?.should be_true + end + + it "#road_point is created road's coordinate for each four direction" do + params = { + :top => 1, + :bottom => 2, + :left => 3, + :right => 4 + } + + @dtb.road_point.should be_empty + + params.each do |d, v| + @dtb.set_road_point(d, v) + end + + params.each do |d, v| + @dtb.road_point[d].should == v + end + end + + it "#remain_cling_blocks is cling block, not have room, and not connect by road from self" do + @dtb.remain_cling_blocks.should be_empty + @dtb.has_remain_cling_blocks?.should be_false + + b = DivideTempBlock.create_whole_block(10, 10) + room = Room.create(1, 5, 1, 5) + b.room = room + + @dtb.add_remain_cling_blocks(b) + @dtb.remain_cling_blocks.should be_empty + @dtb.has_remain_cling_blocks?.should be_false + + b = DivideTempBlock.create_whole_block(10, 10) + + @dtb.add_remain_cling_blocks(b) + @dtb.remain_cling_blocks.size.should == 1 + @dtb.remain_cling_blocks.first.should == b + @dtb.has_remain_cling_blocks?.should be_true + end + + it "#dead_end is only one road block of cross point" do + @dtb.dead_end?.should be_false + + @dtb.create_room + @dtb.dead_end?.should be_false + @dtb.remove_all + + @dtb.create_cross_point + @dtb.dead_end?.should be_false + + @dtb.set_road_point(:top, 1) + @dtb.dead_end?.should be_true + + @dtb.set_road_point(:bottom, 20) + @dtb.dead_end?.should be_false + end + + it "#remain_direction provieds remain direction of not road create" do + @dtb.remain_direction.size.should == 4 + + @dtb.set_road_point(:top, 1) + @dtb.remain_direction.size.should == 3 + @dtb.remain_direction.should_not be_include(:top) + + @dtb.set_road_point(:bottom, 20) + @dtb.remain_direction.size.should == 2 + @dtb.remain_direction.should_not be_include(:top) + @dtb.remain_direction.should_not be_include(:bottom) + end + + it "create_road to cling block" do + b1 = DivideTempBlock.create(1, 10, 1, 10) + b2 = DivideTempBlock.create(11, 20, 1, 10) + b3 = DivideTempBlock.create(1, 10 , 11, 20) + b4 = DivideTempBlock.create(11, 20 , 11, 20) + + b1.create_room + b2.create_cross_point + b3.create_cross_point + b4.create_room + + b1.create_road_to(b2) + b1.roads.size.should == 2 + b2.roads.size.should == 1 + + b2.create_road_to(b4) + b2.roads.size.should == 3 + b4.roads.size.should == 1 + + b4.create_road_to(b3) + b4.roads.size.should == 2 + b3.roads.size.should == 2 + + b3.dead_end?.should be_true + end + + end + +end diff --git a/spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb b/spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb new file mode 100644 index 0000000..bbd6cdc --- /dev/null +++ b/spec/rdgc/maker/03_divide_dungeon_maker_divide_spec.rb @@ -0,0 +1,224 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map +include RDGC::Maker + +describe RDGC::Maker::DivideDungeonMaker, 'is divide block by recursive' do + + describe "each acceptable params" do + + it "min_room_size, max_room_size" do + maker = DivideDungeonMaker.new + maker.min_room_size.should be_nil + maker.max_room_size.should be_nil + + maker.params[:min_room_size] = 5 + maker.params[:max_room_size] = 20 + + maker.min_room_size.should == 5 + maker.max_room_size.should == 20 + end + + it "min_block_size" do + # デフォルト + maker = DivideDungeonMaker.new + maker.min_block_size.should == Util::Config.min_block_size + + # デフォルトより小さいとデフォルト + maker = DivideDungeonMaker.new + maker.params[:min_block_size] = 1 + maker.min_block_size.should == Util::Config.min_block_size + + maker = DivideDungeonMaker.new + maker.params[:min_block_size] = 10 + maker.min_block_size.should == 10 + + # 一度読むと書き換えできない + maker.params[:min_block_size] = 20 + maker.min_block_size.should == 10 + + # min_room_sizeが存在し、min_block_sizeが存在しない場合、影響を受ける + maker = DivideDungeonMaker.new + maker.params[:min_room_size] = 5 + maker.min_block_size.should == 8 + end + + it "min_room_count" do + # デフォルトは2 + maker = DivideDungeonMaker.new + maker.min_room_count.should == 2 + + # 値は一度だけセットできる + maker = DivideDungeonMaker.new + maker.params[:min_room_count] = 3 + maker.min_room_count.should == 3 + maker.params[:min_room_count] = 5 + maker.min_room_count.should == 3 + + # 明示的に1を指定すると1 + maker = DivideDungeonMaker.new + maker.params[:min_room_count] = 1 + maker.min_room_count.should == 1 + + # 0以下ならデフォルト + maker = DivideDungeonMaker.new + maker.params[:min_room_count] = 0 + maker.min_room_count.should == 2 + end + + it "max_room_count" do + maker = DivideDungeonMaker.new + maker.max_room_count.should == 0 + + maker.params[:max_room_count] = 8 + maker.max_room_count.should == 8 + end + + it "max_depth" do + maker = DivideDungeonMaker.new + maker.max_depth.should == 0 + + maker.params[:max_depth] = 3 + maker.max_depth.should == 3 + end + + it "cross_road_ratio" do + # デフォルトは2 + maker = DivideDungeonMaker.new + maker.cross_road_ratio.should == DivideDungeonMaker::DEFAULT_CROSS_ROAD_RATIO + + # 値は一度だけセットできる + maker = DivideDungeonMaker.new + maker.params[:cross_road_ratio] = 3 + maker.cross_road_ratio.should == 3 + maker.params[:cross_road_ratio] = 5 + maker.cross_road_ratio.should == 3 + + # 0未満ならデフォルト + maker = DivideDungeonMaker.new + maker.params[:cross_road_ratio] = -1 + maker.cross_road_ratio.should == 2 + + # 0はセット可能 + maker = DivideDungeonMaker.new + maker.params[:cross_road_ratio] = 0 + maker.cross_road_ratio.should == 0 + + # 9を超えるならデフォルト + maker = DivideDungeonMaker.new + maker.params[:cross_road_ratio] = 10 + maker.cross_road_ratio.should == 2 + end + + end + + describe "divide whole_block" do + + it "divide_queue store dividable block, and done_queue store divided block" do + maker = DivideDungeonMaker.new + maker.queue_size.should == 0 + + maker.divide_queue << DivideTempBlock.create_whole_block(20, 20) + maker.divide_queue.size.should == 1 + maker.queue_size.should == 1 + + maker.done_queue << DivideTempBlock.create_whole_block(20, 20) + maker.done_queue.size.should == 1 + maker.queue_size.should == 2 + end + + it "#finish? will check divide end" do + maker = DivideDungeonMaker.new + maker.finish?.should be_true + + maker.done_queue << DivideTempBlock.create_whole_block(20, 20) + maker.finish?.should be_true + + maker.divide_queue << DivideTempBlock.create_whole_block(20, 20) + maker.finish?.should be_false + + maker.params[:max_block_count] = 3 + maker.finish?.should be_false + + maker.done_queue << DivideTempBlock.create_whole_block(20, 20) + maker.finish?.should be_true + end + + it "#dividable_block? check block dividable" do + # max_depthの指定がない場合 + maker = DivideDungeonMaker.new + b = DivideTempBlock.create_whole_block(20, 20) + + maker.dividable_block?(b).should be_false + b.dividable + maker.dividable_block?(b).should be_true + + # max_depthが指定されている場合 + maker = DivideDungeonMaker.new + maker.params[:max_depth] = 3 + b = DivideTempBlock.create_whole_block(20, 20) + + b.dividable + maker.dividable_block?(b).should be_true + b.depth = 3 + maker.dividable_block?(b).should be_false + end + + it "create_whole_block" do + maker = DivideDungeonMaker.new + tb = maker.create_whole_block(30, 40) + tb.should be_an_instance_of(DivideTempBlock) + tb.width.should == 30 + tb.height.should == 40 + tb.min_size.should == Util::Config.min_block_size + tb.dividable?.should be_true + end + + it "divide block" do + each_create_block do |b| + b.should be_an_instance_of(DivideTempBlock) + end + end + + it "min_block_size/max_block_count/max_depth affect divide as possible" do + 10.times do + each_create_block(:min_block_size, 6) do |b| + b.should be_an_instance_of(DivideTempBlock) + b.width.should >= 6 + b.height.should >= 6 + end + end + + 10.times do + count = 0 + each_create_block(:max_block_count, 5) do |b| + b.should be_an_instance_of(DivideTempBlock) + count += 0 + end + count.should <= 5 + end + + 10.times do + count = 0 + each_create_block(:max_depth, 3) do |b| + b.should be_an_instance_of(DivideTempBlock) + b.depth <= 3 + count += 1 + end + count.should <= 8 + end + end + + def each_create_block(name = nil, val = nil) + maker = DivideDungeonMaker.new + maker.params[name] = val if name && val + tb = maker.create_whole_block(40, 40) + bl = maker.make_blocks(tb) + + bl.each{|b| yield(b)} + end + + end + +end diff --git a/spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb b/spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb new file mode 100644 index 0000000..b534df4 --- /dev/null +++ b/spec/rdgc/maker/04_divide_dungeon_maker_create_spec.rb @@ -0,0 +1,244 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map +include RDGC::Maker + +describe RDGC::Maker::DivideDungeonMaker, 'create room/road for each block' do + + describe "create room" do + + it "create_room by default" do + 10.times do + maker = create_maker_with_blocks + maker.create_room + + maker.blocks.each do |b| + rsl_room = b.has_room? + rsl_cross = b.has_cross_point? + (rsl_room || rsl_cross).should be_true + (rsl_room && rsl_cross).should be_false + end + + maker.blocks.select{|b| b.has_room?}.size.should >= 2 + end + end + + it "min_room_size/max_room_size affect room size" do + val = 5 + + 10.times do + maker = create_maker_with_blocks(:min_room_size => val) + maker.create_room + + maker.blocks.select{|b| b.has_room?}.map{|b| b.room}.each do |r| + r.width.should >= val + r.height.should >= val + end + end + + 10.times do + maker = create_maker_with_blocks(:max_room_size => val) + maker.create_room + + maker.blocks.select{|b| b.has_room?}.map{|b| b.room}.each do |r| + r.width.should <= val + r.height.should <= val + end + end + end + + it "min_room_count/max_room_count affect room count" do + 10.times do + maker = create_maker_with_blocks(:min_room_count => 3) + maker.create_room + maker.blocks.select{|b| b.has_room?}.size.should >= 3 + end + + 10.times do + maker = create_maker_with_blocks(:max_room_count => 3) + maker.create_room + maker.blocks.select{|b| b.has_room?}.size.should <= 3 + end + + 10.times do + maker = create_maker_with_blocks(:min_room_count => 1, :max_room_count => 1) + maker.create_room + maker.blocks.select{|b| b.has_room?}.size.should == 1 + end + + end + + it "cross_road_ratio affect room create" do + 10.times do + maker = create_maker_with_blocks(:cross_road_ratio => 9) + maker.create_room + + all_size = maker.blocks.size + maker.blocks.select{|b| b.has_room?}.size.should >= 2 + maker.blocks.select{|b| b.has_cross_point?}.size.should <= all_size - 2 + end + + 10.times do + maker = create_maker_with_blocks(:cross_road_ratio => 0) + maker.create_room + + all_size = maker.blocks.size + maker.blocks.select{|b| b.has_room?}.size.should == all_size + maker.blocks.select{|b| b.has_cross_point?}.size.should == 0 + end + end + + end + + describe "create road" do + + it "room block should has roads, if min_room_count too big" do + 10.times do + maker = create_maker_with_blocks(:min_room_count => 99) + maker.create_room + maker.create_road + + maker.blocks.select{|b| b.has_room?}.each do |b| + b.has_road?.should be_true + end + end + end + + it "no create road if only one block" do + maker = create_maker_with_blocks(:min_block_size => 99) + maker.create_room + maker.blocks.size.should == 1 + + maker.create_road + maker.blocks.select{|b| b.has_road?}.should be_empty + end + + it "#move_room_and_connect spec" do + + b1 = DivideTempBlock.create(0, 10, 0, 10) + b2 = DivideTempBlock.create(0, 10, 11, 20) + b3 = DivideTempBlock.create(0, 10, 21, 30) + b4 = DivideTempBlock.create(0, 10, 31, 40) + + b1.create_room + b2.create_room + b4.create_room + b1.create_road_to(b2) + b2.add_remain_cling_blocks(b3) + + maker = DivideDungeonMaker.new + maker.instance_eval do + @params = {:min_room_count => 10} + @blocks = [b1, b2, b3, b4] + end + + maker.move_room_and_connect + + b3.has_room?.should be_true + b3.has_road?.should be_true + b4.has_room?.should be_false + b4.has_road?.should be_false + end + + end + + describe "make all" do + + it "create provide complete board" do + board = DivideDungeonMaker.create(40, 40) + board.should be_an_instance_of(Map::Board) + board.blocks.select{|b| b.has_room?}.each do |b| + b.should be_an_instance_of(Block) + b.should_not be_an_instance_of(DivideTempBlock) + b.has_road?.should be_true + end + end + + it "create accept params" do + params = {} + params[:min_room_size] = 5 + params[:max_room_size] = 10 + params[:min_block_size] = 8 + params[:min_room_count] = 3 + params[:max_room_count] = 8 + params[:max_depth] = 4 + params[:cross_road_ratio] = 4 + + 10.times do + board = DivideDungeonMaker.create(80, 80, params) + board.should be_an_instance_of(Map::Board) + + board.blocks.size.should <= 16 # depth + + room_count = 0 + board.blocks.each do |b| + b.should be_an_instance_of(Block) + b.should_not be_an_instance_of(DivideTempBlock) + + b.width.should >= params[:min_block_size] + b.height.should >= params[:min_block_size] + + next unless b.has_room? + room = b.room + + room.width.should >= params[:min_room_size] + room.width.should <= params[:max_room_size] + room.height.should >= params[:min_room_size] + room.height.should <= params[:max_room_size] + + room_count += 1 + end + room_count.should >= params[:min_room_count] + room_count.should <= params[:max_room_count] + end + end + + it "only one block board" do + params = {} + params[:min_room_count] = 1 + params[:max_room_count] = 1 + params[:min_block_size] = 99 + + 10.times do + board = DivideDungeonMaker.create(40, 40, params) + board.should be_an_instance_of(Map::Board) + + board.blocks.size.should == 1 + board.blocks.map(&:room).size.should == 1 + board.blocks.inject([]){|l, b| l + b.roads}.should be_empty + end + end + + it "only room board" do + 10.times do + board = DivideDungeonMaker.create(40, 40, :cross_road_ratio => 0) + board.should be_an_instance_of(Map::Board) + + board.blocks.each do |b| + b.has_room?.should be_true + b.has_road?.should be_true + b.has_cross_point?.should be_false + end + end + end + + end + + def create_maker_with_blocks(params = nil) + maker = DivideDungeonMaker.new + maker.instance_eval do + @params = params + end + + tb = maker.create_whole_block(40, 40) + bl = maker.make_blocks(tb) + + bl.each do |b| + maker.blocks << b + end + + maker + end + +end diff --git a/spec/rdgc/map/01_tile_spec.rb b/spec/rdgc/map/01_tile_spec.rb new file mode 100644 index 0000000..13626d1 --- /dev/null +++ b/spec/rdgc/map/01_tile_spec.rb @@ -0,0 +1,56 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map + +describe RDGC::Map::Tile do + + it "created for :out" do + t = Tile.new(:out) + t.out?.should be_true + t.movable?.should be_false + end + + it "created for :wall" do + t = Tile.new(:wall) + t.wall?.should be_true + t.movable?.should be_false + end + + it "created for :room" do + t = Tile.new(:room) + t.room?.should be_true + t.movable?.should be_true + end + + it "created for :road" do + t = Tile.new(:road) + t.road?.should be_true + t.movable?.should be_true + end + + it "TileType::OUT behaves for :out" do + t = TileType::OUT + t.out?.should be_true + t.movable?.should be_false + end + + it "TileType::WALL behaves for :wall" do + t = TileType::WALL + t.wall?.should be_true + t.movable?.should be_false + end + + it "TileType::ROOM behaves for :room" do + t = TileType::ROOM + t.room?.should be_true + t.movable?.should be_true + end + + it "TileType::ROAD behaves for :road" do + t = TileType::ROAD + t.road?.should be_true + t.movable?.should be_true + end + +end diff --git a/spec/rdgc/map/02_area_spec.rb b/spec/rdgc/map/02_area_spec.rb new file mode 100644 index 0000000..7a0ed4d --- /dev/null +++ b/spec/rdgc/map/02_area_spec.rb @@ -0,0 +1,118 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map + +describe RDGC::Map::Area, "provide area, filled with Tile" do + + before(:all) do + @top = 8 + @bottom = 10 + @left = 11 + @right = 19 + + @area = Area.new + @area.top = @top + @area.bottom = @bottom + @area.left = @left + @area.right = @right + end + + it "top <= bottom, left <= right" do + (@top <= @bottom).should be_true + (@left <= @right).should be_true + end + + it "#height should be (bottom - top + 1)" do + @area.height.should == (@bottom - @top + 1) + end + + it "#width should be (right - left + 1)" do + @area.width.should == (@right - @left + 1) + end + + it "#coordinates/#to_co puts params" do + expect = "t:#{@top} b:#{@bottom} l:#{@left} r:#{@right} / w:#{@area.width} h:#{@area.height}" + @area.coordinates.should == expect + @area.to_co.should == expect + end + + it "#has_xy? should be true if in area, false out of area, for (x, y)" do + @area.has_xy?(@left, @top).should be_true + @area.has_xy?(@left-1, @top).should be_false + @area.has_xy?(@left, @top-1).should be_false + @area.has_xy?(@right, @bottom).should be_true + @area.has_xy?(@right+1, @bottom).should be_false + @area.has_xy?(@right, @bottom+1).should be_false + end + + it "#each_x provides each left to right" do + last = nil + @area.each_x.with_index do |x, i| + x.should == @left + i + last = @left + i + end + last.should == @right + end + + it "#each_y provides each top to bottom" do + last = nil + @area.each_y.with_index do |y, i| + y.should == @top + i + last = @top + i + end + last.should == @bottom + end + + it "#each provides all coordinates" do + @area.each do |x, y| + @area.has_xy?(x, y).should be_true + end + + cs = @area.each + cs.should be_kind_of(Enumerable) + cs.each do |x, y| + @area.has_xy?(x, y).should be_true + end + end + + it "#fill_tile set tile for all coordinates" do + @area.fill_tile(TileType::WALL) + @area.each do |x, y| + @area.tile(x, y).should == TileType::WALL + end + end + + it "#each_tile provides each coordinate's tile" do + @area.fill_tile(TileType::ROAD) + @area.each_tile do |x, y, t| + t.should == TileType::ROAD + end + + ts = @area.each_tile + ts.should be_kind_of(Enumerable) + tiles = ts.to_a.map{|a| a.last} + tiles.all?{|t| t == TileType::ROAD} + end + + it "#set_tile will set tile object for (x, y)" do + @area.set_tile(@left, @top, TileType::ROOM).should be_an_instance_of(Tile) + t = @area.tile(@left, @top) + t.should be_an_instance_of(Tile) + t.should == TileType::ROOM + end + + it "#set_tile failed, and #tile is nil, if out of area" do + @area.set_tile(@left-1, @top-1, TileType::ROOM).should be_nil + t = @area.tile(@left-1, @top-1) + t.should be_nil + end + + it "#random_point provides random point in area" do + 10.times do + x, y = @area.random_point + @area.has_xy?(x, y).should be_true + end + end + +end diff --git a/spec/rdgc/map/03_road_spec.rb b/spec/rdgc/map/03_road_spec.rb new file mode 100644 index 0000000..974e48e --- /dev/null +++ b/spec/rdgc/map/03_road_spec.rb @@ -0,0 +1,23 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map + +describe RDGC::Map::Road, "is Area, filled with TileType::ROAD" do + + before do + @top = 8 + @bottom = 8 + @left = 11 + @right = 19 + + @road = Road.create(@top, @bottom, @left, @right) + end + + it "filled with TileType::ROAD" do + @road.each_tile do |x, y, t| + t.should == TileType::ROAD + end + end + +end diff --git a/spec/rdgc/map/04_room_spec.rb b/spec/rdgc/map/04_room_spec.rb new file mode 100644 index 0000000..1d1058b --- /dev/null +++ b/spec/rdgc/map/04_room_spec.rb @@ -0,0 +1,190 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map + +describe RDGC::Map::Room, "is Area, filled with TileType::ROOM" do + + before(:all) do + @top = 8 + @bottom = 20 + @left = 21 + @right = 40 + + @block = Area.create(@top, @bottom, @left, @right) + @notblock = Area.create(1, 1, 1, 1) + end + + it "room_size provides random value for room's height/width" do + min = 1 + max = 50 + (min..max).each do |val| + size = Room.room_size(val) + if size <= 0 + (val-3).should < Util::Config.min_room_size + else + size.should >= Util::Config.min_room_size + size.should <= val-3 + end + end + end + + describe "for create_from_block" do + + it "not enough size block can't create room" do + Room.create_from_block(@notblock).should be_nil + end + + it "filled with TileType::ROOM" do + each_create_room do |r| + r.each_tile do |x, y, t| + t.should == TileType::ROOM + end + end + end + + it "room height/width <= block height/width - 3" do + each_create_room do |r| + r.height.should <= @block.height - 3 + r.width.should <= @block.width - 3 + end + end + + it "room's all coordinates in block area" do + each_create_room do |r| + r.each do |x, y| + @block.has_xy?(x, y).should be_true + end + end + end + + end + + describe "for create_from_block with min and max value" do + + it "room create accept min and max value" do + min = 5 + max = 10 + opt = {:min => min, :max => max} + + each_create_room(opt) do |r| + r.height.should <= max + r.height.should >= min + r.width.should <= max + r.width.should >= min + end + end + + it "only max" do + max = 10 + min = Util::Config.min_room_size + opt = {:max => max} + + each_create_room(opt) do |r| + r.height.should <= max + r.height.should >= min + r.width.should <= max + r.width.should >= min + end + end + + it "only min" do + min = 5 + opt = {:min => min} + + each_create_room(opt) do |r| + r.height.should <= @block.height - 3 + r.height.should >= min + r.width.should <= @block.width - 3 + r.width.should >= min + end + end + + it "min = max if min > max" do + min = 10 + max = 5 + opt = {:min => min, :max => max} + + each_create_room(opt) do |r| + r.height.should == max + r.width.should == max + end + end + + it "min value can't under MIN_ROOM_SIZE, and adjust MIN_ROOM_SIZE" do + min = 1 + opt = {:min => min} + + each_create_room(opt) do |r| + valid_room?(r).should be_true + end + end + + it "room size adjust limit size, if min value over base size" do + min = 200 + opt = {:min => min} + + each_create_room(opt) do |r| + r.height.should == @block.height - 3 + r.width.should == @block.width - 3 + end + end + + it "max value can't over base size, and adjust base size" do + max = 200 + opt = {:max => max} + + each_create_room(opt) do |r| + valid_room?(r).should be_true + end + end + + it "room size adjust MIN_ROOM_SIZE, if max value under MIN_ROOM_SIZE" do + max = 1 + opt = {:max => max} + + each_create_room(opt) do |r| + r.height.should == Util::Config.min_room_size + r.width.should == Util::Config.min_room_size + end + end + + end + + describe "Config affect min_room_size" do + + it "min_room_size change if Config change" do + Util::Config.set(:min_room_size => 5).should be_true + + min = 1 + max = 50 + (min..max).each do |val| + size = Room.room_size(val) + if size <= 0 + (val-3).should < 5 + else + size.should >= 5 + size.should <= val-3 + end + end + + Util::Config.reset!.should be_true + end + + end + + def each_create_room(opt = nil) + 10.times do + yield(Room.create_from_block(@block, opt)) + end + end + + def valid_room?(r) + return false unless r.height <= @block.height - 3 + return false unless r.height >= Util::Config.min_room_size + return false unless r.width <= @block.width - 3 + return false unless r.width >= Util::Config.min_room_size + true + end + +end diff --git a/spec/rdgc/map/05_block_spec.rb b/spec/rdgc/map/05_block_spec.rb new file mode 100644 index 0000000..f139989 --- /dev/null +++ b/spec/rdgc/map/05_block_spec.rb @@ -0,0 +1,273 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map + +describe RDGC::Map::Block, 'has room and roads' do + + before do + @block = Block.create(1, 20, 11, 30) + end + + it "set/remove room" do + room = Room.create(1, 7, 15, 20) + + @block.room = room + @block.has_room?.should be_true + @block.room.should equal(room) + + @block.remove_room + @block.has_room?.should be_false + @block.room.should be_nil + end + + it "add/remove road" do + road1 = Road.create(2, 2, 11, 14) + road2 = Road.create(1, 6, 20, 20) + + @block.add_road(road1) + @block.has_road?.should be_true + @block.roads.size.should == 1 + @block.roads[0].should equal(road1) + + @block.add_road(road2) + @block.has_road?.should be_true + @block.roads.size.should == 2 + @block.roads[0].should equal(road1) + @block.roads[1].should equal(road2) + + @block.remove_roads + @block.has_road?.should be_false + @block.roads.should be_empty + end + + it "#fill_room will set tile at room coordinates" do + room = Room.create(1, 7, 15, 20) + + @block.room = room + @block.has_room?.should be_true + @block.room.should equal(room) + + @block.fill_room + + room.each_tile do |x, y, t| + @block.has_xy?(x, y).should be_true + @block.tile(x, y).should equal(TileType::ROOM) + end + end + + it "#fill_roads will set tile at road coordinates" do + road1 = Road.create(2, 2, 11, 14) + road2 = Road.create(1, 6, 20, 20) + + @block.add_road(road1) + @block.add_road(road2) + @block.has_road?.should be_true + @block.roads.size.should == 2 + + @block.fill_roads + + [road1, road2].each do |road| + road.each_tile do |x, y, t| + @block.has_xy?(x, y).should be_true + @block.tile(x, y).should equal(TileType::ROAD) + end + end + end + + it "#fill will fill room/road, and fill at wall other coordinates" do + room = Room.create(1, 7, 15, 20) + road = Road.create(2, 2, 11, 14) + + @block.room = room + @block.add_road(road) + + @block.fill + + @block.each_tile do |x, y, t| + case + when room.has_xy?(x, y) + t.should equal(TileType::ROOM) + when road.has_xy?(x, y) + t.should equal(TileType::ROAD) + else + t.should equal(TileType::WALL) + end + end + end + + it "#create_room create and set room from self block" do + @block.room.should be_nil + + 10.times do + room = @block.create_room + room.should be_an_instance_of(Room) + + room.width.should <= @block.width - 3 + room.height.should <= @block.height - 3 + + room.each do |x, y| + @block.has_xy?(x, y).should be_true + end + end + end + + it "#create_room accept option value" do + min = 5 + max = 8 + + @block.room.should be_nil + 10.times do + room = @block.create_room(:min => min, :max => max) + room.should be_an_instance_of(Room) + + room.width.should >= min + room.width.should <= max + room.height.should >= min + room.height.should <= max + end + end + + it "cross_point is cross point of road, instead of room" do + @block.cross_point.should be_nil + @block.has_cross_point?.should be_false + + 10.times do + x, y = @block.create_cross_point + + @block.has_cross_point?.should be_true + @block.has_xy?(x, y).should be_true + x.should >= @block.left + 1 + x.should <= @block.right - 2 + y.should >= @block.top + 1 + y.should <= @block.bottom - 2 + + _x, _y = @block.cross_point + _x.should == x + _y.should == y + end + + @block.remove_cross_point + + @block.cross_point.should be_nil + @block.has_cross_point?.should be_false + end + + it "#remove_all will clear room/road/cross_point and #empty? is true" do + room = Room.create(1, 7, 15, 20) + road = Road.create(2, 2, 11, 14) + + @block.room = room + @block.add_road(road) + @block.create_cross_point + + @block.has_room?.should be_true + @block.has_road?.should be_true + @block.has_cross_point?.should be_true + @block.empty?.should be_false + + @block.remove_all + + @block.has_room?.should be_false + @block.has_road?.should be_false + @block.has_cross_point?.should be_false + @block.empty?.should be_true + end + + it "#cling_to_top? / #cling_direction_to judge self and target block adjoin with top" do + # 基準(元の左上) + b = Block.create(-10, 0, 0, 10) + @block.cling_to_top?(b).should be_false + + # 右端が範囲内 + b = Block.create(-10, 0, 1, 11) + @block.cling_to_top?(b).should be_true + @block.cling_direction_to(b).should == :top + + # 左端が範囲内 + b = Block.create(-10, 0, 30, 40) + @block.cling_to_top?(b).should be_true + @block.cling_direction_to(b).should == :top + + # 左端が範囲外 + b = Block.create(-10, 0, 31, 41) + @block.cling_to_top?(b).should be_false + + # 重なるとダメ + b = Block.create(-9, 1, 15, 25) + @block.cling_to_top?(b).should be_false + end + + it "#cling_to_bottom? / #cling_direction_to judge self and target block adjoin with bottom" do + # 基準(元の左下) + b = Block.create(21, 31, 0, 10) + @block.cling_to_bottom?(b).should be_false + + # 右端が範囲内 + b = Block.create(21, 31, 1, 11) + @block.cling_to_bottom?(b).should be_true + @block.cling_direction_to(b).should == :bottom + + # 左端が範囲内 + b = Block.create(21, 31, 30, 40) + @block.cling_to_bottom?(b).should be_true + @block.cling_direction_to(b).should == :bottom + + # 左端が範囲外 + b = Block.create(21, 31, 31, 41) + @block.cling_to_bottom?(b).should be_false + + # 重なるとダメ + b = Block.create(20, 30, 15, 25) + @block.cling_to_bottom?(b).should be_false + end + + it "#cling_to_left? / #cling_direction_to judge self and target block adjoin with left" do + # 基準(元の左上) + b = Block.create(-10, 0, 0, 10) + @block.cling_to_left?(b).should be_false + + # 下端が範囲内 + b = Block.create(-9, 1, 0, 10) + @block.cling_to_left?(b).should be_true + @block.cling_direction_to(b).should == :left + + # 上端が範囲内 + b = Block.create(20, 30, 0, 10) + @block.cling_to_left?(b).should be_true + @block.cling_direction_to(b).should == :left + + # 上端が範囲外 + b = Block.create(21, 31, 0, 10) + @block.cling_to_left?(b).should be_false + + # 重なるとダメ + b = Block.create(15, 30, 1, 11) + @block.cling_to_left?(b).should be_false + end + + it "#cling_to_right? / #cling_direction_to judge self and target block adjoin with right" do + # 基準(元の右上) + b = Block.create(-10, 0, 31, 41) + @block.cling_to_right?(b).should be_false + + # 下端が範囲内 + b = Block.create(-9, 1, 31, 41) + @block.cling_to_right?(b).should be_true + @block.cling_direction_to(b).should == :right + + # 上端が範囲内 + b = Block.create(20, 30, 31, 41) + @block.cling_to_right?(b).should be_true + @block.cling_direction_to(b).should == :right + + # 上端が範囲外 + b = Block.create(21, 31, 31, 41) + @block.cling_to_right?(b).should be_false + + # 重なるとダメ + b = Block.create(15, 30, 30, 40) + @block.cling_to_right?(b).should be_false + end + +end diff --git a/spec/rdgc/map/06_board_spec.rb b/spec/rdgc/map/06_board_spec.rb new file mode 100644 index 0000000..35913e9 --- /dev/null +++ b/spec/rdgc/map/06_board_spec.rb @@ -0,0 +1,132 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Map + +describe RDGC::Map::Board, 'has rooms and roads from Blocks' do + + it "#set_coordinates will set self coordinates from blocks coordinates" do + b = Board.create(1, 1, 1, 1) + b.should be_an_instance_of(Board) + b.width.should == 1 + b.height.should == 1 + + b.blocks << Block.create(0, 20, 10, 30) + b.blocks << Block.create(10, 30, 20, 40) + + b.set_coordinates + + b.top.should == 0 + b.bottom.should == 30 + b.left.should == 10 + b.right.should == 40 + end + + it "#fill will fill room/road, and fill at wall other coordinates" do + b = Board.create(0, 20, 0, 20) + + room = Room.create(5, 15, 5, 15) + road1 = Road.create(0, 4, 10, 10) + road2 = Road.create(16, 20, 12, 12) + + b.rooms << room + b.roads << road1 + b.roads << road2 + + b.fill + + b.each_tile do |x, y, t| + case t + when TileType::WALL + room.has_xy?(x, y).should be_false + road1.has_xy?(x, y).should be_false + road2.has_xy?(x, y).should be_false + + b.movable?(x, y).should be_false + b.room?(x, y).should be_false + b.road?(x, y).should be_false + when TileType::ROOM + room.has_xy?(x, y).should be_true + road1.has_xy?(x, y).should be_false + road2.has_xy?(x, y).should be_false + + b.movable?(x, y).should be_true + b.room?(x, y).should be_true + b.road?(x, y).should be_false + when TileType::ROAD + room.has_xy?(x, y).should be_false + [road1, road2].map{|r| r.has_xy?(x, y)}.any?.should be_true + + b.movable?(x, y).should be_true + b.room?(x, y).should be_false + b.road?(x, y).should be_true + end + end + end + + it "#init will initialize self from blocks, and create_from_blocks will provides init Board" do + block1 = Block.create(0, 20, 0, 20) + room1 = Room.create(5, 15, 5, 15) + road1 = Road.create(0, 4, 10, 10) + road2 = Road.create(16, 20, 12, 12) + block1.room = room1 + block1.add_road(road1) + block1.add_road(road2) + + block2 = Block.create(21, 40, 0, 20) + room2 = Room.create(25, 35, 25, 35) + road3 = Road.create(21, 24, 12, 12) + block2.room = room2 + block2.add_road(road3) + + b1 = Board.create(1, 1, 1, 1) + b1.init([block1, block2]) + + b2 = Board.create_from_blocks([block1, block2]) + b2.should be_an_instance_of(Board) + + [b1, b2].each do |b| + b.blocks.should be_include(block1) + b.blocks.should be_include(block2) + b.rooms.should be_include(room1) + b.rooms.should be_include(room2) + b.roads.should be_include(road1) + b.roads.should be_include(road2) + b.roads.should be_include(road3) + + # set_coordinates + b.top.should == 0 + b.bottom.should == 40 + b.left.should == 0 + b.right.should == 20 + + # fill + b.each_tile do |x, y, t| + case t + when TileType::WALL + [room1, room2].map{|r| r.has_xy?(x, y)}.any?.should be_false + [road1, road2, road3].map{|r| r.has_xy?(x, y)}.any?.should be_false + + b.movable?(x, y).should be_false + b.room?(x, y).should be_false + b.road?(x, y).should be_false + when TileType::ROOM + [room1, room2].map{|r| r.has_xy?(x, y)}.any?.should be_true + [road1, road2, road3].map{|r| r.has_xy?(x, y)}.any?.should be_false + + b.movable?(x, y).should be_true + b.room?(x, y).should be_true + b.road?(x, y).should be_false + when TileType::ROAD + [room1, room2].map{|r| r.has_xy?(x, y)}.any?.should be_false + [road1, road2, road3].map{|r| r.has_xy?(x, y)}.any?.should be_true + + b.movable?(x, y).should be_true + b.room?(x, y).should be_false + b.road?(x, y).should be_true + end + end + end + end + +end \ No newline at end of file diff --git a/spec/rdgc/util/01_config_spec.rb b/spec/rdgc/util/01_config_spec.rb new file mode 100644 index 0000000..acc2b7b --- /dev/null +++ b/spec/rdgc/util/01_config_spec.rb @@ -0,0 +1,44 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Util + +describe RDGC::Util::Config do + + it "default value" do + Util::Config.min_room_size.should == 4 + Util::Config.min_block_size.should == 7 + Util::Config.act_max_count.should == 200 + end + + it "value change only once, and #reset! will force change default value" do + val1 = { + :min_room_size => 5, + :act_max_count => 100 + } + + Util::Config.set(val1).should be_true + Util::Config.min_room_size.should == 5 + Util::Config.act_max_count.should == 100 + + val2 = { + :min_room_size => 10, + :act_max_count => 80 + } + + Util::Config.set(val2).should be_false + Util::Config.min_room_size.should == 5 + Util::Config.act_max_count.should == 100 + + Util::Config.reset!.should be_true + Util::Config.min_room_size.should == 4 + Util::Config.act_max_count.should == 200 + + Util::Config.set(val2).should be_true + Util::Config.min_room_size.should == 10 + Util::Config.act_max_count.should == 80 + + Util::Config.reset!.should be_true + end + +end diff --git a/spec/rdgc/util/02_random_util_spec.rb b/spec/rdgc/util/02_random_util_spec.rb new file mode 100644 index 0000000..ba30943 --- /dev/null +++ b/spec/rdgc/util/02_random_util_spec.rb @@ -0,0 +1,153 @@ +# coding: UTF-8 +require File.expand_path(File.dirname(__FILE__) + '../../../spec_helper') + +include RDGC::Util + +describe RDGC::Util::RandomUtil do + + it "bool_rand provides true or false" do + 100.times do + [true, false].should be_include(bool_rand) + end + end + + describe "range_rand provides s_val <= val <= e_val" do + + it "give s_val and e_val" do + s_val = 1 + e_val = 10 + + 100.times do + ret = range_rand(s_val, e_val) + ret.should >= s_val + ret.should <= e_val + end + end + + it "return s_val if s_val > e_val" do + s_val = 15 + e_val = 1 + + 100.times do + ret = range_rand(s_val, e_val) + ret.should == s_val + end + end + + end + + describe "select_rand provides hash key at random" do + + it "select random key" do + hash = {:k1 => 10, :k2 => 5, :k3 => 3} + expect = [:k1, :k2, :k3] + + 100.times do + ret = select_rand(hash) + expect.should be_include(ret) + end + end + + it "never return key if value = 0" do + hash = {:k1 => 1, :k2 => 1, :k3 => 0} + expect = [:k1, :k2] + + 100.times do + ret = select_rand(hash) + expect.should be_include(ret) + end + end + + it "return nil, if hash is nil or values sum 0" do + hash = {:k1 => 0, :k2 => 0, :k3 => 0} + + 10.times do + ret = select_rand(hash) + ret.should be_nil + end + + 10.times do + ret = select_rand(nil) + ret.should be_nil + end + end + + end + + describe "dice provides value like (n-dice * times)" do + + it "dice(1, n) behave n-dice" do + [4, 6, 10].each do |n| + 100.times do + val = dice(1, n) + val.should >= 1 + val.should <= n + end + end + end + + it "dice(n, 6) behave 6-dice roll n-times" do + (1..10).each do |n| + 100.times do + val = dice(n, 6) + val.should >= (1 * n) + val.should <= (6 * n) + end + end + end + + end + + describe "define Integer#dice" do + + it "#d4 #d6 #d10 provides each-dice roll self-times" do + (1..10).each do |n| + 100.times do + d4 = n.d4 + d4.should >= (1 * n) + d4.should <= (4 * n) + + d6 = n.d6 + d6.should >= (1 * n) + d6.should <= (6 * n) + + d10 = n.d10 + d10.should >= (1 * n) + d10.should <= (10 * n) + end + end + end + + it "any number dice can use, example 4.d5, 3.d16" do + 100.times do + val1 = 4.d5 + val1.should >= (1 * 4) + val1.should <= (5 * 4) + + val2 = 3.d16 + val2.should >= (1 * 3) + val2.should <= (16 * 3) + end + end + + end + + describe "define Array#pickup!" do + + it "#pickup! shift random value in Array" do + array = [1, 2, 3, 4, 5] + list = array.dup + + array.size.times do |i| + ret = list.pickup! + array.should be_include(ret) + list.should_not be_include(ret) + list.size.should == array.size - (i+1) + end + + list.should be_empty + end + + end + +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index dce2118..d4a4775 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,9 +1,11 @@ $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'rdgc-dm' require 'spec' require 'spec/autorun' +include RDGC + Spec::Runner.configure do |config| end
parrot-studio/rdgc-dm
337ab755acc37b5a8931a51038bfec37f1c28adf
Version bump to 0.1.0
diff --git a/VERSION b/VERSION index 77d6f4c..6e8bf73 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.0 +0.1.0
parrot-studio/rdgc-dm
a1ac521253b8da100836d246940e08c835248b08
Version bump to 0.0.0
diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..77d6f4c --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.0.0
makevoid/voidtools
d2cd5e571946dd6896d0745dbd820664d42eeaa6
added name_url spec
diff --git a/.gitignore b/.gitignore index b81217d..d35a340 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .bundle -*.gem \ No newline at end of file +*.gem +*.sql \ No newline at end of file diff --git a/Gemfile b/Gemfile index e69de29..0fd2c6a 100644 --- a/Gemfile +++ b/Gemfile @@ -0,0 +1,9 @@ +source :rubygems + +group :test do + gem "rspec-core" + gem "rspec-mocks" + gem "rspec-expectations" + gem "dm-core" + gem "dm-sqlite-adapter" +end \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..be00c88 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,31 @@ +GEM + remote: http://rubygems.org/ + specs: + addressable (2.2.8) + data_objects (0.10.8) + addressable (~> 2.1) + diff-lcs (1.1.3) + dm-core (1.2.0) + addressable (~> 2.2.6) + dm-do-adapter (1.2.0) + data_objects (~> 0.10.6) + dm-core (~> 1.2.0) + dm-sqlite-adapter (1.2.0) + dm-do-adapter (~> 1.2.0) + do_sqlite3 (~> 0.10.6) + do_sqlite3 (0.10.8) + data_objects (= 0.10.8) + rspec-core (2.10.0) + rspec-expectations (2.10.0) + diff-lcs (~> 1.1.3) + rspec-mocks (2.10.1) + +PLATFORMS + ruby + +DEPENDENCIES + dm-core + dm-sqlite-adapter + rspec-core + rspec-expectations + rspec-mocks diff --git a/README.md b/README.md index 2dc4a8c..da897d7 100644 --- a/README.md +++ b/README.md @@ -1,116 +1,116 @@ # Voidtools #### handy toolset for Sinatra with DataMapper and HAML --- ### Install from RubyGems gem i voidtools ### DataMapper - form helpers: error_messages_for - name url - pagination ### Sinatra - seo tracking - view helpers - link_to - image_tag - include_assets (include_js, include_css) - body_class note: ruby 1.9 required ## Usage: ## DataMapper ### error_messages_for in your form view: error_messages_for :resource or error_messages_for @resource ### name url example: in your DM model add a name_url property property :name_url, String, length: 255 before :create do - self.name_url = generate_url_from_name + self.name_url = generate_url_from_name name end before create, the name_url will be generated to make your urls seo-friendly ## Sinatra helpers examples: link_to "Label", "/your/link" image_tag "/image/file.png" include_js "antani" #=> <script src='/js/antani.js' ...> include_css "antani" #=> <link href='/css/antani.css' ...> %body{ class: body_class } #=> "/" -> home, "/posts/1" -> "posts", etc. ### Paginable Usage: in your model add: require 'voidtools/dm/paginable' include Voidtools::Paginable in a controller (or similar): Model.paginate(page: params[:page]) in your view: .pagination pag: - Model.pages.times do |i| %a{ :href => "/path?page=#{i}" }= i+1 (optional) in your model: def self.per_page 20 end a simple stylesheet (sass): .pagination margin: 10px 20px a padding: 3px 6px background: #DDD a:hover background: #FFF ## Development ### Build & install git clone git://github.com/makevoid/voidtools.git cd voidtools; gem build voidtools.gemspec; gem install voidtools-x.x.x.gem ### Changelog v0.2.9 - added datamapper module autoload if DataMapper is defined v0.2.3 - first stable version, autoloads modules for sinatra and rails diff --git a/lib/voidtools/dm/name_url.rb b/lib/voidtools/dm/name_url.rb index f29c977..557a9f8 100644 --- a/lib/voidtools/dm/name_url.rb +++ b/lib/voidtools/dm/name_url.rb @@ -1,26 +1,20 @@ module Voidtools module NameUrl def generate_url_from_name(name) - name.gsub(/\./, '').gsub(/'|"/, ' ').gsub(/\s+/, '_').gsub(/_-_/, '_').downcase + name.gsub(/\./, '').gsub(/['"\/]/, ' ').gsub(/\s+/, '_').gsub(/_-_/, '_').downcase end - # TODO: try to embed this into the model - - # before :create do - # self.name_url = generate_url_from_name - # end - def generate_name_url nurl = generate_url_from_name update(name_url: nurl) end end class NameUrler def self.generate(klass, options={}) klass.all(options).each do |model| model.generate_name_url end end end end \ No newline at end of file diff --git a/spec/voidtools_spec.rb b/spec/voidtools_spec.rb index 03ef566..bbd7171 100644 --- a/spec/voidtools_spec.rb +++ b/spec/voidtools_spec.rb @@ -1,14 +1,40 @@ path = File.expand_path "../../", __FILE__ require 'dm-core' +require 'dm-sqlite-adapter' +require 'dm-migrations' require "#{path}/lib/voidtools" +DataMapper.setup :default, "sqlite://#{path}/tmp/voidtools.sql" + +class NameUrlStub + include DataMapper::Resource + include Voidtools::NameUrl + + property :id, Serial + property :name, String + property :name_url, String + + before :create do + self.name_url = generate_url_from_name name + end +end +DataMapper.finalize +DataMapper.auto_migrate! + describe Voidtools do it "should load DataMapper" do - class Resource + class DMResource include DataMapper::Resource + include Voidtools::NameUrl property :id, Serial property :name, String - include Voidtools::NameUrl + end + end + + describe NameUrlStub do + it "should generate name_url" do + stub = NameUrlStub.create(name: "asd asd") + stub.name_url.should == "asd_asd" end end end \ No newline at end of file
makevoid/voidtools
a147c22c20bb5b65e5b1881acc218c8498cf08e0
removed unresolved git diff
diff --git a/lib/voidtools/dm/name_url.rb b/lib/voidtools/dm/name_url.rb index 4ca6f21..f29c977 100644 --- a/lib/voidtools/dm/name_url.rb +++ b/lib/voidtools/dm/name_url.rb @@ -1,30 +1,26 @@ module Voidtools module NameUrl def generate_url_from_name(name) name.gsub(/\./, '').gsub(/'|"/, ' ').gsub(/\s+/, '_').gsub(/_-_/, '_').downcase end # TODO: try to embed this into the model # before :create do # self.name_url = generate_url_from_name # end -<<<<<<< HEAD -======= - ->>>>>>> f8377c0e7f2a4c11717a96590bfadaec0fdad5e8 def generate_name_url nurl = generate_url_from_name update(name_url: nurl) end end class NameUrler def self.generate(klass, options={}) klass.all(options).each do |model| model.generate_name_url end end end end \ No newline at end of file
makevoid/voidtools
f8377c0e7f2a4c11717a96590bfadaec0fdad5e8
changed api of url module
diff --git a/lib/voidtools/dm/name_url.rb b/lib/voidtools/dm/name_url.rb index dd860ff..cec0103 100644 --- a/lib/voidtools/dm/name_url.rb +++ b/lib/voidtools/dm/name_url.rb @@ -1,27 +1,27 @@ module Voidtools module NameUrl - def generate_url_from_name + def generate_url_from_name(name) name.gsub(/\./, '').gsub(/'|"/, ' ').gsub(/\s+/, '_').gsub(/_-_/, '_').downcase end - + # TODO: try to embed this into the model - + # before :create do # self.name_url = generate_url_from_name # end - - + + def generate_name_url nurl = generate_url_from_name update(name_url: nurl) end end class NameUrler def self.generate(klass, options={}) klass.all(options).each do |model| model.generate_name_url end end end end \ No newline at end of file diff --git a/spec/voidtools_spec.rb b/spec/voidtools_spec.rb new file mode 100644 index 0000000..03ef566 --- /dev/null +++ b/spec/voidtools_spec.rb @@ -0,0 +1,14 @@ +path = File.expand_path "../../", __FILE__ +require 'dm-core' +require "#{path}/lib/voidtools" + +describe Voidtools do + it "should load DataMapper" do + class Resource + include DataMapper::Resource + property :id, Serial + property :name, String + include Voidtools::NameUrl + end + end +end \ No newline at end of file
makevoid/voidtools
3f7982fb9ef5ce7c2d495316dab5ad94c1057d49
edited require, deleted rails
diff --git a/lib/voidtools.rb b/lib/voidtools.rb index 852adfa..8c5fa00 100644 --- a/lib/voidtools.rb +++ b/lib/voidtools.rb @@ -1,40 +1,38 @@ module Voidtools # namespace our plugin and inherit from Rails::Railtie # to get our plugin into the initialization process if defined?(Rails) class Railtie < Rails::Railtie # configure our plugin on boot. other extension points such # as configuration, rake tasks, etc, are also available initializer "voidtools.initialize" do |app| # subscribe to all rails notifications: controllers, AR, etc. # ActiveSupport::Notifications.subscribe do |*args| # event = ActiveSupport::Notifications::Event.new(*args) # puts "Voidrails - got notification: #{event.inspect}" # end - require 'voidtools/dm/form_helpers' + require 'voidtools/dm/datamapper' require 'voidtools/sinatra/tracking' ActiveSupport.on_load(:action_view) do module ApplicationHelper include Voidtools::FormHelpers include Voidtools::Tracking end end - # require 'voidtools/dm/name_url' - # require 'voidtools/dm/paginable' end end end @@path = File.expand_path "../", __FILE__ if defined?(Sinatra) require "#{@@path}/voidtools/sinatra/sinatra" end if defined?(DataMapper) require "#{@@path}/voidtools/dm/datamapper" end end diff --git a/lib/voidtools/rails/app_mixin.rb b/lib/voidtools/rails/app_mixin.rb deleted file mode 100644 index 17e8f9b..0000000 --- a/lib/voidtools/rails/app_mixin.rb +++ /dev/null @@ -1,8 +0,0 @@ -module Voidtools - module AppMixin - def not_found - #render template: "exceptions/not_found", status: :not_found - render file: "/public/404.html", layout: false, status: 404 - end - end -end \ No newline at end of file
makevoid/voidtools
562286aa0d45cc32945bb8b1c7ceddbe9fa1e77f
edited readme
diff --git a/README.md b/README.md index 561efbd..825d99e 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,46 @@ # Voidtools #### growing toolset for Rails 3 and Sinatra with DataMapper and HAML class and helper modules --- +### Install from RubyGems + + gem i voidtools + + ### DataMapper - form helpers: error_messages_for - name url - pagination ### Sinatra - view helpers - link_to - image tag - include_assets (include_js, include_css) note: ruby 1.9 required ## DataMapper ### error_messages_for in your form view: `error_messages_for :resource` or `error_messages_for @resource` ### Build & install -gem build voidtools.gemspec; gem install voidtools-0.2.3.gem + + git clone git://github.com/makevoid/voidtools.git + cd voidtools; + gem build voidtools.gemspec; gem install voidtools-x.x.x.gem ### Changelog v0.2.9 - added datamapper module autoload if DataMapper is defined v0.2.3 - first stable version, autoloads modules for sinatra and rails
makevoid/voidtools
eed116d0530d52c8b021eb2ea5aced26d5d9fdef
bumped to 0.2.9
diff --git a/lib/voidtools/version.rb b/lib/voidtools/version.rb index 9d30903..e16279f 100644 --- a/lib/voidtools/version.rb +++ b/lib/voidtools/version.rb @@ -1,3 +1,3 @@ module Voidtools - VERSION = "0.2.4" + VERSION = "0.2.9" end \ No newline at end of file diff --git a/voidtools.gemspec b/voidtools.gemspec index 0538d6c..2edff0c 100644 --- a/voidtools.gemspec +++ b/voidtools.gemspec @@ -1,19 +1,19 @@ path = File.expand_path("../lib", __FILE__) $:.unshift(path) unless $:.include?(path) require "voidtools/version" Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'voidtools' s.version = Voidtools::VERSION - s.summary = 'custom rails3 toolset - for dm+jquery+haml+warden setup' - s.description = 'custom rails3 toolset setup with helpers for: datamapper, jquery, haml and warden' + s.summary = 'handy toolset for sinatra and datamapper' + s.description = 'handy toolset for sinatra and datamapper - sinatra modules: tracking, view_helpers - datamapper modules: form_helpers, name_url, paginable' s.author = "Francesco 'makevoid' Canessa" s.email = '[email protected]' s.homepage = 'http://www.makevoid.com' s.rubyforge_project = 'voidtools' s.files = Dir['Readme.md', 'lib/**/*'] s.require_path = 'lib' end \ No newline at end of file
makevoid/voidtools
baad09155d74a4f19d660239f483417122208d37
added datamapper module autoload if DataMapper is defined
diff --git a/.gitignore b/.gitignore index 06de90a..e1da4f0 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -.bundle \ No newline at end of file +.bundle +.gem \ No newline at end of file diff --git a/README.md b/README.md index 2c5df9c..561efbd 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,38 @@ # Voidtools #### growing toolset for Rails 3 and Sinatra with DataMapper and HAML class and helper modules --- ### DataMapper - form helpers: error_messages_for - name url - pagination ### Sinatra - view helpers - link_to - image tag - include_assets (include_js, include_css) note: ruby 1.9 required ## DataMapper ### error_messages_for in your form view: `error_messages_for :resource` or `error_messages_for @resource` ### Build & install gem build voidtools.gemspec; gem install voidtools-0.2.3.gem + + +### Changelog + +v0.2.9 - added datamapper module autoload if DataMapper is defined +v0.2.3 - first stable version, autoloads modules for sinatra and rails diff --git a/lib/voidtools.rb b/lib/voidtools.rb index 024c943..852adfa 100644 --- a/lib/voidtools.rb +++ b/lib/voidtools.rb @@ -1,35 +1,40 @@ module Voidtools - + # namespace our plugin and inherit from Rails::Railtie # to get our plugin into the initialization process if defined?(Rails) class Railtie < Rails::Railtie - + # configure our plugin on boot. other extension points such # as configuration, rake tasks, etc, are also available initializer "voidtools.initialize" do |app| - + # subscribe to all rails notifications: controllers, AR, etc. # ActiveSupport::Notifications.subscribe do |*args| # event = ActiveSupport::Notifications::Event.new(*args) # puts "Voidrails - got notification: #{event.inspect}" # end require 'voidtools/dm/form_helpers' require 'voidtools/sinatra/tracking' ActiveSupport.on_load(:action_view) do module ApplicationHelper include Voidtools::FormHelpers include Voidtools::Tracking end end # require 'voidtools/dm/name_url' # require 'voidtools/dm/paginable' end end end - + + @@path = File.expand_path "../", __FILE__ + if defined?(Sinatra) - path = File.expand_path "../", __FILE__ - require "#{path}/voidtools/sinatra/sinatra" + require "#{@@path}/voidtools/sinatra/sinatra" + end + + if defined?(DataMapper) + require "#{@@path}/voidtools/dm/datamapper" end end diff --git a/lib/voidtools/dm/datamapper.rb b/lib/voidtools/dm/datamapper.rb new file mode 100644 index 0000000..483ad23 --- /dev/null +++ b/lib/voidtools/dm/datamapper.rb @@ -0,0 +1,3 @@ +require_relative "form_helpers" +require_relative "name_url" +require_relative "paginable" \ No newline at end of file
makevoid/voidtools
8c66592a782877ed15621857f652c9e84dcb3815
tracking autoloads
diff --git a/lib/voidtools/sinatra/sinatra.rb b/lib/voidtools/sinatra/sinatra.rb index bc76b43..6b430ca 100644 --- a/lib/voidtools/sinatra/sinatra.rb +++ b/lib/voidtools/sinatra/sinatra.rb @@ -1,2 +1,11 @@ path = File.expand_path "../", __FILE__ -require "#{path}/view_helpers" \ No newline at end of file +require "#{path}/view_helpers" + +require "#{path}/tracking" +module Voidtools + module Sinatra + module ViewHelpers + include Tracking + end + end +end \ No newline at end of file
makevoid/voidtools
117e2e401ea3a543ec60992f3e0158467a1bdf8b
added multi domain support to analytics tracking
diff --git a/lib/voidtools/sinatra/tracking.rb b/lib/voidtools/sinatra/tracking.rb index 8d65ce7..ffbaeda 100644 --- a/lib/voidtools/sinatra/tracking.rb +++ b/lib/voidtools/sinatra/tracking.rb @@ -1,83 +1,88 @@ # Voidtools::Tracking # --------------------------------------------- # Setup: # # put these lines in your app_helper.rb: # # require 'voidtools/sinatra/tracking' # include Voidtools::Tracking # Usage: # # :javascript # #{crazyegg} # #{gauges("id")} module Voidtools module Tracking def track_run(&block) if defined?(Rails) yield if Rails.env != "development" else yield if ENV["RACK_ENV"] != "development" end end - def analytics(id, domain) # before the end of head tag + def analytics(id, *domains) # before the end of head tag + # FIXME: try with multiple domains + # TODO: test case track_run do - <<-FUN + out = <<-FUN var _gaq = _gaq || []; - _gaq.push(['_setAccount', '#{id}']); - //_gaq.push(['_setDomainName', '.#{domain}']); + _gaq.push(['_setAccount', '#{id}']);FUN + domains.each do |domain| + out << " _gaq.push(['_setDomainName', '.#{domain}']);" + end + <<-FUN _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); FUN end end def mixpanel track_run do # ... end end def crazyegg # before the end of body tag track_run do <<-FUN setTimeout(function(){var a=document.createElement("script"); var b=document.getElementsByTagName('script')[0]; a.src=document.location.protocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0011/5433.js"; a.async=true;a.type="text/javascript";b.parentNode.insertBefore(a,b)}, 1); FUN end end def gauges(id) # before the end of body tag track_run do <<-FUN (function() { var t = document.createElement('script'); t.type = 'text/javascript'; t.async = true; t.id = 'gauges-tracker'; t.setAttribute('data-site-id', '#{id}'); t.src = '//secure.gaug.es/track.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(t, s); })(); FUN end end end end \ No newline at end of file