bitcoin-atm

bitcoin atm for pyc inc.

git clone https://9o.is/git/bitcoin-atm.git

commit 98041019198e8310ffc70afc5b168b680c4d8573
parent 3d45c9c069706a5dfee70f34cea3273cc517d898
Author: Jul <jul@9o.is>
Date:   Tue, 29 Jul 2014 10:19:22 -0400

update. does not compile

Diffstat:
Mbuild.config.js | 22+++++++++++++++++++++-
Mproject/Build.scala | 12+++++++++---
Mproject/BuildSettings.scala | 12++++++++----
Asrc/main/resources/application.conf | 20++++++++++++++++++++
Asrc/main/resources/btcwallet_keystore.jks | 0
Msrc/main/resources/props/default.props | 3+++
Msrc/main/scala/bootstrap/liftweb/Boot.scala | 18++++++++++++++++--
Asrc/main/scala/inc/pyc/chimera/bitcoin/BitcoinServices.scala | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/PriceTicker.scala | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/Wallet.scala | 44++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/service/BitStamp.scala | 47+++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/service/BitcoinExchange.scala | 48++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/service/BitcoinServiceActor.scala | 15+++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/service/BitcoinWallet.scala | 221+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/service/BlockChain.scala | 33+++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/service/HttpBitcoinService.scala | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/service/JsonRPC.scala | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/bitcoin/service/WsBitcoinService.scala | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dsrc/main/scala/inc/pyc/chimera/comet/BitStampActor.scala | 37-------------------------------------
Asrc/main/scala/inc/pyc/chimera/config/Machine.scala | 18++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/lycia/Lycia.scala | 47+++++++++++++++++++++++++++++++++++++++++++++++
Dsrc/main/scala/inc/pyc/chimera/snippet/AngularActorBridge.scala | 31-------------------------------
Asrc/main/scala/inc/pyc/chimera/snippet/ClientActorBridge.scala | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dsrc/main/scala/inc/pyc/chimera/snippet/PriceTicker.scala | 33---------------------------------
Asrc/main/scala/inc/pyc/chimera/snippet/PriceTickerComet.scala | 43+++++++++++++++++++++++++++++++++++++++++++
Asrc/main/scala/inc/pyc/chimera/snippet/RoundTripSnippet.scala | 32++++++++++++++++++++++++++++++++
Msrc/main/scala/inc/pyc/chimera/snippet/UtilSnips.scala | 12++++++++++++
Msrc/main/webapp/app/App.js | 26+++++++++++++++++++++++---
Msrc/main/webapp/app/controllers/Forms.js | 2+-
Asrc/main/webapp/img/bitcoin.png | 0
Dsrc/main/webapp/img/spinner.gif | 0
Msrc/main/webapp/index.html | 24+++++++++++++++++++++++-
Msrc/main/webapp/less/custom.less | 5+++++
Asrc/main/webapp/less/extras/angular-wizard.less | 185+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/main/webapp/less/overrides.less | 16++++++++--------
Dsrc/main/webapp/less/pages/about.less | 17-----------------
Dsrc/main/webapp/less/pages/index.less | 77-----------------------------------------------------------------------------
Dsrc/main/webapp/less/pages/locations.less | 85-------------------------------------------------------------------------------
Asrc/main/webapp/less/pages/qr-scanner-wizard.less | 14++++++++++++++
Msrc/main/webapp/less/styles.less | 14++++++++++----
Msrc/main/webapp/less/variables.less | 3++-
Msrc/main/webapp/templates-hidden/base-wrap.html | 13++++++++++---
Asrc/main/webapp/vendor/angular-qr-scanner.js | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/angular-wizard.js | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/alignpat.js | 280+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/bitmat.js | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/bmparser.js | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/datablock.js | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/databr.js | 325+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/datamask.js | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/decoder.js | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/detector.js | 414+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/errorlevel.js | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/findpat.js | 649+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/formatinf.js | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/gf256.js | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/gf256poly.js | 231+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/grid.js | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/qrcode.js | 319+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/rsdecoder.js | 179+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/test.html | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/jsqrcode/version.js | 262+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/main/webapp/vendor/underscore.min.js | 6++++++
63 files changed, 5819 insertions(+), 311 deletions(-)

diff --git a/build.config.js b/build.config.js @@ -56,9 +56,29 @@ module.exports = { * */ vendor_files: { js: [ + "<%= dirs.vendor %>/underscore.min.js", "<%= dirs.vendor %>/angular.min.js", + "<%= dirs.vendor %>/angular-wizard.js", "<%= dirs.vendor %>/ui-bootstrap-tpls.js", - "<%= dirs.vendor %>/liftAjax.js" + "<%= dirs.vendor %>/liftAjax.js", + "<%= dirs.vendor %>/jsqrcode/grid.js", + "<%= dirs.vendor %>/jsqrcode/version.js", + "<%= dirs.vendor %>/jsqrcode/detector.js", + "<%= dirs.vendor %>/jsqrcode/formatinf.js", + "<%= dirs.vendor %>/jsqrcode/errorlevel.js", + "<%= dirs.vendor %>/jsqrcode/bitmat.js", + "<%= dirs.vendor %>/jsqrcode/datablock.js", + "<%= dirs.vendor %>/jsqrcode/bmparser.js", + "<%= dirs.vendor %>/jsqrcode/datamask.js", + "<%= dirs.vendor %>/jsqrcode/rsdecoder.js", + "<%= dirs.vendor %>/jsqrcode/gf256poly.js", + "<%= dirs.vendor %>/jsqrcode/gf256.js", + "<%= dirs.vendor %>/jsqrcode/decoder.js", + "<%= dirs.vendor %>/jsqrcode/qrcode.js", + "<%= dirs.vendor %>/jsqrcode/findpat.js", + "<%= dirs.vendor %>/jsqrcode/alignpat.js", + "<%= dirs.vendor %>/jsqrcode/databr.js", + "<%= dirs.vendor %>/angular-qr-scanner.js" ], css: [ ], diff --git a/project/Build.scala b/project/Build.scala @@ -9,10 +9,16 @@ object LiftProjectBuild extends Build { .settings(liftAppSettings: _*) .settings(libraryDependencies ++= Seq( - "net.liftweb" %% "lift-webkit" % Ver.lift % "compile", - "net.liftmodules" %% ("extras_"+Ver.lift_edition) % "0.4-SNAPSHOT" % "compile", + "net.liftweb" %% "lift-webkit" % Ver.lift, + "net.liftmodules" %% ("extras_"+Ver.lift_edition) % "0.4-SNAPSHOT", + "com.typesafe.akka" %% "akka-actor" % "2.3.3", + "com.typesafe.akka" %% "akka-agent" % "2.3.3", + "net.databinder.dispatch" %% "dispatch-core" % "0.11.1", + "net.databinder.dispatch" %% "dispatch-lift-json" % "0.11.0", + "com.markgoldenstein" %% "bitcoin-akka" % "0.1-SNAPSHOT", + "com.palletops" % "java-websocket" % "1.3.1-SNAPSHOT", "org.eclipse.jetty" % "jetty-webapp" % Ver.jetty % "container", - "ch.qos.logback" % "logback-classic" % "1.0.13" % "compile", + "ch.qos.logback" % "logback-classic" % "1.0.13", "org.scalatest" %% "scalatest" % "1.9.2" % "test" ) ) diff --git a/project/BuildSettings.scala b/project/BuildSettings.scala @@ -9,7 +9,7 @@ import ohnosequences.sbt.SbtS3Resolver._ object BuildSettings { object Ver { - val lift = "3.0-M0" + val lift = "3.0-M1" val lift_edition = "3.0" val jetty = "9.1.4.v20140401" } @@ -49,15 +49,19 @@ object BuildSettings { name := "chimera", version := "0.1-SNAPSHOT", organization := "inc.pyc", - scalaVersion := "2.10.3", + scalaVersion := "2.10.4", scalacOptions <<= scalaVersion map { sv: String => if (sv.startsWith("2.10.")) Seq("-deprecation", "-unchecked", "-feature", "-language:postfixOps", "-language:implicitConversions") else Seq("-deprecation", "-unchecked") }, - resolvers += "Sonatype Releases" at "http://oss.sonatype.org/content/repositories/releases", - resolvers += "Sonatype Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots" + resolvers ++= Seq[Resolver]( + "Sonatype Releases" at "http://oss.sonatype.org/content/repositories/releases", + "Sonatype Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots", + s3resolver.value("PYC Snapshots", s3("snapshots-pyc-inc")), + "clojars.org" at "http://clojars.org/repo" + ) ) val gruntSettings = Seq( diff --git a/src/main/resources/application.conf b/src/main/resources/application.conf @@ -0,0 +1,20 @@ + +btcwallet { + websocket-uri = "wss://pycbitcoin.com:8332/ws" + rpc-user = "jcabrra" + rpc-pass = "jcabrrarpcpass" + wallet-pass = "walletpass" + keystore-file = "src/main/resources/btcwallet_keystore.jks" + keystore-pass = "keystorepass" +} + +blockchain { + rpc-user = "{wallet login guid}" + rpc-pass = "{main wallet password}" + wallet-pass = "{second password}" +} + +akka { + loglevel = "DEBUG" + log-dead-letters = off +} diff --git a/src/main/resources/btcwallet_keystore.jks b/src/main/resources/btcwallet_keystore.jks Binary files differ. diff --git a/src/main/resources/props/default.props b/src/main/resources/props/default.props @@ -0,0 +1,2 @@ +# The machine's unique ID should be given as a param during execution. +# chimera.id +\ No newline at end of file diff --git a/src/main/scala/bootstrap/liftweb/Boot.scala b/src/main/scala/bootstrap/liftweb/Boot.scala @@ -2,12 +2,15 @@ package bootstrap.liftweb import inc.pyc.chimera.config._ import net.liftweb._ +import actor.LiftActor import common._ import http._ import util._ +import Helpers._ import net.liftmodules.extras.LiftExtras -import net.liftweb.sitemap._, Loc._ - +import net.liftweb.sitemap._ +import Loc._ +import inc.pyc.chimera.bitcoin.BitcoinServices /** * A class that's instantiated early and run. It allows the application @@ -47,5 +50,16 @@ class Boot extends Loggable { // don't include the liftAjax.js code. It's served statically. LiftRules.autoIncludeAjaxCalc.default.set(() => (session: LiftSession) => false) + + // Does the following at system shutdown + LiftRules.unloadHooks.append { + () => + import inc.pyc.chimera._ + import bitcoin.service._ + import lycia._ + + BitcoinServices.system.shutdown() + Lycia.system.shutdown() + } } } diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/BitcoinServices.scala b/src/main/scala/inc/pyc/chimera/bitcoin/BitcoinServices.scala @@ -0,0 +1,70 @@ +package inc.pyc.chimera +package bitcoin + +import lycia._ +import service._ +import akka.actor.{ActorSystem, Props} +import inc.pyc.chimera.snippet.LiftActorEventBus + +/** + * The different choices for bitcoin services. + */ +object BitcoinService extends Enumeration { + type BitcoinService = Value + val BitStamp, BlockChain, BtcWallet = Value + + def priceTickers: Map[BitcoinService, Props] = Map( + BitStamp -> Props[BitStamp], + BlockChain -> Props[BlockChain] + ) + + def wallets: Map[BitcoinService, Props] = Map( + //BtcWallet -> Props[BtcWallet], + BlockChain -> Props[BlockChain] + ) + + + def getPriceTicker(s: Value): Props = { + get(s, priceTickers) + } + + def getWallet(s: Value): Props = { + get(s, wallets) + } + + private def get(s: Value, m: Map[BitcoinService, Props]) = { + m.filter(_._1 == s).map(_._2).head + } +} + + +/** + * Command to change the bitcoin service provider. + */ +case class ChangeBitcoinService(service: BitcoinService.Value) + + +/** + * Main bitcoin actor services + */ +object BitcoinServices { + + /** + * Bitcoin services Actor System + */ + val system = ActorSystem("BitcoinServicesSystem") + + /** + * Event Bus for Bitcoin services. + */ + val bus = new LookupBitcoinServices +} + + +/** + * PubSub for Bitcoin services. + */ +class LookupBitcoinServices extends LiftActorEventBus { + // newPrice + override protected def mapSize: Int = 100 +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/PriceTicker.scala b/src/main/scala/inc/pyc/chimera/bitcoin/PriceTicker.scala @@ -0,0 +1,88 @@ +package inc.pyc.chimera +package bitcoin + +import lycia._ +import service._ +import snippet.EventUpdate +import akka.actor._ +import scala.concurrent._ +import duration._ +import ExecutionContext.Implicits._ + +/** + * Main object to access the buy price. + */ +object PriceTicker { + import BitcoinServices._ + + def !(x: Any): Unit = actor ! x + + /** + * The main actor that handles communications. + */ + private val actor = system.actorOf(Props[PriceTicker], "PriceTicker") + + /** + * The ticker that updates the price every 5 minutes. + */ + private val ticker = system.scheduler.schedule(0 milliseconds, 5 minutes, actor, Tick) + + /** + * Topics to subscribe to for event bus. + */ + object topics { + val newPrice = "newPrice" + } +} + +/** + * Bridge to access BitStamp information from snippet. + */ +class PriceTicker extends Actor { + import BitcoinServices._ + import BitcoinService._ + + /** The current service to use to check price. */ + var service: ActorRef = createServiceActor(Lycia.servicePriceTicker) + context.watch(service) + + /** Price per bitcoin */ + var price: String = "0.00" + + def receive = { + case Tick => + service ! Tick + + case Price(price) => + import PriceTicker._ + this.price = price + bus.publish(EventUpdate(topics.newPrice, Price(price))) + + case GossipPrice => + if(price == "0.00") self ! Tick + else self ! Price(price) + + case ChangeBitcoinService(provider) => + service ! Kill + service = createServiceActor(provider) + } + + private def createServiceActor(service: BitcoinService.Value): ActorRef = { + context.actorOf(getPriceTicker(service), service.toString) + } +} + +/** + * Price per bitcoin + */ +case class Price(price: String) + +/** + * Command to sends a broadcast of the buy price. + */ +case object GossipPrice + +/** + * Command to update the price per bitcoin. + */ +case object Tick +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/Wallet.scala b/src/main/scala/inc/pyc/chimera/bitcoin/Wallet.scala @@ -0,0 +1,43 @@ +package inc.pyc.chimera +package bitcoin + +import lycia._ +import service._ +import akka.actor._ +import akka.util._ +import scala.concurrent.duration._ + + +object Wallet { + import BitcoinServices._ + + def !(x: Any): Unit = actor ! x + + /** + * The main actor that handles communications. + */ + private val actor = system.actorOf(Props[Wallet], "BitcoinWallet") +} + +class Wallet extends BitcoinWallet { + import BitcoinServices._ + import BitcoinService._ + + implicit val timeout: Timeout = Timeout(5 seconds) + + /** The current service to use to check price. */ + var service: ActorRef = createServiceActor(Lycia.serviceWallet) + context.watch(service) + + def receive = { + + + case ChangeBitcoinService(provider) => + service ! Kill + service = createServiceActor(provider) + } + + private def createServiceActor(service: BitcoinService.Value): ActorRef = { + context.actorOf(getWallet(service), service.toString) + } +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/service/BitStamp.scala b/src/main/scala/inc/pyc/chimera/bitcoin/service/BitStamp.scala @@ -0,0 +1,46 @@ +package inc.pyc.chimera +package bitcoin +package service + +import lycia._ +import dispatch._, Defaults._ +import net.liftweb._ +import util.Helpers._ +import json._ +import akka.actor.ActorRef + +/** + * BitStamp REST services + * NOTE: Bitstamp is almost useless since it keeps asking for captcha -_- + */ +class BitStamp extends HttpBitcoinExchange { + import BitStamp._ + implicit val formats = DefaultFormats + + protected val api = :/ ("www.bitstamp.net").secure / "api" + + protected val ticker_api = api / "ticker" / "" + + protected def buyPrice: Future[Either[String, String]] = requestExtract(ticker_api, "price", { + json => tryo((json.extract[BitStampPrices]).last) + }) +} + +object BitStamp { + /** + * Different prices returned by BitStamp's API. + * + * Note: Currently not configurable. 'last' is default. + * + * last - last BTC price (BitStamp's Current Price) + * high - last 24 hours price high + * low - last 24 hours price low + * vwap - last 24 hours volume weighted average price + * volume - last 24 hours volume + * bid - highest buy order + * ask - lowest sell order + */ + case class BitStampPrices( + last: String, high: String, low: String, vwap: String, volume: String, + bid: String, ask: String, timestamp: String) +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/service/BitcoinExchange.scala b/src/main/scala/inc/pyc/chimera/bitcoin/service/BitcoinExchange.scala @@ -0,0 +1,47 @@ +package inc.pyc.chimera +package bitcoin +package service + +import lycia._ +import dispatch._, Defaults._ + +/** + * Bitcoin Exchange service to buy and sell bitcoin + */ +trait BitcoinExchange extends BitcoinServiceActor with BitcoinPriceTicker + +trait HttpBitcoinExchange extends HttpBitcoinService with HttpBitcoinPriceTicker + +/** + * A Bitcoin service with buy/sell prices. + */ +trait BitcoinPriceTicker extends BitcoinServiceActor + +trait HttpBitcoinPriceTicker extends HttpBitcoinService with BitcoinPriceTicker { + + /** + * Price ticker API + */ + protected val ticker_api: Req + + /** + * Gets the buy price + */ + protected def buyPrice: Future[Either[String, String]] + + def receive = { + case Tick => + val price = dispatch.retry.Backoff(10)(() => buyPrice) + price().left.map(log.error) + + price(). + right.map(formatPrice). + right.map{ + p => + log.info("Received price: {}", p) + sender ! Price(p) + } + } + + private def formatPrice(price: String): String = "%1.2f" format (price.toDouble) +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/service/BitcoinServiceActor.scala b/src/main/scala/inc/pyc/chimera/bitcoin/service/BitcoinServiceActor.scala @@ -0,0 +1,14 @@ +package inc.pyc.chimera +package bitcoin +package service + +import akka.actor._ +import akka.event._ + +/** + * Any Bitcoin Service Actor must be this. + */ +trait BitcoinServiceActor extends Actor { + protected val log = Logging(context.system, this) + protected val serviceName: String = this.getClass.getName.split("""\.""").last +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/service/BitcoinWallet.scala b/src/main/scala/inc/pyc/chimera/bitcoin/service/BitcoinWallet.scala @@ -0,0 +1,220 @@ +package inc.pyc.chimera +package bitcoin +package service + +import net.liftweb.json._ +import net.liftweb.util.Helpers.tryo +import JsonAST.JValue +import scala.collection._ +import scala.concurrent._ +import ExecutionContext.Implicits.global +import akka.util.Timeout +import akka.pattern.ask + +/** + * Actor to handle bitcoin wallet communications with JSON-RPC. + * Main Wallet Actor should have this and send commands to a child wallet that + * uses a wallet client service like BlockChain. + */ +trait BitcoinWallet extends BitcoinServiceActor with BitcoinJsonRPC { + + protected implicit val timeout: Timeout + + def walletPassPhrase(walletPass: String, timeout: BigDecimal) { + (self ! WalletPassPhrase(walletPass, timeout)) // give & forget + } + + def createRawTransaction(inputs: Seq[(String, BigDecimal)], receivers: Seq[(String, BigDecimal)]) = { + val r = (self ? CreateRawTransaction(inputs, receivers)).mapTo[String] + logme(r)("CreateRawTransaction"); r + } + + def listUnspentTransactions(minConfirmations: BigDecimal = 1, maxConfirmations: BigDecimal = 999999) = { + val r = (self ? ListUnspentTransactions(minConfirmations, maxConfirmations)).mapTo[Seq[UnspentTransaction]] + logme(r)("ListUnspentTransactions"); r + } + + def sendRawTransaction(signedTransaction: String) = { + val r = (self ? SendRawTransaction(signedTransaction)).mapTo[String] + logme(r)("SendRawTransaction"); r + } + + def getNewAddress(): Future[String] = { + val r = (self ? GetNewAddress).mapTo[String] + logme(r)("GetNewAddress"); r + } + + def getRawTransaction(transactionHash: String) = { + val r = (self ? GetRawTransaction(transactionHash)).mapTo[RawTransaction] + logme(r)("GetRawTransaction"); r + } + + def signRawTransaction(transaction: String): Future[SignedTransaction] = { + val r = (self ? SignRawTransaction(transaction)).mapTo[SignedTransaction] + logme(r)("SignRawTransaction"); r + } + + def validateAddress(address: String): Future[AddressValidation] = { + val r = (self ? ValidateAddress(address)).mapTo[AddressValidation] + logme(r)("ValidateAddress"); r + } + + private def logme(f: Future[_])(implicit cmd: String) { + f onFailure { case e => log.error("Command {} Failed: {}", cmd, e.getMessage()) } + f onSuccess { case r => + implicit val formats = DefaultFormats + log.debug("Command {} Success:\n{}", cmd, pretty(render(Extraction.decompose(r)))) + } + } +} + + +/** + * Actor to handle bitcoin wallet communications with JSON-RPC + * over Http. + */ +trait HttpBitcoinWallet extends HttpBitcoinService with BitcoinWallet { + import dispatch._ + import net.liftweb.util.Helpers.tryo + + override val headers = Map("Content-type" -> "application/json-rpc") + + override def receive = { + case CreateRawTransaction(inputs, receivers) => + val json = JsonMessage.createRawTransaction(inputs, receivers) + val res = requestExtract(post(json), "CreateRawTransaction", { + json => tryo(json.extract[String]) + }) + for(r <- res().right) yield { + + } + + case GetNewAddress => + val json = JsonMessage.getNewAddress + request(WsRequest(json.id, json, Some(json => { json.extract[String] }))) + + case GetRawTransaction(transactionHash) => + val json = JsonMessage.getRawTransaction(transactionHash) + request(WsRequest(json.id, json, Some(json => { json.extract[RawTransaction] }))) + + case ListUnspentTransactions(minConfirmations, maxConfirmations) => + val json = JsonMessage.listUnspentTransactions(minConfirmations, maxConfirmations) + request(WsRequest(json.id, json, Some(json => { json.extract[List[UnspentTransaction]] }))) + + case SendRawTransaction(signedTransaction) => + val json = JsonMessage.sendRawTransaction(signedTransaction) + request(WsRequest(json.id, json, Some(json => { json.extract[String] }))) + + case SignRawTransaction(transaction) => + val json = JsonMessage.signRawTransaction(transaction) + request(WsRequest(json.id, json, Some(json => { json.extract[SignedTransaction] }))) + + case WalletPassPhrase(walletPass, timeout) => + val json = JsonMessage.walletPassPhrase(walletPass, timeout) + request(WsRequest(json.id, json)) + + case ValidateAddress(address) => + val json = JsonMessage.validateAddress(address) + request(WsRequest(json.id, json, Some(json => { json.extract[AddressValidation] }))) + + } + + private def post(msg: JValue): Req = api << compact(render(msg)) +} + + +/** + * Actor to handle bitcoin wallet communications with JSON-RPC + * over WebSocket. + */ +trait WsBitcoinWallet extends WsBitcoinService with BitcoinWallet { + + /** + * Handles notifications incoming from server. + */ + protected def handleNotification: Receive + + + override def receive = { + case CreateRawTransaction(inputs, receivers) => + val json = JsonMessage.createRawTransaction(inputs, receivers) + requestExtract(json.id, json, "CreateRawTransaction", _.extract[String]) + + case GetNewAddress => + val json = JsonMessage.getNewAddress + requestExtract(json.id, json, "GetNewAddress", r => tryo(r.extract[String])) + + case GetRawTransaction(transactionHash) => + val json = JsonMessage.getRawTransaction(transactionHash) + requestExtract(json.id, json, "GetRawTransaction", _.extract[RawTransaction]) + + case ListUnspentTransactions(minConfirmations, maxConfirmations) => + val json = JsonMessage.listUnspentTransactions(minConfirmations, maxConfirmations) + requestExtract(json.id, json, "ListUnspentTransactions", r => tryo(r.extract[List[UnspentTransaction]])) + + case SendRawTransaction(signedTransaction) => + val json = JsonMessage.sendRawTransaction(signedTransaction) + requestExtract(json.id, json, "SendRawTransaction", r => tryo(r.extract[String])) + + case SignRawTransaction(transaction) => + val json = JsonMessage.signRawTransaction(transaction) + requestExtract(json.id, json, "SignRawTransaction", r => tryo(r.extract[SignedTransaction])) + + case WalletPassPhrase(walletPass, timeout) => + val json = JsonMessage.walletPassPhrase(walletPass, timeout) + requestForget(json) + + case ValidateAddress(address) => + val json = JsonMessage.validateAddress(address) + requestExtract(json.id, json, "", r => tryo(r.extract[AddressValidation])) + + case json @ JsonResponse(resultOption, errorOption, id) => + requests.remove(id).foreach(req => { + val (p: Promise[AnyRef], extract) = req + json.either.left.map(p tryFailure new RuntimeException(_)) + json.either.right.map(p trySuccess extract(_)) + }) + + case n: NotificationMessage => + handleNotification.applyOrElse(n, unhandled) + } + + /* + * Handles notifications incoming from server. + */ + private def handleResponseNotification: PartialFunction[JsonNotification, Unit] = { + + /* New Transaction */ + case JsonNotification(_, "newtx", params) => + for { + tx <- tryo(params(1).extract[TransactionNotification]) + if tx.category == "receive" + } self ! ReceivedPayment(tx.txid, tx.address, tx.amount, tx.confirmations) + + case _ => // ignore + } + + override def onMessage(msg: JValue) = () => { + + // messages should be either JsonNotification or JsonResponse + // only notifications have jsonrpc field. + def isNotification: Boolean = + (msg find { + case JField("jsonrpc", _) => true + case _ => false + }).isDefined + + if(isNotification) + tryo(msg.extract[JsonNotification]).map( + handleResponseNotification.applyOrElse(_, unhandled)) + else + tryo(msg.extract[JsonResponse]).map(self ! _) + } +} + + +/** + * Actor to handle bitcoin wallet communications with JSON-RPC + * over Secure WebSocket. + */ +trait WssBitcoinWallet extends WssBitcoinService with WsBitcoinWallet +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/service/BlockChain.scala b/src/main/scala/inc/pyc/chimera/bitcoin/service/BlockChain.scala @@ -0,0 +1,32 @@ +package inc.pyc.chimera +package bitcoin +package service + +import inc.pyc.chimera.lycia._ +import dispatch._, Defaults._ +import net.liftweb._ +import json._ +import akka.actor.ActorRef + +/** + * BlockChain REST services + */ +class BlockChain extends HttpBitcoinService with HttpBitcoinPriceTicker { + implicit val formats = DefaultFormats + + protected val api = :/ ("blockchain.info") + + protected val ticker_api = api / "ticker" + + protected def buyPrice: Future[Either[String, String]] = requestExtract(ticker_api, "price", { + json => + (for (JField("USD", usd) <- json) + yield compact(render(usd \ "last"))).headOption + }) +} + + +/** + * BlockChain WebSocket services + */ +//class BockChainWs extends +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/service/HttpBitcoinService.scala b/src/main/scala/inc/pyc/chimera/bitcoin/service/HttpBitcoinService.scala @@ -0,0 +1,54 @@ +package inc.pyc.chimera +package bitcoin +package service + +import dispatch._, Defaults._ +import net.liftweb.json.JsonAST.JValue +import java.net.ConnectException + +/** + * Bitcoin service over HTTP communications. + */ +abstract class HttpBitcoinService extends BitcoinServiceActor { + + /** + * Service's API + */ + protected val api: Req + + /** + * Request headers + */ + protected val headers: Map[String,String] = Map() + + /** + * Extracts a value from response given a request and an extractor handler. + */ + protected def requestExtract[T](req: Req, dataType: String, extractor: JValue => Option[T]): Future[Either[String, T]] = { + + def extract(json: JValue): Either[String, T] = { + extractor(json).toRight { + s"Can't extract $dataType from $serviceName response" + } + } + + for (jsonEither <- request(req)) + yield for { + json <- jsonEither.right + value <- extract(json).right + } yield value + } + + /** + * Request and get a json response. + */ + protected def request(req: Req): Future[Either[String, JValue]] = { + val res = (Http(req <:< headers > as.lift.Json).either) + + for (e <- res.left) + yield { + new ConnectException(s"Can't connect to $serviceName: ${e.getMessage}") + s"Can't connect to $serviceName: ${e.getMessage}" + } + } +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/service/JsonRPC.scala b/src/main/scala/inc/pyc/chimera/bitcoin/service/JsonRPC.scala @@ -0,0 +1,124 @@ +package inc.pyc.chimera +package bitcoin +package service + +import net.liftweb._ +import json.JsonAST._ + +sealed trait JsonMessage + +/** + * For more information, visit + * http://json-rpc.org/wiki/specification + */ +sealed trait JsonRPC { + implicit val formats = json.DefaultFormats + + // JSON-RPC MESSAGES + case class JsonNotification(jsonrpc: String, method: String, params: JArray) extends JsonMessage + case class JsonRequest(jsonrpc: String, id: String, method: String, params: JArray) extends JsonMessage + case class JsonResponse(result: Option[JValue], error: Option[JValue], id: String) extends JsonMessage { + def either: Either[String, JValue] = + (result, error) match { + case (Some(result), _) => Right(result) + case (_, Some(error)) => Left((error \ "message").extract[String]) + case _ => Left("Unknown response") + } + } + + // JsonMessage to JValue implicits + implicit def jsonRequestToJValue(m: JsonRequest): JValue = m.extract[JsonRequest] +} + +trait WalletMessage +trait NotificationMessage extends WalletMessage + +/** + * For more information, visit + * https://en.bitcoin.it/wiki/API_reference_(JSON-RPC) + */ +trait BitcoinJsonRPC extends JsonRPC { + + // BITCOIN TRANSACTIONS + case class RawTransaction(hex: String, txid: String, version: BigDecimal, locktime: BigDecimal, vin: Seq[VIn], vout: Seq[VOut]) + case class VIn(txid: String, vout: Int, scriptSig: ScriptSig, sequence: BigDecimal) + case class VOut(value: BigDecimal, n: BigDecimal, scriptPubKey: ScriptPubKey) + case class ScriptSig(asm: String, hex: String) + case class ScriptPubKey(asm: String, hex: String, reqSigs: BigDecimal, `type`: String, addresses: Seq[String]) + case class UnspentTransaction(txid: String, account: String, address: String, amount: BigDecimal, confirmations: BigDecimal) + case class SignedTransaction(hex: String, complete: Boolean) + case class TransactionNotification(txid: String, account: String, address: String, + category: String, amount: BigDecimal, confirmations: BigDecimal, timereceived: BigDecimal) + + // OTHER BITCOIN MESSAGES + case class AddressValidation(isvalid: Boolean, address: Option[String], + ismine: Option[Boolean], pubkey: Option[String], iscompressed: Option[Boolean]) + + // ACTOR MESSAGES + // notifications + case class ReceivedPayment(txId: String, address: String, amount: BigDecimal, confirmations: BigDecimal) extends NotificationMessage + + // requests + sealed trait RequestMessage extends WalletMessage + case class CreateRawTransaction(inputs: Seq[(String, BigDecimal)], receivers: Seq[(String, BigDecimal)]) extends RequestMessage + case object GetNewAddress extends RequestMessage + case class GetRawTransaction(transactionHash: String) extends RequestMessage + case class ListUnspentTransactions(minConfirmations: BigDecimal = 1, maxConfirmations: BigDecimal = 999999) extends RequestMessage + case class SendRawTransaction(signedTransaction: String) extends RequestMessage + case class SignRawTransaction(transaction: String) extends RequestMessage + case class WalletPassPhrase(walletPass: String, timeout: BigDecimal) extends RequestMessage + case class ValidateAddress(address: String) extends RequestMessage + + /** + * Constructs JSON-RPC messages out of the existing actor messages related + * to Bitcoin's standard rpc-json commands. + */ + object JsonMessage { + def createRawTransaction(inputs: Seq[(String, BigDecimal)], receivers: Seq[(String, BigDecimal)]) = + JsonRequest("1.0", Utils.getUUID, "createrawtransaction", JArray( + inputs.map(i => JObject(List("txid" -> i._1, "vout" -> i._2))).toList :: + receivers.map(r => JObject(List(r._1 -> r._2))).toList)) + + def getNewAddress = + JsonRequest("1.0", Utils.getUUID, "getnewaddress", Seq()) + + def getRawTransaction(transactionHash: String) = + JsonRequest("1.0", Utils.getUUID, "getrawtransaction", JArray(List(transactionHash, 1))) + + def listUnspentTransactions(minConfirmations: BigDecimal, maxConfirmations: BigDecimal, addresses: Seq[String] = Seq.empty[String]) = { + val params = + if (addresses.isEmpty) JArray(List(minConfirmations, maxConfirmations)) + else JArray(List(minConfirmations, maxConfirmations, addresses)) + JsonRequest("1.0", Utils.getUUID, "listunspent", params) + } + + def sendRawTransaction(signedTransaction: String) = + JsonRequest("1.0", Utils.getUUID, "sendrawtransaction", Seq(signedTransaction)) + + def signRawTransaction(transaction: String) = + JsonRequest("1.0", Utils.getUUID, "signrawtransaction", Seq(transaction)) + + def walletPassPhrase(walletPass: String, timeout: BigDecimal) = + JsonRequest("1.0", Utils.getUUID, "walletpassphrase", JArray(List(walletPass, timeout))) + + def validateAddress(address: String) = + JsonRequest("1.0", Utils.getUUID, "validateaddress", Seq(address)) + } + + private object Utils { + def getUUID = java.util.UUID.randomUUID.toString + } + + // JValue implicits + implicit def intToJInt(i: Int): JInt = JInt(i) + implicit def stringToJString(s: String): JString = JString(s) + implicit def stringToJField(m: (String, String)): JField = JField(m._1, m._2) + + // BigDecimal to JValue implicits + implicit def bigdecimalToJField(m: (String, BigDecimal)): JField = JField(m._1, m._2) + implicit def bigdecimalToJDouble(d: BigDecimal): JDouble = JDouble(d.doubleValue) + + // Scala collections to JArray implicits + implicit def listToJArray(l: List[JValue]): JArray = JArray(l) + implicit def seqStringToJArray(l: Seq[String]): JArray = JArray(l.map(JString).toList) +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/bitcoin/service/WsBitcoinService.scala b/src/main/scala/inc/pyc/chimera/bitcoin/service/WsBitcoinService.scala @@ -0,0 +1,194 @@ +package inc.pyc.chimera +package bitcoin +package service + +import java.net.{URI, ConnectException} +import concurrent._ +import duration._ +import collection._ +import collection.JavaConversions._ +import ExecutionContext.Implicits.global +import scala.util.{Success, Failure} +import akka.actor._ +import akka.pattern._ +import akka.util._ +import net.liftweb.json._ +import JsonAST.JValue +import org.java_websocket._ +import client._ +import handshake._ +import drafts._ + +/** + * Bitcoin service over WebSocket communications. + */ +abstract class WsBitcoinService extends BitcoinServiceActor { + + protected implicit val timeout: Timeout + + /** + * Service's API + */ + protected val api: URI + + /** + * Handle json messages sent from server. + */ + protected def onMessage(msg: JValue): () => Unit + + /** + * Request headers + */ + protected val headers: Map[String,String] = Map() + + /** + * Maps request IDs to the corresponding response promises + * and a function that converts the JSON RPC response to the final actor response. + */ + protected val requests = mutable.HashMap.empty[String, (Promise[AnyRef], JValue => _)] + + /** + * Executes on websocket initial connection. + */ + protected def onConnect: () => Unit = () => {} + + /** + * Request and forget. + */ + protected def requestForget(req: JValue): Unit = { + request(req) + } + + /** + * Request and extract promised json response. + * Note: Must be an actor making the request to receive response. + */ + protected def requestExtract[T](id: String, req: JValue, dataType: String, extractor: JValue => T): Unit = { + + val p = Promise[AnyRef]() + val f = p.future + requests += id -> (p, extractor) + request(req) + + context.system.scheduler.scheduleOnce(timeout.duration) { + p tryFailure { + new TimeoutException(s"Timeout: $serviceName bitcoin wallet did not respond in time") + } + self ! RemoveWsRequest(id) + } + + pipe(f) to sender + } + + override def preStart(): Unit = { + context.become(connecting) + tryToConnect() + } + + /** + * Receive when disconnected. + */ + def connecting: Receive = { + case Connected => + context.become(receive) + onConnect() + + case msg => + context.system.scheduler.scheduleOnce(1 second, self, msg) + } + + /** + * Receive when connected. + */ + def receive = { + case RemoveWsRequest(id) => + requests -= id + + case Disconnected(reason) => + log.warning("Connection to {} bitcoin wallet closed: {}", serviceName, reason) + context.become(connecting) + tryToConnect() + } + + /** + * Tries to connect to the websocket. + * @param f function to manipulate the websocket object before trying to connect. + */ + protected def tryToConnect(f: WebSocketBtcWalletClient => WebSocketBtcWalletClient = walletClient => walletClient) { + requests.clear() + walletClient = new WebSocketBtcWalletClient(api, new Draft_17, headers, 0) + walletClient = f(walletClient) + val connected = walletClient.connectBlocking() + + if (connected) { + log.info("Connection to {} bitcoin wallet established", serviceName) + self ! Connected + } else { + new ConnectException(s"$serviceName bitcoin wallet not available: $api") + } + } + + /* Send request down websocket. */ + private def request(req: JValue) { walletClient.send(compact(render(req))) } + + /* Personal websocket class of the java-websocket library. */ + class WebSocketBtcWalletClient(serverUri: URI, protocolDraft: Draft, httpHeaders: Map[String, String], connectTimeout: Int) + extends WebSocketClient(serverUri, protocolDraft, headers, connectTimeout) { + override def onMessage(jsonMessage: String): Unit = { ws.onMessage(parse(jsonMessage)) } + override def onOpen(handshakeData: ServerHandshake) { } + override def onClose(code: Int, reason: String, remote: Boolean) { self ! Disconnected(reason) } + override def onError(ex: Exception) { self ! Disconnected(ex.getMessage()) } + } + + /* The actual websocket. */ + protected var walletClient: WebSocketBtcWalletClient = null + + /* Used by the websocket class to access actor methods with same name. */ + private def ws = this + + /* Websocket Messages */ + case object Connected + case class Disconnected(reason: String) + case class RemoveWsRequest(id: String) +} + +/** + * Bitcoin service over WebSocket communications with SSL. + */ +trait WssBitcoinService extends WsBitcoinService { + import java.io._ + import java.security._ + import javax.net.ssl._ + + /** + * KeyStore file containing trusted certificates. + */ + val keyStoreFile: File + + /** + * Password of the KeyStore `keyStoreFile` + */ + val keyStorePass: String + + private val socketFactory = createSslSocketFactory + + override def tryToConnect(f: WebSocketBtcWalletClient => WebSocketBtcWalletClient = walletClient => walletClient) = + super.tryToConnect( walletClient => { + walletClient.setSocket(socketFactory.createSocket()) + walletClient + }) + + /** + * Creates a ssl socket factory for the websocket using the + * given keystore file and password. + */ + private def createSslSocketFactory: SSLSocketFactory = { + val ks = KeyStore.getInstance("JKS") + ks.load(new FileInputStream(keyStoreFile), keyStorePass.toCharArray) + val tmf = TrustManagerFactory.getInstance("SunX509") + tmf.init(ks) + val sslContext = SSLContext.getInstance("TLS") + sslContext.init(null, tmf.getTrustManagers, null) + sslContext.getSocketFactory + } +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/comet/BitStampActor.scala b/src/main/scala/inc/pyc/chimera/comet/BitStampActor.scala @@ -1,36 +0,0 @@ -package inc.pyc.chimera -package comet - -import net.liftweb._ -import http._ -import actor._ -import util._, Helpers._ - -object BitStampSettings extends Factory { - - /** Price per bitcoin */ - val price = new FactoryMaker[Float](0) {} -} - -/** - * Bridge to access BitStamp information from snippet. - */ -object BitStampActor extends LiftActor with ListenerManager { - - protected def createUpdate = "" - - override def lowPriority = { - - case UpdatePrice => - // TODO get price from bitstamp - val price = Price(234.12f) - updateListeners(price) - Schedule.schedule(this, UpdatePrice, 10 minutes) - } -} - -/** Price per bitcoin */ -case class Price(price: Float) - -/** Command to update the price per bitcoin. */ -case object UpdatePrice -\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/config/Machine.scala b/src/main/scala/inc/pyc/chimera/config/Machine.scala @@ -0,0 +1,17 @@ +package inc.pyc.chimera +package config + +import lycia._ +import akka.agent._ +import akka.actor.ActorSystem +import concurrent._ +import ExecutionContext.Implicits.global +import net.liftweb.util.Props + +object Machine { + + implicit val system = ActorSystem("MachineConfig") + + val id = Agent(Props.get("chimera.id", "default")) + val name = Agent(Lycia.machineName) +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/lycia/Lycia.scala b/src/main/scala/inc/pyc/chimera/lycia/Lycia.scala @@ -0,0 +1,46 @@ +package inc.pyc.chimera +package lycia + +import config._ +import bitcoin.service._ +import akka.actor._ +import akka.event._ +import inc.pyc.chimera.bitcoin.BitcoinService + +object Lycia { + + def !(x: Any): Unit = actor ! x + + /** + * Lycia Actor System + */ + val system = ActorSystem("LyciaSystem") + + /** + * The main actor that handles communications. + */ + private val actor = system.actorOf(Props[Lycia], "Lycia") + + def machineName: String = { + // get name of machine with given name + Machine.id() + "" + } + + def servicePriceTicker: BitcoinService.Value = { + // TODO get service configured + BitcoinService.BlockChain + } + + def serviceWallet: BitcoinService.Value = { + // TODO get service configured + BitcoinService.BlockChain + } +} + +class Lycia extends Actor { + + val log = Logging(context.system, this) + + +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/snippet/AngularActorBridge.scala b/src/main/scala/inc/pyc/chimera/snippet/AngularActorBridge.scala @@ -1,30 +0,0 @@ -package inc.pyc.chimera -package snippet - -import scala.xml._ -import net.liftweb._ -import common._ -import actor._ -import http._ -import js._ -import JE._ -import JsCmds._ -import net.liftmodules.extras.JsExtras - -trait AngularActorBridge extends Logger { - - protected def connectActorBridge(clientFunc: String, in: NodeSeq, f: (LiftSession, LiftActor) => ScopedLiftActor): NodeSeq = - (for { - sess <- S.session - } yield { - val clientProxy = sess.serverActorForClient("window.actorsBridge."+clientFunc) - - val serverActor: ScopedLiftActor = f(sess, clientProxy) - - S.appendJs(SetExp(JsVar("window.actorsBridge"), - JsExtras.CallNew("window.ActorsBridge", sess.clientActorFor(serverActor)) )) - - in - }) openOr NodeSeq.Empty - -} -\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/snippet/ClientActorBridge.scala b/src/main/scala/inc/pyc/chimera/snippet/ClientActorBridge.scala @@ -0,0 +1,102 @@ +package inc.pyc.chimera +package snippet + +import scala.xml._ +import net.liftweb._ +import common._ +import actor._ +import http._ +import js._ +import JE._ +import JsCmds._ +import json._, Extraction.decompose +import net.liftmodules.extras.JsExtras +import akka.event.{EventBus, LookupClassification} + +/** + * Lift snippet to initiate a comet actor that subscribes to a + * topic in an Akka event bus system. Client-side javascript Actor + * Bridge must have a function with the topic name to receive updates. + */ +class EventRegister(bus: LiftActorEventBus, topics: (String, () => Unit)*) + extends ClientEventPushBridge with ImplicitSnip { + + def render(in: NodeSeq): NodeSeq = topics map (x => connectActorBridge(bus, x._1, x._2, in)) +} + +/** + * Bridge to push messages from akka's event bus system to Actor Bridge in javascript. + * + * The topic being listened client-side should be the same as the + * topic in the event bus server-side. + */ +trait ClientEventPushBridge extends ClientActorBridge { + + protected def connectActorBridge(bus: LiftActorEventBus, topic: String, postSubscribe: () => Unit, in: NodeSeq): NodeSeq = + super.connectActorBridge(topic, in, { + (session, clientProxy) => + + val serverActor = new ScopedLiftActor with LiftActorCompare { + override def lowPriority = { + case payload => + clientProxy ! payload + } + } + + bus.subscribe(serverActor, topic) + postSubscribe() + serverActor + }) +} + +/** + * The bridge between ActorBridge in javascript and server-side actors. + */ +trait ClientActorBridge extends Logger { + + /** + * Connects a given `ScopedLiftActor` to the given function name listening from + * the client-side Actor Bridge. + */ + protected def connectActorBridge(topic: String, in: NodeSeq, f: (LiftSession, LiftActor) => ScopedLiftActor): NodeSeq = + (for (sess <- S.session) yield { + val clientProxy = sess.serverActorForClient("window.actorsBridge."+topic) + + val serverActor: ScopedLiftActor = f(sess, clientProxy) + //val className: String = this.getClass.getName.split("""\.""").last + + S.appendJs(SetExp(JsVar("window.actorsBridge"), + JsExtras.CallNew("window.ActorsBridge", sess.clientActorFor(serverActor)) )) + + in + }) openOr NodeSeq.Empty + +} + + +/** + * Message to update `LiftActorEventBus`. + */ +case class EventUpdate(topic: String, payload: Any) + +/** + * Bridge between Akka's event bus and Lift actors. + */ +abstract class LiftActorEventBus extends EventBus with LookupClassification { + type Event = EventUpdate + type Classifier = String + type Subscriber = LiftActorCompare + + override protected def classify(event: Event): Classifier = event.topic + + override protected def publish(event: Event, subscriber: Subscriber): Unit = { + subscriber ! event.payload + } + + override protected def compareSubscribers(a: Subscriber, b: Subscriber): Int = + a.compareTo(b) +} + +sealed trait LiftActorCompare extends LiftActor with java.lang.Comparable[LiftActor] { + override def compareTo(a: LiftActor): Int = -1 +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/snippet/PriceTicker.scala b/src/main/scala/inc/pyc/chimera/snippet/PriceTicker.scala @@ -1,32 +0,0 @@ -package inc.pyc.chimera -package snippet - -import comet._ -import xml._ -import net.liftweb._ -import json.JsonAST._ -import http._ -import net.liftmodules.extras._ - -/** - * Snippet to update the price ticker on screen. - */ -class PriceTicker extends AngularActorBridge { - - def render(in: NodeSeq): NodeSeq = connectActorBridge("newPrice", in, { - (session, clientProxy) => - - val serverActor = new ScopedLiftActor { - override def lowPriority = { - case Price(price) => - clientProxy ! JString(price.toString) - } - } - - BitStampActor ! AddAListener(serverActor, {case _ => true}) - BitStampActor ! UpdatePrice - - serverActor - }) - -} -\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/snippet/PriceTickerComet.scala b/src/main/scala/inc/pyc/chimera/snippet/PriceTickerComet.scala @@ -0,0 +1,42 @@ +package inc.pyc.chimera +package snippet + +import bitcoin._ +import service._ +import xml._ +import net.liftweb._ +import http._ +import json.JsonAST._ +import inc.pyc.chimera.bitcoin.BitcoinServices + +/** + * Snippet to update the price ticker on screen. + */ +class PriceTickerComet extends EventRegister(BitcoinServices.bus, + (PriceTicker.topics.newPrice, () => { PriceTicker ! GossipPrice })) { + + override def render(o: NodeSeq): NodeSeq = { + super.render(o) + } +} + +class BitcoinAddressScanner extends RoundTripSnippet { + + def roundTrips: List[RoundTripInfo] = List("submitAddress" -> submitAddress _) + + def submitAddress(json: JValue): JValue = + for { + JString(address) <- json + } yield { + + // TODO check if string is valid bitcoin address + // TODO check website database if address exists + // TODO check if address is owned by a user + + // TODO return a message + + JNull + } + + case class BtcAddressMsg() extends MsgData +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/snippet/RoundTripSnippet.scala b/src/main/scala/inc/pyc/chimera/snippet/RoundTripSnippet.scala @@ -0,0 +1,31 @@ +package inc.pyc.chimera +package snippet + +import xml._ +import net.liftweb._ +import http._ +import common._ +import js._ +import JE._ +import JsCmds._ +import json.JsonAST._ + +/** + * Shortcut to build lift roundtrips using the pattern 'window.classname' javascript object. + */ +trait RoundTripSnippet { + implicit def boxedJValueToJValue(in: Box[JValue]): JValue = in openOr JNull + implicit def listJValueToJValue(in: List[JValue]): JValue = in.headOption.getOrElse(JNull) + + def roundTrips: List[RoundTripInfo] + + def render(in: NodeSeq): NodeSeq = { + for (sess <- S.session) yield { + val roundtrips = sess.buildRoundtrip(roundTrips) + val className: String = (RoundTripSnippet.this.getClass.getName.split("""\.""")).last + val script = SetExp(JsVar("window", className), roundtrips) + S.appendGlobalJs(script) + } + in + } +} +\ No newline at end of file diff --git a/src/main/scala/inc/pyc/chimera/snippet/UtilSnips.scala b/src/main/scala/inc/pyc/chimera/snippet/UtilSnips.scala @@ -12,4 +12,16 @@ object ProductionOnly { def render(in: NodeSeq): NodeSeq = if (Props.productionMode) in else NodeSeq.Empty +} + +/* + * This is used to send messages to client. + */ +case class Message(msg_type: String, msg: Option[String] = None, data: Option[MsgData] = None) + +trait MsgData + + +trait ImplicitSnip { + implicit def seqNodeSeqToNodeSeq(in: Seq[NodeSeq]): NodeSeq = in.headOption.getOrElse(NodeSeq.Empty) } \ No newline at end of file diff --git a/src/main/webapp/app/App.js b/src/main/webapp/app/App.js @@ -1,7 +1,7 @@ /** * Main Angular Module */ -var app = angular.module("app", ['ui.bootstrap', 'Forms', 'disabler']); +var app = angular.module("app", ['ui.bootstrap', 'mgo-angular-wizard', 'angular-qr-scanner', 'Forms', 'disabler']); /** * Button display 'loading' (with a spinner) during ajax. @@ -27,12 +27,32 @@ app.directive('disabler', ['$compile', function($compile) { /** * Price Ticker shows price per bitcoin. */ -app.controller('PriceTickerCtrl', ['$scope', '$rootScope', function($scope, $rootScope) { +app.controller('PriceTickerCtrl', ['$scope', '$rootScope', function($scope, $rootScope) { $rootScope.$on("new-price", function (event, message) { - $scope.price = message; + $scope.price = message.price; }); }]); +app.controller('WalletScannerCtrl', ['$scope', function($scope) { + + $scope.onSuccess = function(data) { + if (data !== 'error decoding QR Code') { + window.console.log("QR Data:"+data); + // TODO handle data here + } + }; + + $scope.onError = function(error) { + window.console.log("QR Error: "+error); + // TODO log it in redis + }; + + $scope.onVideoError = function(error) { + window.console.log("QR Video Error: "+error); + // TODO log it in redis + }; +}]); + /** * User registration form controller. */ diff --git a/src/main/webapp/app/controllers/Forms.js b/src/main/webapp/app/controllers/Forms.js @@ -5,7 +5,7 @@ * Included ngAlert as dependency since Forms module checks the success * of the message using ngAlert's message formatting. */ -angular.module("Forms", ['ngAlert']) +angular.module("Forms", []) /** * Simple form controller with helper functions like submit diff --git a/src/main/webapp/img/bitcoin.png b/src/main/webapp/img/bitcoin.png Binary files differ. diff --git a/src/main/webapp/img/spinner.gif b/src/main/webapp/img/spinner.gif Binary files differ. diff --git a/src/main/webapp/index.html b/src/main/webapp/index.html @@ -1,3 +1,25 @@ <div data-lift="surround?with=base-default;at=content"> - <p>HELLO!</p> + +<wizard id="wizard-main" on-finish="finishedWizard()" ng-cloak> + <wz-step title="Start"> + <a type="submit" wz-next class="no-design"> + <h1>Buy bitcoin</h1> + <img src="/img/bitcoin.png" width="350" /> + <p class="lead">Tap on the bitcoin to get started</p> + </a> + </wz-step> + <wz-step title="Scan Wallet"> + <h1>Scan your Bitcoin Wallet - QR Code</h1> + + <div id="wallet-scanner" ng-controller="WalletScannerCtrl"> + <qr-scanner ng-success="onSuccess(data)" width="400" height="300"></qr> + </div> + </wz-step> + <wz-step title="More steps"> + <h1>More Steps</h1> + <p>Even more steps!!</p> + <input type="submit" wz-next value="Finish now" class="btn btn-primary" /> + </wz-step> +</wizard> + </div> \ No newline at end of file diff --git a/src/main/webapp/less/custom.less b/src/main/webapp/less/custom.less @@ -158,4 +158,9 @@ h1,h2,h3,h4,h5,h6,h7 { &.bold { font-weight: @headings-font-weight + 100; } +} + +a.no-design { + color: @text-color !important; + text-decoration: none !important; } \ No newline at end of file diff --git a/src/main/webapp/less/extras/angular-wizard.less b/src/main/webapp/less/extras/angular-wizard.less @@ -0,0 +1,184 @@ + +#wizard-main { + height: 600px; // TODO issue #2 +} + +.steps-indicator { + /* ---- steps quantity ---- */ + + @color-default: #E6E6E6; + @color-current: #808080; + @color-done: #339933; + @color-editing: #FF0000; + + position: absolute; + right: 0; + bottom: 0; + left: 0; + margin: 0; + padding: 0; + height: 30px; + list-style: none; + + + + &:before { + background-color: @color-default; + content: ''; + position: absolute; + height: 1px; + } + + &.steps-2:before { + left: ~'calc(100% / 2 / 2)'; + right: ~'calc(100% / 2 / 2)'; + } + + &.steps-3:before { + left: ~'calc(100% / 3 / 2)'; + right: ~'calc(100% / 3 / 2)'; + } + + &.steps-4:before { + left: ~'calc(100% / 4 / 2)'; + right: ~'calc(100% / 4 / 2)'; + } + + &.steps-5:before { + left: ~'calc(100% / 5 / 2)'; + right: ~'calc(100% / 5 / 2)'; + } + + &.steps-6:before { + left: ~'calc(100% / 6 / 2)'; + right: ~'calc(100% / 6 / 2)'; + } + + &.steps-7:before { + left: ~'calc(100% / 7 / 2)'; + right: ~'calc(100% / 7 / 2)'; + } + + &.steps-8:before { + left: ~'calc(100% / 8 / 2)'; + right: ~'calc(100% / 8 / 2)'; + } + + &.steps-9:before { + left: ~'calc(100% / 9 / 2)'; + right: ~'calc(100% / 9 / 2)'; + } + + &.steps-10:before { + left: ~'calc(100% / 10 / 2)'; + right: ~'calc(100% / 10 / 2)'; + } + + /* --- http://www.paulirish.com/2012/box-sizing-border-box-ftw/ ---- */ + * { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + + + li { + position: relative; + float: left; + margin: 0; + padding: 0; + padding-top: 10px; + text-align: center; + line-height: 15px; + + a { + color: @color-current; + text-decoration: none; + text-transform: uppercase; + font-weight: bold; + transition: 0.25s; + cursor: pointer; + + &:before { + position: absolute; + top: -7px; + left: ~'calc(50% - 7px)'; + width: 14px; + height: 14px; + border-radius: 100%; + background-color: @color-default; + content: ''; + transition: 0.25s; + } + + &:hover { + color: darken(@color-current, 20%); + } + } + } + + &.steps-2 li { + width: ~'calc(100% / 2)'; + } + + &.steps-3 li { + width: ~'calc(100% / 3)'; + } + + &.steps-4 li { + width: ~'calc(100% / 4)'; + } + + &.steps-5 li { + width: ~'calc(100% / 5)'; + } + + &.steps-6 li { + width: ~'calc(100% / 6)'; + } + + &.steps-7 li { + width: ~'calc(100% / 7)'; + } + + &.steps-8 li { + width: ~'calc(100% / 8)'; + } + + &.steps-9 li { + width: ~'calc(100% / 9)'; + } + + &.steps-10 li { + width: ~'calc(100% / 10)'; + } + + &.steps-11 li { + width: ~'calc(100% / 11)'; + } + + li.default { + pointer-events: none; + + a:hover { + color: @color-current; + } + } + + li.current, + li.editing { + pointer-events: none; + } + + li.current a:before { + background-color: @color-current; + } + + li.done a:before { + background-color: @color-done; + } + + li.editing a:before { + background-color: @color-editing; + } +} +\ No newline at end of file diff --git a/src/main/webapp/less/overrides.less b/src/main/webapp/less/overrides.less @@ -14,14 +14,8 @@ body { background: @white; > #content, > footer { - padding:0 14px 10px 14px; - @media (max-width: @screen-sm) { - padding:0 4px 10px 4px; - } - + vertical-align: middle; - display: table-cell; - vertical-align: top; &, p { text-align: center; @@ -66,6 +60,12 @@ body { border-color: transparent; } +.navbar-container { + min-height: @navbar-container-height !important; + height: @navbar-container-height !important; + right: 13px; // TODO issue #2 +} + #navbar-main { margin-bottom: 0; @@ -73,7 +73,7 @@ body { .navbar-brand { padding: (@navbar-padding-vertical * 0.22222) @navbar-padding-horizontal; img { - height: @navbar-height * 0.8; + height: @navbar-container-height * 0.8; } } diff --git a/src/main/webapp/less/pages/about.less b/src/main/webapp/less/pages/about.less @@ -1,16 +0,0 @@ -.ourteam { - h3 { - color: @brand-primary; - font-weight: 400; - } - - img.img-ourteam { - width: 70%; - @media (min-width: @screen-xs) and (max-width: @screen-xs-max) { - width: 50%; - } - @media (max-width: @screen-xs) { - width: 100%; - } - } -} -\ No newline at end of file diff --git a/src/main/webapp/less/pages/index.less b/src/main/webapp/less/pages/index.less @@ -1,76 +0,0 @@ -#content-index { - - @index-page-height: 1025px; - @buysell-height: 275px; - @semi-content-padding: @jumbotron-padding / 1.5; - - @media(max-width: @screen-sm-max) { - #applyatm-index { - min-height: 0; - } - - #buysell-index { - min-height: 0; - margin-top: @jumbotron-padding; - } - - #whoweare-index, #findatm-index { - min-height: 0; - } - - & > div[class^="col-"], .semi-content-index > div[class^="col-"] { - padding-left: @semi-content-padding + 20; - padding-right: @semi-content-padding + 20; - } - } - - @media(min-width: @screen-md) { - #applyatm-index { - min-height: @index-page-height; - } - - #buysell-index { - min-height: @buysell-height; - padding-left: 0; // jumbotron - .jumbotron { margin-bottom: 0 } - } - - #whoweare-index, #findatm-index { - min-height: @index-page-height - @buysell-height; - } - - & > div[class^="col-"], .semi-content-index > div[class^="col-"] { - padding-left: @semi-content-padding; - padding-right: @semi-content-padding; - } - } - - // for div,img, btn etc that need 100% width but looks bad when stretched - .center-fixed-expand { - @media(min-width: @screen-md) { - width: 100%; - } - } - - & > div[class^="col-"] { - padding-left: 0; - padding-right: 0; - } - - // formats the atm application form - #applyatm-index-form { - fieldset { padding:0 } - footer { background:none } - } - - #atm-benefits { - td { height: 70px; } - } - - #atm-bitcoin-video { - iframe { - width: 100%; - height: 300px; - } - } -} -\ No newline at end of file diff --git a/src/main/webapp/less/pages/locations.less b/src/main/webapp/less/pages/locations.less @@ -1,84 +0,0 @@ -#atm-locations { - position: relative; - - // WARNING: Width is fixed because of layer-outer, but map-canvas can be 100% width - // layer-outer is temporary :) - .angular-google-map-container, .layer-overlay, layer-info { - pointer-events: none; - - @media (max-width: @screen-lg) { - width: 1136px; - height: 400px; - } - - @media (max-width: @screen-md-max) { - width: 936px; - height: 400px; - } - - @media (max-width: @screen-sm-max) { - width: 716px; - height: 650px; - } - - @media (max-width: @screen-xs-max) { - width: 98%; - height: 700px; - } - - width: 1136px; - height: 400px; - } - - .layer-overlay { - position: absolute; - - .layer-inner { - #gradient > .horizontal-three-colors(rgba(0,0,0,0.6), rgba(0,0,0,0.3), 50%, rgba(0,0,0,0.6)); - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - z-index: @gmap-overlay-zindex; - } - } - - .layer-info { - position: absolute; - z-index: @gmap-text-overlay-zindex + 10; - - #coming-soon-msg { - @title-font-size: 50px; - @message-font-size: 20px; - - @media (max-width: @screen-sm-max) { - .text-center(); - } - - h1 { - @media (max-width: @screen-xs) { - font-size: @title-font-size * 0.75; - padding: 5px; - } - - @media (min-width: @screen-xs) { - font-size: @title-font-size; - padding: 20px; - } - } - - p.message { - @media (max-width: @screen-xs){ - font-size: @message-font-size * 0.85; - padding: 5px; - } - - @media (min-width: @screen-xs) { - font-size: @message-font-size; - padding: 20px; - } - } - } - } -} -\ No newline at end of file diff --git a/src/main/webapp/less/pages/qr-scanner-wizard.less b/src/main/webapp/less/pages/qr-scanner-wizard.less @@ -0,0 +1,13 @@ +.scale(@x, @y) { + -moz-transform: scale(@x,@y); + -webkit-transform: scale(@x,@y); + -ms-transform: scale(@x,@y); // IE9+ + transform: scale(@x,@y); +} + +#wallet-scanner { + video { + // flips image horizontally + .scale(-1,1); + } +} +\ No newline at end of file diff --git a/src/main/webapp/less/styles.less b/src/main/webapp/less/styles.less @@ -137,14 +137,20 @@ @import "@{SmartAdminPath}/main-custom.less"; /********************************************************* - * My Website Pages + * Extras + ******************************************************* + */ +@ExtrasPath: "./extras"; + +@import "@{ExtrasPath}/angular-wizard.less"; + +/********************************************************* + * My Pages ******************************************************* */ @PagesPath: "./pages"; -@import "@{PagesPath}/about.less"; -@import "@{PagesPath}/index.less"; -@import "@{PagesPath}/locations.less"; +@import "@{PagesPath}/qr-scanner-wizard.less"; /********************************************************* * Overrides diff --git a/src/main/webapp/less/variables.less b/src/main/webapp/less/variables.less @@ -300,13 +300,14 @@ // Basics of a navbar @navbar-height: 80px; +@navbar-container-height: @navbar-height + 20; @navbar-margin-bottom: @line-height-computed /2; @navbar-default-color: #777; @navbar-default-bg: #f8f8f8; @navbar-default-border: darken(@navbar-default-bg, 6.5%); @navbar-border-radius: @border-radius-base; @navbar-padding-horizontal: floor(@grid-gutter-width / 2); -@navbar-padding-vertical: ((@navbar-height - @line-height-computed) / 2); +@navbar-padding-vertical: ((@navbar-container-height - @line-height-computed) / 2); // Navbar links @navbar-default-link-color: #777; diff --git a/src/main/webapp/templates-hidden/base-wrap.html b/src/main/webapp/templates-hidden/base-wrap.html @@ -17,21 +17,28 @@ </head> <body> -<div class="container"> +<div class="navbar-fixed-bottom container navbar-container"> <div id="navbar-main" class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand"><img src="/img/logo.png"></a> </div> - <div class="navbar-price pull-right" data-lift="PriceTicker" ng-controller="PriceTickerCtrl"> - <span class="lead">${{price}} / 1 BTC</span> + <div class="navbar-price pull-right" ng-controller="PriceTickerCtrl" ng-cloak> + <span class="lead">$ {{price}} / BTC</span> </div> </div> </div> +</div> +<div class="container"> <div id="content"></div> </div> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.min.js"></script> <script data-lift="Assets.js" type="text/javascript"></script> + +<!-- Comets --> +<script data-lift="TestComet"></script> +<script data-lift="PriceTickerComet"></script> + </body> </html> diff --git a/src/main/webapp/vendor/angular-qr-scanner.js b/src/main/webapp/vendor/angular-qr-scanner.js @@ -0,0 +1,70 @@ +angular.module('angular-qr-scanner', []) + +.directive('qrScanner', ['$timeout', function($timeout) { + return { + restrict: 'E', + scope: { + ngSuccess: '&ngSuccess', + ngError: '&ngError', + ngVideoError: '&ngVideoError' + }, + link: function(scope, element, attrs) { + + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; + + var height = attrs.height || 300; + var width = attrs.width || 250; + var localMediaStream; + + var video = document.createElement('video'); + video.setAttribute('width', width); + video.setAttribute('height', height); + var canvas = document.createElement('canvas'); + canvas.setAttribute('id', 'qr-canvas'); + canvas.setAttribute('width', width); + canvas.setAttribute('height', height); + canvas.setAttribute('style', 'display:none;'); + + angular.element(element).append(video); + angular.element(element).append(canvas); + var context = canvas.getContext('2d'); + + var scan = function() { + if (localMediaStream) { + try { + context.drawImage(video, 0, 0, width, height); + var data = canvas.toDataURL('image/png'); + qrcode.decode(data); + } catch(e) { + if (e.name == "NS_ERROR_NOT_AVAILABLE") {} else { + scope.ngError({error: e}); + } + } + } + $timeout(scan, 500); + } + + var successCallback = function(stream) { + video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; + localMediaStream = stream; + + video.play(); + $timeout(scan, 1000); + } + + // Call the getUserMedia method with our callback functions + if (navigator.getUserMedia) { + navigator.getUserMedia({video: true}, successCallback, function(e) { + scope.ngVideoError({error: e}); + }); + } else { + scope.ngVideoError({error: 'Native web camera streaming (getUserMedia) not supported in this browser.'}); + } + + qrcode.callback = function(data) { + scope.ngSuccess({data: data}); + }; + } + } +}]); +\ No newline at end of file diff --git a/src/main/webapp/vendor/angular-wizard.js b/src/main/webapp/vendor/angular-wizard.js @@ -0,0 +1,209 @@ +/** + * Easy to use Wizard library for AngularJS + * @version v0.4.0 - 2014-05-17 * @link https://github.com/mgonto/angular-wizard + * @author Martin Gontovnikas <martin@gon.to> + * @license MIT License, http://www.opensource.org/licenses/MIT + */ +angular.module('templates-angularwizard', ['step.html', 'wizard.html']); + +angular.module("step.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("step.html", + "<section ng-show=\"selected\" ng-class=\"{current: selected, done: completed}\" class=\"step\" ng-transclude>\n" + + "</section>"); +}]); + +angular.module("wizard.html", []).run(["$templateCache", function($templateCache) { + $templateCache.put("wizard.html", + "<div>\n" + + " <div class=\"steps\" ng-transclude></div>\n" + + " <ul class=\"steps-indicator steps-{{steps.length}}\" ng-if=\"!hideIndicators\">\n" + + " <li ng-class=\"{default: !step.completed && !step.selected, current: step.selected && !step.completed, done: step.completed && !step.selected, editing: step.selected && step.completed}\" ng-repeat=\"step in steps\">\n" + + " <a ng-click=\"goTo(step)\">{{step.title || step.wzTitle}}</a>\n" + + " </li>\n" + + " </ul>\n" + + "</div>\n" + + ""); +}]); + +angular.module('mgo-angular-wizard', ['templates-angularwizard']); + +angular.module('mgo-angular-wizard').directive('wzStep', function() { + return { + restrict: 'EA', + replace: true, + transclude: true, + scope: { + wzTitle: '@', + title: '@' + }, + require: '^wizard', + templateUrl: function(element, attributes) { + return attributes.template || "step.html"; + }, + link: function($scope, $element, $attrs, wizard) { + $scope.title = $scope.title || $scope.wzTitle; + wizard.addStep($scope); + } + }; +}); + +angular.module('mgo-angular-wizard').directive('wizard', function() { + return { + restrict: 'EA', + replace: true, + transclude: true, + scope: { + currentStep: '=', + onFinish: '&', + hideIndicators: '=', + editMode: '=', + name: '@' + }, + templateUrl: function(element, attributes) { + return attributes.template || "wizard.html"; + }, + controller: ['$scope', '$element', 'WizardHandler', function($scope, $element, WizardHandler) { + + WizardHandler.addWizard($scope.name || WizardHandler.defaultName, this); + $scope.$on('$destroy', function() { + WizardHandler.removeWizard($scope.name || WizardHandler.defaultName); + }); + + $scope.steps = []; + + $scope.$watch('currentStep', function(step) { + if (!step) return; + var stepTitle = $scope.selectedStep.title || $scope.selectedStep.wzTitle; + if ($scope.selectedStep && stepTitle !== $scope.currentStep) { + $scope.goTo(_.findWhere($scope.steps, {title: $scope.currentStep})); + } + + }); + + $scope.$watch('[editMode, steps.length]', function() { + var editMode = $scope.editMode; + if (_.isUndefined(editMode) || _.isNull(editMode)) return; + + if (editMode) { + _.each($scope.steps, function(step) { + step.completed = true; + }); + } + }, true); + + this.addStep = function(step) { + $scope.steps.push(step); + if ($scope.steps.length === 1) { + $scope.goTo($scope.steps[0]); + } + }; + + $scope.goTo = function(step) { + unselectAll(); + $scope.selectedStep = step; + if (!_.isUndefined($scope.currentStep)) { + $scope.currentStep = step.title || step.wzTitle; + } + step.selected = true; + $scope.$emit('wizard:stepChanged', {step: step, index: _.indexOf($scope.steps , step)}); + }; + + function unselectAll() { + _.each($scope.steps, function (step) { + step.selected = false; + }); + $scope.selectedStep = null; + } + + this.next = function(draft) { + var index = _.indexOf($scope.steps , $scope.selectedStep); + if (!draft) { + $scope.selectedStep.completed = true; + } + if (index === $scope.steps.length - 1) { + this.finish(); + } else { + $scope.goTo($scope.steps[index + 1]); + } + }; + + this.goTo = function(step) { + var stepTo; + if (_.isNumber(step)) { + stepTo = $scope.steps[step]; + } else { + stepTo = _.findWhere($scope.steps, {title: step}); + } + $scope.goTo(stepTo); + }; + + this.finish = function() { + if ($scope.onFinish) { + $scope.onFinish(); + } + }; + + this.cancel = this.previous = function() { + var index = _.indexOf($scope.steps , $scope.selectedStep); + if (index === 0) { + throw new Error("Can't go back. It's already in step 0"); + } else { + $scope.goTo($scope.steps[index - 1]); + } + }; + }] + }; +}); + +function wizardButtonDirective(action) { + angular.module('mgo-angular-wizard') + .directive(action, function() { + return { + restrict: 'A', + replace: false, + require: '^wizard', + link: function($scope, $element, $attrs, wizard) { + + $element.on("click", function(e) { + e.preventDefault(); + $scope.$apply(function() { + $scope.$eval($attrs[action]); + wizard[action.replace("wz", "").toLowerCase()](); + }); + }); + } + }; + }); +} + +wizardButtonDirective('wzNext'); +wizardButtonDirective('wzPrevious'); +wizardButtonDirective('wzFinish'); +wizardButtonDirective('wzCancel'); + +angular.module('mgo-angular-wizard').factory('WizardHandler', function() { + var service = {}; + + var wizards = {}; + + service.defaultName = "defaultWizard"; + + service.addWizard = function(name, wizard) { + wizards[name] = wizard; + }; + + service.removeWizard = function(name) { + delete wizards[name]; + }; + + service.wizard = function(name) { + var nameToUse = name; + if (!name) { + nameToUse = service.defaultName; + } + + return wizards[nameToUse]; + }; + + return service; +}); diff --git a/src/main/webapp/vendor/jsqrcode/alignpat.js b/src/main/webapp/vendor/jsqrcode/alignpat.js @@ -0,0 +1,279 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function AlignmentPattern(posX, posY, estimatedModuleSize) +{ + this.x=posX; + this.y=posY; + this.count = 1; + this.estimatedModuleSize = estimatedModuleSize; + + this.__defineGetter__("EstimatedModuleSize", function() + { + return this.estimatedModuleSize; + }); + this.__defineGetter__("Count", function() + { + return this.count; + }); + this.__defineGetter__("X", function() + { + return Math.floor(this.x); + }); + this.__defineGetter__("Y", function() + { + return Math.floor(this.y); + }); + this.incrementCount = function() + { + this.count++; + } + this.aboutEquals=function( moduleSize, i, j) + { + if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) + { + var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); + return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; + } + return false; + } + +} + +function AlignmentPatternFinder( image, startX, startY, width, height, moduleSize, resultPointCallback) +{ + this.image = image; + this.possibleCenters = new Array(); + this.startX = startX; + this.startY = startY; + this.width = width; + this.height = height; + this.moduleSize = moduleSize; + this.crossCheckStateCount = new Array(0,0,0); + this.resultPointCallback = resultPointCallback; + + this.centerFromEnd=function(stateCount, end) + { + return (end - stateCount[2]) - stateCount[1] / 2.0; + } + this.foundPatternCross = function(stateCount) + { + var moduleSize = this.moduleSize; + var maxVariance = moduleSize / 2.0; + for (var i = 0; i < 3; i++) + { + if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) + { + return false; + } + } + return true; + } + + this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal) + { + var image = this.image; + + var maxI = qrcode.height; + var stateCount = this.crossCheckStateCount; + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + + // Start counting up from center + var i = startI; + while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + i--; + } + // If already too many modules in this state or ran off the edge: + if (i < 0 || stateCount[1] > maxCount) + { + return NaN; + } + while (i >= 0 && !image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount) + { + stateCount[0]++; + i--; + } + if (stateCount[0] > maxCount) + { + return NaN; + } + + // Now also count down from center + i = startI + 1; + while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + i++; + } + if (i == maxI || stateCount[1] > maxCount) + { + return NaN; + } + while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[2] <= maxCount) + { + stateCount[2]++; + i++; + } + if (stateCount[2] > maxCount) + { + return NaN; + } + + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; + if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) + { + return NaN; + } + + return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; + } + + this.handlePossibleCenter=function( stateCount, i, j) + { + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; + var centerJ = this.centerFromEnd(stateCount, j); + var centerI = this.crossCheckVertical(i, Math.floor (centerJ), 2 * stateCount[1], stateCountTotal); + if (!isNaN(centerI)) + { + var estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0; + var max = this.possibleCenters.length; + for (var index = 0; index < max; index++) + { + var center = this.possibleCenters[index]; + // Look for about the same center and module size: + if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) + { + return new AlignmentPattern(centerJ, centerI, estimatedModuleSize); + } + } + // Hadn't found this before; save it + var point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize); + this.possibleCenters.push(point); + if (this.resultPointCallback != null) + { + this.resultPointCallback.foundPossibleResultPoint(point); + } + } + return null; + } + + this.find = function() + { + var startX = this.startX; + var height = this.height; + var maxJ = startX + width; + var middleI = startY + (height >> 1); + // We are looking for black/white/black modules in 1:1:1 ratio; + // this tracks the number of black/white/black modules seen so far + var stateCount = new Array(0,0,0); + for (var iGen = 0; iGen < height; iGen++) + { + // Search from middle outwards + var i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1)); + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + var j = startX; + // Burn off leading white pixels before anything else; if we start in the middle of + // a white run, it doesn't make sense to count its length, since we don't know if the + // white run continued to the left of the start point + while (j < maxJ && !image[j + qrcode.width* i]) + { + j++; + } + var currentState = 0; + while (j < maxJ) + { + if (image[j + i*qrcode.width]) + { + // Black pixel + if (currentState == 1) + { + // Counting black pixels + stateCount[currentState]++; + } + else + { + // Counting white pixels + if (currentState == 2) + { + // A winner? + if (this.foundPatternCross(stateCount)) + { + // Yes + var confirmed = this.handlePossibleCenter(stateCount, i, j); + if (confirmed != null) + { + return confirmed; + } + } + stateCount[0] = stateCount[2]; + stateCount[1] = 1; + stateCount[2] = 0; + currentState = 1; + } + else + { + stateCount[++currentState]++; + } + } + } + else + { + // White pixel + if (currentState == 1) + { + // Counting black pixels + currentState++; + } + stateCount[currentState]++; + } + j++; + } + if (this.foundPatternCross(stateCount)) + { + var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); + if (confirmed != null) + { + return confirmed; + } + } + } + + // Hmm, nothing we saw was observed and confirmed twice. If we had + // any guess at all, return it. + if (!(this.possibleCenters.length == 0)) + { + return this.possibleCenters[0]; + } + + throw "Couldn't find enough alignment patterns"; + } + +} +\ No newline at end of file diff --git a/src/main/webapp/vendor/jsqrcode/bitmat.js b/src/main/webapp/vendor/jsqrcode/bitmat.js @@ -0,0 +1,111 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function BitMatrix( width, height) +{ + if(!height) + height=width; + if (width < 1 || height < 1) + { + throw "Both dimensions must be greater than 0"; + } + this.width = width; + this.height = height; + var rowSize = width >> 5; + if ((width & 0x1f) != 0) + { + rowSize++; + } + this.rowSize = rowSize; + this.bits = new Array(rowSize * height); + for(var i=0;i<this.bits.length;i++) + this.bits[i]=0; + + this.__defineGetter__("Width", function() + { + return this.width; + }); + this.__defineGetter__("Height", function() + { + return this.height; + }); + this.__defineGetter__("Dimension", function() + { + if (this.width != this.height) + { + throw "Can't call getDimension() on a non-square matrix"; + } + return this.width; + }); + + this.get_Renamed=function( x, y) + { + var offset = y * this.rowSize + (x >> 5); + return ((URShift(this.bits[offset], (x & 0x1f))) & 1) != 0; + } + this.set_Renamed=function( x, y) + { + var offset = y * this.rowSize + (x >> 5); + this.bits[offset] |= 1 << (x & 0x1f); + } + this.flip=function( x, y) + { + var offset = y * this.rowSize + (x >> 5); + this.bits[offset] ^= 1 << (x & 0x1f); + } + this.clear=function() + { + var max = this.bits.length; + for (var i = 0; i < max; i++) + { + this.bits[i] = 0; + } + } + this.setRegion=function( left, top, width, height) + { + if (top < 0 || left < 0) + { + throw "Left and top must be nonnegative"; + } + if (height < 1 || width < 1) + { + throw "Height and width must be at least 1"; + } + var right = left + width; + var bottom = top + height; + if (bottom > this.height || right > this.width) + { + throw "The region must fit inside the matrix"; + } + for (var y = top; y < bottom; y++) + { + var offset = y * this.rowSize; + for (var x = left; x < right; x++) + { + this.bits[offset + (x >> 5)] |= 1 << (x & 0x1f); + } + } + } +} +\ No newline at end of file diff --git a/src/main/webapp/vendor/jsqrcode/bmparser.js b/src/main/webapp/vendor/jsqrcode/bmparser.js @@ -0,0 +1,203 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function BitMatrixParser(bitMatrix) +{ + var dimension = bitMatrix.Dimension; + if (dimension < 21 || (dimension & 0x03) != 1) + { + throw "Error BitMatrixParser"; + } + this.bitMatrix = bitMatrix; + this.parsedVersion = null; + this.parsedFormatInfo = null; + + this.copyBit=function( i, j, versionBits) + { + return this.bitMatrix.get_Renamed(i, j)?(versionBits << 1) | 0x1:versionBits << 1; + } + + this.readFormatInformation=function() + { + if (this.parsedFormatInfo != null) + { + return this.parsedFormatInfo; + } + + // Read top-left format info bits + var formatInfoBits = 0; + for (var i = 0; i < 6; i++) + { + formatInfoBits = this.copyBit(i, 8, formatInfoBits); + } + // .. and skip a bit in the timing pattern ... + formatInfoBits = this.copyBit(7, 8, formatInfoBits); + formatInfoBits = this.copyBit(8, 8, formatInfoBits); + formatInfoBits = this.copyBit(8, 7, formatInfoBits); + // .. and skip a bit in the timing pattern ... + for (var j = 5; j >= 0; j--) + { + formatInfoBits = this.copyBit(8, j, formatInfoBits); + } + + this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); + if (this.parsedFormatInfo != null) + { + return this.parsedFormatInfo; + } + + // Hmm, failed. Try the top-right/bottom-left pattern + var dimension = this.bitMatrix.Dimension; + formatInfoBits = 0; + var iMin = dimension - 8; + for (var i = dimension - 1; i >= iMin; i--) + { + formatInfoBits = this.copyBit(i, 8, formatInfoBits); + } + for (var j = dimension - 7; j < dimension; j++) + { + formatInfoBits = this.copyBit(8, j, formatInfoBits); + } + + this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); + if (this.parsedFormatInfo != null) + { + return this.parsedFormatInfo; + } + throw "Error readFormatInformation"; + } + this.readVersion=function() + { + + if (this.parsedVersion != null) + { + return this.parsedVersion; + } + + var dimension = this.bitMatrix.Dimension; + + var provisionalVersion = (dimension - 17) >> 2; + if (provisionalVersion <= 6) + { + return Version.getVersionForNumber(provisionalVersion); + } + + // Read top-right version info: 3 wide by 6 tall + var versionBits = 0; + var ijMin = dimension - 11; + for (var j = 5; j >= 0; j--) + { + for (var i = dimension - 9; i >= ijMin; i--) + { + versionBits = this.copyBit(i, j, versionBits); + } + } + + this.parsedVersion = Version.decodeVersionInformation(versionBits); + if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) + { + return this.parsedVersion; + } + + // Hmm, failed. Try bottom left: 6 wide by 3 tall + versionBits = 0; + for (var i = 5; i >= 0; i--) + { + for (var j = dimension - 9; j >= ijMin; j--) + { + versionBits = this.copyBit(i, j, versionBits); + } + } + + this.parsedVersion = Version.decodeVersionInformation(versionBits); + if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) + { + return this.parsedVersion; + } + throw "Error readVersion"; + } + this.readCodewords=function() + { + + var formatInfo = this.readFormatInformation(); + var version = this.readVersion(); + + // Get the data mask for the format used in this QR Code. This will exclude + // some bits from reading as we wind through the bit matrix. + var dataMask = DataMask.forReference( formatInfo.DataMask); + var dimension = this.bitMatrix.Dimension; + dataMask.unmaskBitMatrix(this.bitMatrix, dimension); + + var functionPattern = version.buildFunctionPattern(); + + var readingUp = true; + var result = new Array(version.TotalCodewords); + var resultOffset = 0; + var currentByte = 0; + var bitsRead = 0; + // Read columns in pairs, from right to left + for (var j = dimension - 1; j > 0; j -= 2) + { + if (j == 6) + { + // Skip whole column with vertical alignment pattern; + // saves time and makes the other code proceed more cleanly + j--; + } + // Read alternatingly from bottom to top then top to bottom + for (var count = 0; count < dimension; count++) + { + var i = readingUp?dimension - 1 - count:count; + for (var col = 0; col < 2; col++) + { + // Ignore bits covered by the function pattern + if (!functionPattern.get_Renamed(j - col, i)) + { + // Read a bit + bitsRead++; + currentByte <<= 1; + if (this.bitMatrix.get_Renamed(j - col, i)) + { + currentByte |= 1; + } + // If we've made a whole byte, save it off + if (bitsRead == 8) + { + result[resultOffset++] = currentByte; + bitsRead = 0; + currentByte = 0; + } + } + } + } + readingUp ^= true; // readingUp = !readingUp; // switch directions + } + if (resultOffset != version.TotalCodewords) + { + throw "Error readCodewords"; + } + return result; + } +} +\ No newline at end of file diff --git a/src/main/webapp/vendor/jsqrcode/datablock.js b/src/main/webapp/vendor/jsqrcode/datablock.js @@ -0,0 +1,117 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function DataBlock(numDataCodewords, codewords) +{ + this.numDataCodewords = numDataCodewords; + this.codewords = codewords; + + this.__defineGetter__("NumDataCodewords", function() + { + return this.numDataCodewords; + }); + this.__defineGetter__("Codewords", function() + { + return this.codewords; + }); +} + +DataBlock.getDataBlocks=function(rawCodewords, version, ecLevel) +{ + + if (rawCodewords.length != version.TotalCodewords) + { + throw "ArgumentException"; + } + + // Figure out the number and size of data blocks used by this version and + // error correction level + var ecBlocks = version.getECBlocksForLevel(ecLevel); + + // First count the total number of data blocks + var totalBlocks = 0; + var ecBlockArray = ecBlocks.getECBlocks(); + for (var i = 0; i < ecBlockArray.length; i++) + { + totalBlocks += ecBlockArray[i].Count; + } + + // Now establish DataBlocks of the appropriate size and number of data codewords + var result = new Array(totalBlocks); + var numResultBlocks = 0; + for (var j = 0; j < ecBlockArray.length; j++) + { + var ecBlock = ecBlockArray[j]; + for (var i = 0; i < ecBlock.Count; i++) + { + var numDataCodewords = ecBlock.DataCodewords; + var numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords; + result[numResultBlocks++] = new DataBlock(numDataCodewords, new Array(numBlockCodewords)); + } + } + + // All blocks have the same amount of data, except that the last n + // (where n may be 0) have 1 more byte. Figure out where these start. + var shorterBlocksTotalCodewords = result[0].codewords.length; + var longerBlocksStartAt = result.length - 1; + while (longerBlocksStartAt >= 0) + { + var numCodewords = result[longerBlocksStartAt].codewords.length; + if (numCodewords == shorterBlocksTotalCodewords) + { + break; + } + longerBlocksStartAt--; + } + longerBlocksStartAt++; + + var shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock; + // The last elements of result may be 1 element longer; + // first fill out as many elements as all of them have + var rawCodewordsOffset = 0; + for (var i = 0; i < shorterBlocksNumDataCodewords; i++) + { + for (var j = 0; j < numResultBlocks; j++) + { + result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; + } + } + // Fill out the last data block in the longer ones + for (var j = longerBlocksStartAt; j < numResultBlocks; j++) + { + result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; + } + // Now add in error correction blocks + var max = result[0].codewords.length; + for (var i = shorterBlocksNumDataCodewords; i < max; i++) + { + for (var j = 0; j < numResultBlocks; j++) + { + var iOffset = j < longerBlocksStartAt?i:i + 1; + result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; + } + } + return result; +} diff --git a/src/main/webapp/vendor/jsqrcode/databr.js b/src/main/webapp/vendor/jsqrcode/databr.js @@ -0,0 +1,325 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function QRCodeDataBlockReader(blocks, version, numErrorCorrectionCode) +{ + this.blockPointer = 0; + this.bitPointer = 7; + this.dataLength = 0; + this.blocks = blocks; + this.numErrorCorrectionCode = numErrorCorrectionCode; + if (version <= 9) + this.dataLengthMode = 0; + else if (version >= 10 && version <= 26) + this.dataLengthMode = 1; + else if (version >= 27 && version <= 40) + this.dataLengthMode = 2; + + this.getNextBits = function( numBits) + { + var bits = 0; + if (numBits < this.bitPointer + 1) + { + // next word fits into current data block + var mask = 0; + for (var i = 0; i < numBits; i++) + { + mask += (1 << i); + } + mask <<= (this.bitPointer - numBits + 1); + + bits = (this.blocks[this.blockPointer] & mask) >> (this.bitPointer - numBits + 1); + this.bitPointer -= numBits; + return bits; + } + else if (numBits < this.bitPointer + 1 + 8) + { + // next word crosses 2 data blocks + var mask1 = 0; + for (var i = 0; i < this.bitPointer + 1; i++) + { + mask1 += (1 << i); + } + bits = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); + this.blockPointer++; + bits += ((this.blocks[this.blockPointer]) >> (8 - (numBits - (this.bitPointer + 1)))); + + this.bitPointer = this.bitPointer - numBits % 8; + if (this.bitPointer < 0) + { + this.bitPointer = 8 + this.bitPointer; + } + return bits; + } + else if (numBits < this.bitPointer + 1 + 16) + { + // next word crosses 3 data blocks + var mask1 = 0; // mask of first block + var mask3 = 0; // mask of 3rd block + //bitPointer + 1 : number of bits of the 1st block + //8 : number of the 2nd block (note that use already 8bits because next word uses 3 data blocks) + //numBits - (bitPointer + 1 + 8) : number of bits of the 3rd block + for (var i = 0; i < this.bitPointer + 1; i++) + { + mask1 += (1 << i); + } + var bitsFirstBlock = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); + this.blockPointer++; + + var bitsSecondBlock = this.blocks[this.blockPointer] << (numBits - (this.bitPointer + 1 + 8)); + this.blockPointer++; + + for (var i = 0; i < numBits - (this.bitPointer + 1 + 8); i++) + { + mask3 += (1 << i); + } + mask3 <<= 8 - (numBits - (this.bitPointer + 1 + 8)); + var bitsThirdBlock = (this.blocks[this.blockPointer] & mask3) >> (8 - (numBits - (this.bitPointer + 1 + 8))); + + bits = bitsFirstBlock + bitsSecondBlock + bitsThirdBlock; + this.bitPointer = this.bitPointer - (numBits - 8) % 8; + if (this.bitPointer < 0) + { + this.bitPointer = 8 + this.bitPointer; + } + return bits; + } + else + { + return 0; + } + } + this.NextMode=function() + { + if ((this.blockPointer > this.blocks.length - this.numErrorCorrectionCode - 2)) + return 0; + else + return this.getNextBits(4); + } + this.getDataLength=function( modeIndicator) + { + var index = 0; + while (true) + { + if ((modeIndicator >> index) == 1) + break; + index++; + } + + return this.getNextBits(qrcode.sizeOfDataLengthInfo[this.dataLengthMode][index]); + } + this.getRomanAndFigureString=function( dataLength) + { + var length = dataLength; + var intData = 0; + var strData = ""; + var tableRomanAndFigure = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'); + do + { + if (length > 1) + { + intData = this.getNextBits(11); + var firstLetter = Math.floor(intData / 45); + var secondLetter = intData % 45; + strData += tableRomanAndFigure[firstLetter]; + strData += tableRomanAndFigure[secondLetter]; + length -= 2; + } + else if (length == 1) + { + intData = this.getNextBits(6); + strData += tableRomanAndFigure[intData]; + length -= 1; + } + } + while (length > 0); + + return strData; + } + this.getFigureString=function( dataLength) + { + var length = dataLength; + var intData = 0; + var strData = ""; + do + { + if (length >= 3) + { + intData = this.getNextBits(10); + if (intData < 100) + strData += "0"; + if (intData < 10) + strData += "0"; + length -= 3; + } + else if (length == 2) + { + intData = this.getNextBits(7); + if (intData < 10) + strData += "0"; + length -= 2; + } + else if (length == 1) + { + intData = this.getNextBits(4); + length -= 1; + } + strData += intData; + } + while (length > 0); + + return strData; + } + this.get8bitByteArray=function( dataLength) + { + var length = dataLength; + var intData = 0; + var output = new Array(); + + do + { + intData = this.getNextBits(8); + output.push( intData); + length--; + } + while (length > 0); + return output; + } + this.getKanjiString=function( dataLength) + { + var length = dataLength; + var intData = 0; + var unicodeString = ""; + do + { + intData = getNextBits(13); + var lowerByte = intData % 0xC0; + var higherByte = intData / 0xC0; + + var tempWord = (higherByte << 8) + lowerByte; + var shiftjisWord = 0; + if (tempWord + 0x8140 <= 0x9FFC) + { + // between 8140 - 9FFC on Shift_JIS character set + shiftjisWord = tempWord + 0x8140; + } + else + { + // between E040 - EBBF on Shift_JIS character set + shiftjisWord = tempWord + 0xC140; + } + + //var tempByte = new Array(0,0); + //tempByte[0] = (sbyte) (shiftjisWord >> 8); + //tempByte[1] = (sbyte) (shiftjisWord & 0xFF); + //unicodeString += new String(SystemUtils.ToCharArray(SystemUtils.ToByteArray(tempByte))); + unicodeString += String.fromCharCode(shiftjisWord); + length--; + } + while (length > 0); + + + return unicodeString; + } + + this.__defineGetter__("DataByte", function() + { + var output = new Array(); + var MODE_NUMBER = 1; + var MODE_ROMAN_AND_NUMBER = 2; + var MODE_8BIT_BYTE = 4; + var MODE_KANJI = 8; + do + { + var mode = this.NextMode(); + //canvas.println("mode: " + mode); + if (mode == 0) + { + if (output.length > 0) + break; + else + throw "Empty data block"; + } + //if (mode != 1 && mode != 2 && mode != 4 && mode != 8) + // break; + //} + if (mode != MODE_NUMBER && mode != MODE_ROMAN_AND_NUMBER && mode != MODE_8BIT_BYTE && mode != MODE_KANJI) + { + /* canvas.println("Invalid mode: " + mode); + mode = guessMode(mode); + canvas.println("Guessed mode: " + mode); */ + throw "Invalid mode: " + mode + " in (block:" + this.blockPointer + " bit:" + this.bitPointer + ")"; + } + dataLength = this.getDataLength(mode); + if (dataLength < 1) + throw "Invalid data length: " + dataLength; + //canvas.println("length: " + dataLength); + switch (mode) + { + + case MODE_NUMBER: + //canvas.println("Mode: Figure"); + var temp_str = this.getFigureString(dataLength); + var ta = new Array(temp_str.length); + for(var j=0;j<temp_str.length;j++) + ta[j]=temp_str.charCodeAt(j); + output.push(ta); + break; + + case MODE_ROMAN_AND_NUMBER: + //canvas.println("Mode: Roman&Figure"); + var temp_str = this.getRomanAndFigureString(dataLength); + var ta = new Array(temp_str.length); + for(var j=0;j<temp_str.length;j++) + ta[j]=temp_str.charCodeAt(j); + output.push(ta ); + //output.Write(SystemUtils.ToByteArray(temp_sbyteArray2), 0, temp_sbyteArray2.Length); + break; + + case MODE_8BIT_BYTE: + //canvas.println("Mode: 8bit Byte"); + //sbyte[] temp_sbyteArray3; + var temp_sbyteArray3 = this.get8bitByteArray(dataLength); + output.push(temp_sbyteArray3); + //output.Write(SystemUtils.ToByteArray(temp_sbyteArray3), 0, temp_sbyteArray3.Length); + break; + + case MODE_KANJI: + //canvas.println("Mode: Kanji"); + //sbyte[] temp_sbyteArray4; + //temp_sbyteArray4 = SystemUtils.ToSByteArray(SystemUtils.ToByteArray(getKanjiString(dataLength))); + //output.Write(SystemUtils.ToByteArray(temp_sbyteArray4), 0, temp_sbyteArray4.Length); + var temp_str = this.getKanjiString(dataLength); + output.push(temp_str); + break; + } + // + //canvas.println("DataLength: " + dataLength); + //Console.out.println(dataString); + } + while (true); + return output; + }); +} diff --git a/src/main/webapp/vendor/jsqrcode/datamask.js b/src/main/webapp/vendor/jsqrcode/datamask.js @@ -0,0 +1,207 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +DataMask = {}; + +DataMask.forReference = function(reference) +{ + if (reference < 0 || reference > 7) + { + throw "System.ArgumentException"; + } + return DataMask.DATA_MASKS[reference]; +} + +function DataMask000() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return ((i + j) & 0x01) == 0; + } +} + +function DataMask001() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return (i & 0x01) == 0; + } +} + +function DataMask010() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return j % 3 == 0; + } +} + +function DataMask011() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return (i + j) % 3 == 0; + } +} + +function DataMask100() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return (((URShift(i, 1)) + (j / 3)) & 0x01) == 0; + } +} + +function DataMask101() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + var temp = i * j; + return (temp & 0x01) + (temp % 3) == 0; + } +} + +function DataMask110() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + var temp = i * j; + return (((temp & 0x01) + (temp % 3)) & 0x01) == 0; + } +} +function DataMask111() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) == 0; + } +} + +DataMask.DATA_MASKS = new Array(new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111()); + diff --git a/src/main/webapp/vendor/jsqrcode/decoder.js b/src/main/webapp/vendor/jsqrcode/decoder.js @@ -0,0 +1,95 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +Decoder={}; +Decoder.rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD); + +Decoder.correctErrors=function( codewordBytes, numDataCodewords) +{ + var numCodewords = codewordBytes.length; + // First read into an array of ints + var codewordsInts = new Array(numCodewords); + for (var i = 0; i < numCodewords; i++) + { + codewordsInts[i] = codewordBytes[i] & 0xFF; + } + var numECCodewords = codewordBytes.length - numDataCodewords; + try + { + Decoder.rsDecoder.decode(codewordsInts, numECCodewords); + //var corrector = new ReedSolomon(codewordsInts, numECCodewords); + //corrector.correct(); + } + catch ( rse) + { + throw rse; + } + // Copy back into array of bytes -- only need to worry about the bytes that were data + // We don't care about errors in the error-correction codewords + for (var i = 0; i < numDataCodewords; i++) + { + codewordBytes[i] = codewordsInts[i]; + } +} + +Decoder.decode=function(bits) +{ + var parser = new BitMatrixParser(bits); + var version = parser.readVersion(); + var ecLevel = parser.readFormatInformation().ErrorCorrectionLevel; + + // Read codewords + var codewords = parser.readCodewords(); + + // Separate into data blocks + var dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); + + // Count total number of data bytes + var totalBytes = 0; + for (var i = 0; i < dataBlocks.length; i++) + { + totalBytes += dataBlocks[i].NumDataCodewords; + } + var resultBytes = new Array(totalBytes); + var resultOffset = 0; + + // Error-correct and copy data blocks together into a stream of bytes + for (var j = 0; j < dataBlocks.length; j++) + { + var dataBlock = dataBlocks[j]; + var codewordBytes = dataBlock.Codewords; + var numDataCodewords = dataBlock.NumDataCodewords; + Decoder.correctErrors(codewordBytes, numDataCodewords); + for (var i = 0; i < numDataCodewords; i++) + { + resultBytes[resultOffset++] = codewordBytes[i]; + } + } + + // Decode the contents of that stream of bytes + var reader = new QRCodeDataBlockReader(resultBytes, version.VersionNumber, ecLevel.Bits); + return reader; + //return DecodedBitStreamParser.decode(resultBytes, version, ecLevel); +} diff --git a/src/main/webapp/vendor/jsqrcode/detector.js b/src/main/webapp/vendor/jsqrcode/detector.js @@ -0,0 +1,413 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function PerspectiveTransform( a11, a21, a31, a12, a22, a32, a13, a23, a33) +{ + this.a11 = a11; + this.a12 = a12; + this.a13 = a13; + this.a21 = a21; + this.a22 = a22; + this.a23 = a23; + this.a31 = a31; + this.a32 = a32; + this.a33 = a33; + this.transformPoints1=function( points) + { + var max = points.length; + var a11 = this.a11; + var a12 = this.a12; + var a13 = this.a13; + var a21 = this.a21; + var a22 = this.a22; + var a23 = this.a23; + var a31 = this.a31; + var a32 = this.a32; + var a33 = this.a33; + for (var i = 0; i < max; i += 2) + { + var x = points[i]; + var y = points[i + 1]; + var denominator = a13 * x + a23 * y + a33; + points[i] = (a11 * x + a21 * y + a31) / denominator; + points[i + 1] = (a12 * x + a22 * y + a32) / denominator; + } + } + this. transformPoints2=function(xValues, yValues) + { + var n = xValues.length; + for (var i = 0; i < n; i++) + { + var x = xValues[i]; + var y = yValues[i]; + var denominator = this.a13 * x + this.a23 * y + this.a33; + xValues[i] = (this.a11 * x + this.a21 * y + this.a31) / denominator; + yValues[i] = (this.a12 * x + this.a22 * y + this.a32) / denominator; + } + } + + this.buildAdjoint=function() + { + // Adjoint is the transpose of the cofactor matrix: + return new PerspectiveTransform(this.a22 * this.a33 - this.a23 * this.a32, this.a23 * this.a31 - this.a21 * this.a33, this.a21 * this.a32 - this.a22 * this.a31, this.a13 * this.a32 - this.a12 * this.a33, this.a11 * this.a33 - this.a13 * this.a31, this.a12 * this.a31 - this.a11 * this.a32, this.a12 * this.a23 - this.a13 * this.a22, this.a13 * this.a21 - this.a11 * this.a23, this.a11 * this.a22 - this.a12 * this.a21); + } + this.times=function( other) + { + return new PerspectiveTransform(this.a11 * other.a11 + this.a21 * other.a12 + this.a31 * other.a13, this.a11 * other.a21 + this.a21 * other.a22 + this.a31 * other.a23, this.a11 * other.a31 + this.a21 * other.a32 + this.a31 * other.a33, this.a12 * other.a11 + this.a22 * other.a12 + this.a32 * other.a13, this.a12 * other.a21 + this.a22 * other.a22 + this.a32 * other.a23, this.a12 * other.a31 + this.a22 * other.a32 + this.a32 * other.a33, this.a13 * other.a11 + this.a23 * other.a12 +this.a33 * other.a13, this.a13 * other.a21 + this.a23 * other.a22 + this.a33 * other.a23, this.a13 * other.a31 + this.a23 * other.a32 + this.a33 * other.a33); + } + +} + +PerspectiveTransform.quadrilateralToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3, x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p) +{ + + var qToS = this.quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); + var sToQ = this.squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); + return sToQ.times(qToS); +} + +PerspectiveTransform.squareToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3) +{ + dy2 = y3 - y2; + dy3 = y0 - y1 + y2 - y3; + if (dy2 == 0.0 && dy3 == 0.0) + { + return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0, 0.0, 1.0); + } + else + { + dx1 = x1 - x2; + dx2 = x3 - x2; + dx3 = x0 - x1 + x2 - x3; + dy1 = y1 - y2; + denominator = dx1 * dy2 - dx2 * dy1; + a13 = (dx3 * dy2 - dx2 * dy3) / denominator; + a23 = (dx1 * dy3 - dx3 * dy1) / denominator; + return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0); + } +} + +PerspectiveTransform.quadrilateralToSquare=function( x0, y0, x1, y1, x2, y2, x3, y3) +{ + // Here, the adjoint serves as the inverse: + return this.squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); +} + +function DetectorResult(bits, points) +{ + this.bits = bits; + this.points = points; +} + + +function Detector(image) +{ + this.image=image; + this.resultPointCallback = null; + + this.sizeOfBlackWhiteBlackRun=function( fromX, fromY, toX, toY) + { + // Mild variant of Bresenham's algorithm; + // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm + var steep = Math.abs(toY - fromY) > Math.abs(toX - fromX); + if (steep) + { + var temp = fromX; + fromX = fromY; + fromY = temp; + temp = toX; + toX = toY; + toY = temp; + } + + var dx = Math.abs(toX - fromX); + var dy = Math.abs(toY - fromY); + var error = - dx >> 1; + var ystep = fromY < toY?1:- 1; + var xstep = fromX < toX?1:- 1; + var state = 0; // In black pixels, looking for white, first or second time + for (var x = fromX, y = fromY; x != toX; x += xstep) + { + + var realX = steep?y:x; + var realY = steep?x:y; + if (state == 1) + { + // In white pixels, looking for black + if (this.image[realX + realY*qrcode.width]) + { + state++; + } + } + else + { + if (!this.image[realX + realY*qrcode.width]) + { + state++; + } + } + + if (state == 3) + { + // Found black, white, black, and stumbled back onto white; done + var diffX = x - fromX; + var diffY = y - fromY; + return Math.sqrt( (diffX * diffX + diffY * diffY)); + } + error += dy; + if (error > 0) + { + if (y == toY) + { + break; + } + y += ystep; + error -= dx; + } + } + var diffX2 = toX - fromX; + var diffY2 = toY - fromY; + return Math.sqrt( (diffX2 * diffX2 + diffY2 * diffY2)); + } + + + this.sizeOfBlackWhiteBlackRunBothWays=function( fromX, fromY, toX, toY) + { + + var result = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); + + // Now count other way -- don't run off image though of course + var scale = 1.0; + var otherToX = fromX - (toX - fromX); + if (otherToX < 0) + { + scale = fromX / (fromX - otherToX); + otherToX = 0; + } + else if (otherToX >= qrcode.width) + { + scale = (qrcode.width - 1 - fromX) / (otherToX - fromX); + otherToX = qrcode.width - 1; + } + var otherToY = Math.floor (fromY - (toY - fromY) * scale); + + scale = 1.0; + if (otherToY < 0) + { + scale = fromY / (fromY - otherToY); + otherToY = 0; + } + else if (otherToY >= qrcode.height) + { + scale = (qrcode.height - 1 - fromY) / (otherToY - fromY); + otherToY = qrcode.height - 1; + } + otherToX = Math.floor (fromX + (otherToX - fromX) * scale); + + result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); + return result - 1.0; // -1 because we counted the middle pixel twice + } + + + + this.calculateModuleSizeOneWay=function( pattern, otherPattern) + { + var moduleSizeEst1 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor( pattern.X), Math.floor( pattern.Y), Math.floor( otherPattern.X), Math.floor(otherPattern.Y)); + var moduleSizeEst2 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(otherPattern.X), Math.floor(otherPattern.Y), Math.floor( pattern.X), Math.floor(pattern.Y)); + if (isNaN(moduleSizeEst1)) + { + return moduleSizeEst2 / 7.0; + } + if (isNaN(moduleSizeEst2)) + { + return moduleSizeEst1 / 7.0; + } + // Average them, and divide by 7 since we've counted the width of 3 black modules, + // and 1 white and 1 black module on either side. Ergo, divide sum by 14. + return (moduleSizeEst1 + moduleSizeEst2) / 14.0; + } + + + this.calculateModuleSize=function( topLeft, topRight, bottomLeft) + { + // Take the average + return (this.calculateModuleSizeOneWay(topLeft, topRight) + this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0; + } + + this.distance=function( pattern1, pattern2) + { + xDiff = pattern1.X - pattern2.X; + yDiff = pattern1.Y - pattern2.Y; + return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); + } + this.computeDimension=function( topLeft, topRight, bottomLeft, moduleSize) + { + + var tltrCentersDimension = Math.round(this.distance(topLeft, topRight) / moduleSize); + var tlblCentersDimension = Math.round(this.distance(topLeft, bottomLeft) / moduleSize); + var dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; + switch (dimension & 0x03) + { + + // mod 4 + case 0: + dimension++; + break; + // 1? do nothing + + case 2: + dimension--; + break; + + case 3: + throw "Error"; + } + return dimension; + } + + this.findAlignmentInRegion=function( overallEstModuleSize, estAlignmentX, estAlignmentY, allowanceFactor) + { + // Look for an alignment pattern (3 modules in size) around where it + // should be + var allowance = Math.floor (allowanceFactor * overallEstModuleSize); + var alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance); + var alignmentAreaRightX = Math.min(qrcode.width - 1, estAlignmentX + allowance); + if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) + { + throw "Error"; + } + + var alignmentAreaTopY = Math.max(0, estAlignmentY - allowance); + var alignmentAreaBottomY = Math.min(qrcode.height - 1, estAlignmentY + allowance); + + var alignmentFinder = new AlignmentPatternFinder(this.image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, this.resultPointCallback); + return alignmentFinder.find(); + } + + this.createTransform=function( topLeft, topRight, bottomLeft, alignmentPattern, dimension) + { + var dimMinusThree = dimension - 3.5; + var bottomRightX; + var bottomRightY; + var sourceBottomRightX; + var sourceBottomRightY; + if (alignmentPattern != null) + { + bottomRightX = alignmentPattern.X; + bottomRightY = alignmentPattern.Y; + sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0; + } + else + { + // Don't have an alignment pattern, just make up the bottom-right point + bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X; + bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y; + sourceBottomRightX = sourceBottomRightY = dimMinusThree; + } + + var transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y); + + return transform; + } + + this.sampleGrid=function( image, transform, dimension) + { + + var sampler = GridSampler; + return sampler.sampleGrid3(image, dimension, transform); + } + + this.processFinderPatternInfo = function( info) + { + + var topLeft = info.TopLeft; + var topRight = info.TopRight; + var bottomLeft = info.BottomLeft; + + var moduleSize = this.calculateModuleSize(topLeft, topRight, bottomLeft); + if (moduleSize < 1.0) + { + throw "Error"; + } + var dimension = this.computeDimension(topLeft, topRight, bottomLeft, moduleSize); + var provisionalVersion = Version.getProvisionalVersionForDimension(dimension); + var modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7; + + var alignmentPattern = null; + // Anything above version 1 has an alignment pattern + if (provisionalVersion.AlignmentPatternCenters.length > 0) + { + + // Guess where a "bottom right" finder pattern would have been + var bottomRightX = topRight.X - topLeft.X + bottomLeft.X; + var bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y; + + // Estimate that alignment pattern is closer by 3 modules + // from "bottom right" to known top left location + var correctionToTopLeft = 1.0 - 3.0 / modulesBetweenFPCenters; + var estAlignmentX = Math.floor (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X)); + var estAlignmentY = Math.floor (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y)); + + // Kind of arbitrary -- expand search radius before giving up + for (var i = 4; i <= 16; i <<= 1) + { + //try + //{ + alignmentPattern = this.findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, i); + break; + //} + //catch (re) + //{ + // try next round + //} + } + // If we didn't find alignment pattern... well try anyway without it + } + + var transform = this.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); + + var bits = this.sampleGrid(this.image, transform, dimension); + + var points; + if (alignmentPattern == null) + { + points = new Array(bottomLeft, topLeft, topRight); + } + else + { + points = new Array(bottomLeft, topLeft, topRight, alignmentPattern); + } + return new DetectorResult(bits, points); + } + + + + this.detect=function() + { + var info = new FinderPatternFinder().findFinderPattern(this.image); + + return this.processFinderPatternInfo(info); + } +} +\ No newline at end of file diff --git a/src/main/webapp/vendor/jsqrcode/errorlevel.js b/src/main/webapp/vendor/jsqrcode/errorlevel.js @@ -0,0 +1,58 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function ErrorCorrectionLevel(ordinal, bits, name) +{ + this.ordinal_Renamed_Field = ordinal; + this.bits = bits; + this.name = name; + this.__defineGetter__("Bits", function() + { + return this.bits; + }); + this.__defineGetter__("Name", function() + { + return this.name; + }); + this.ordinal=function() + { + return this.ordinal_Renamed_Field; + } +} + +ErrorCorrectionLevel.forBits=function( bits) +{ + if (bits < 0 || bits >= FOR_BITS.length) + { + throw "ArgumentException"; + } + return FOR_BITS[bits]; +} + +var L = new ErrorCorrectionLevel(0, 0x01, "L"); +var M = new ErrorCorrectionLevel(1, 0x00, "M"); +var Q = new ErrorCorrectionLevel(2, 0x03, "Q"); +var H = new ErrorCorrectionLevel(3, 0x02, "H"); +var FOR_BITS = new Array( M, L, H, Q); diff --git a/src/main/webapp/vendor/jsqrcode/findpat.js b/src/main/webapp/vendor/jsqrcode/findpat.js @@ -0,0 +1,649 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +var MIN_SKIP = 3; +var MAX_MODULES = 57; +var INTEGER_MATH_SHIFT = 8; +var CENTER_QUORUM = 2; + +qrcode.orderBestPatterns=function(patterns) + { + + function distance( pattern1, pattern2) + { + xDiff = pattern1.X - pattern2.X; + yDiff = pattern1.Y - pattern2.Y; + return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); + } + + /// <summary> Returns the z component of the cross product between vectors BC and BA.</summary> + function crossProductZ( pointA, pointB, pointC) + { + var bX = pointB.x; + var bY = pointB.y; + return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX)); + } + + + // Find distances between pattern centers + var zeroOneDistance = distance(patterns[0], patterns[1]); + var oneTwoDistance = distance(patterns[1], patterns[2]); + var zeroTwoDistance = distance(patterns[0], patterns[2]); + + var pointA, pointB, pointC; + // Assume one closest to other two is B; A and C will just be guesses at first + if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) + { + pointB = patterns[0]; + pointA = patterns[1]; + pointC = patterns[2]; + } + else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) + { + pointB = patterns[1]; + pointA = patterns[0]; + pointC = patterns[2]; + } + else + { + pointB = patterns[2]; + pointA = patterns[0]; + pointC = patterns[1]; + } + + // Use cross product to figure out whether A and C are correct or flipped. + // This asks whether BC x BA has a positive z component, which is the arrangement + // we want for A, B, C. If it's negative, then we've got it flipped around and + // should swap A and C. + if (crossProductZ(pointA, pointB, pointC) < 0.0) + { + var temp = pointA; + pointA = pointC; + pointC = temp; + } + + patterns[0] = pointA; + patterns[1] = pointB; + patterns[2] = pointC; + } + + +function FinderPattern(posX, posY, estimatedModuleSize) +{ + this.x=posX; + this.y=posY; + this.count = 1; + this.estimatedModuleSize = estimatedModuleSize; + + this.__defineGetter__("EstimatedModuleSize", function() + { + return this.estimatedModuleSize; + }); + this.__defineGetter__("Count", function() + { + return this.count; + }); + this.__defineGetter__("X", function() + { + return this.x; + }); + this.__defineGetter__("Y", function() + { + return this.y; + }); + this.incrementCount = function() + { + this.count++; + } + this.aboutEquals=function( moduleSize, i, j) + { + if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) + { + var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); + return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; + } + return false; + } + +} + +function FinderPatternInfo(patternCenters) +{ + this.bottomLeft = patternCenters[0]; + this.topLeft = patternCenters[1]; + this.topRight = patternCenters[2]; + this.__defineGetter__("BottomLeft", function() + { + return this.bottomLeft; + }); + this.__defineGetter__("TopLeft", function() + { + return this.topLeft; + }); + this.__defineGetter__("TopRight", function() + { + return this.topRight; + }); +} + +function FinderPatternFinder() +{ + this.image=null; + this.possibleCenters = []; + this.hasSkipped = false; + this.crossCheckStateCount = new Array(0,0,0,0,0); + this.resultPointCallback = null; + + this.__defineGetter__("CrossCheckStateCount", function() + { + this.crossCheckStateCount[0] = 0; + this.crossCheckStateCount[1] = 0; + this.crossCheckStateCount[2] = 0; + this.crossCheckStateCount[3] = 0; + this.crossCheckStateCount[4] = 0; + return this.crossCheckStateCount; + }); + + this.foundPatternCross=function( stateCount) + { + var totalModuleSize = 0; + for (var i = 0; i < 5; i++) + { + var count = stateCount[i]; + if (count == 0) + { + return false; + } + totalModuleSize += count; + } + if (totalModuleSize < 7) + { + return false; + } + var moduleSize = Math.floor((totalModuleSize << INTEGER_MATH_SHIFT) / 7); + var maxVariance = Math.floor(moduleSize / 2); + // Allow less than 50% variance from 1-1-3-1-1 proportions + return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; + } + this.centerFromEnd=function( stateCount, end) + { + return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0; + } + this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal) + { + var image = this.image; + + var maxI = qrcode.height; + var stateCount = this.CrossCheckStateCount; + + // Start counting up from center + var i = startI; + while (i >= 0 && image[centerJ + i*qrcode.width]) + { + stateCount[2]++; + i--; + } + if (i < 0) + { + return NaN; + } + while (i >= 0 && !image[centerJ +i*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + i--; + } + // If already too many modules in this state or ran off the edge: + if (i < 0 || stateCount[1] > maxCount) + { + return NaN; + } + while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount) + { + stateCount[0]++; + i--; + } + if (stateCount[0] > maxCount) + { + return NaN; + } + + // Now also count down from center + i = startI + 1; + while (i < maxI && image[centerJ +i*qrcode.width]) + { + stateCount[2]++; + i++; + } + if (i == maxI) + { + return NaN; + } + while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[3] < maxCount) + { + stateCount[3]++; + i++; + } + if (i == maxI || stateCount[3] >= maxCount) + { + return NaN; + } + while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[4] < maxCount) + { + stateCount[4]++; + i++; + } + if (stateCount[4] >= maxCount) + { + return NaN; + } + + // If we found a finder-pattern-like section, but its size is more than 40% different than + // the original, assume it's a false positive + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; + if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) + { + return NaN; + } + + return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; + } + this.crossCheckHorizontal=function( startJ, centerI, maxCount, originalStateCountTotal) + { + var image = this.image; + + var maxJ = qrcode.width; + var stateCount = this.CrossCheckStateCount; + + var j = startJ; + while (j >= 0 && image[j+ centerI*qrcode.width]) + { + stateCount[2]++; + j--; + } + if (j < 0) + { + return NaN; + } + while (j >= 0 && !image[j+ centerI*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + j--; + } + if (j < 0 || stateCount[1] > maxCount) + { + return NaN; + } + while (j >= 0 && image[j+ centerI*qrcode.width] && stateCount[0] <= maxCount) + { + stateCount[0]++; + j--; + } + if (stateCount[0] > maxCount) + { + return NaN; + } + + j = startJ + 1; + while (j < maxJ && image[j+ centerI*qrcode.width]) + { + stateCount[2]++; + j++; + } + if (j == maxJ) + { + return NaN; + } + while (j < maxJ && !image[j+ centerI*qrcode.width] && stateCount[3] < maxCount) + { + stateCount[3]++; + j++; + } + if (j == maxJ || stateCount[3] >= maxCount) + { + return NaN; + } + while (j < maxJ && image[j+ centerI*qrcode.width] && stateCount[4] < maxCount) + { + stateCount[4]++; + j++; + } + if (stateCount[4] >= maxCount) + { + return NaN; + } + + // If we found a finder-pattern-like section, but its size is significantly different than + // the original, assume it's a false positive + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; + if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) + { + return NaN; + } + + return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, j):NaN; + } + this.handlePossibleCenter=function( stateCount, i, j) + { + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; + var centerJ = this.centerFromEnd(stateCount, j); //float + var centerI = this.crossCheckVertical(i, Math.floor( centerJ), stateCount[2], stateCountTotal); //float + if (!isNaN(centerI)) + { + // Re-cross check + centerJ = this.crossCheckHorizontal(Math.floor( centerJ), Math.floor( centerI), stateCount[2], stateCountTotal); + if (!isNaN(centerJ)) + { + var estimatedModuleSize = stateCountTotal / 7.0; + var found = false; + var max = this.possibleCenters.length; + for (var index = 0; index < max; index++) + { + var center = this.possibleCenters[index]; + // Look for about the same center and module size: + if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) + { + center.incrementCount(); + found = true; + break; + } + } + if (!found) + { + var point = new FinderPattern(centerJ, centerI, estimatedModuleSize); + this.possibleCenters.push(point); + if (this.resultPointCallback != null) + { + this.resultPointCallback.foundPossibleResultPoint(point); + } + } + return true; + } + } + return false; + } + + this.selectBestPatterns=function() + { + + var startSize = this.possibleCenters.length; + if (startSize < 3) + { + // Couldn't find enough finder patterns + throw "Couldn't find enough finder patterns"; + } + + // Filter outlier possibilities whose module size is too different + if (startSize > 3) + { + // But we can only afford to do so if we have at least 4 possibilities to choose from + var totalModuleSize = 0.0; + var square = 0.0; + for (var i = 0; i < startSize; i++) + { + //totalModuleSize += this.possibleCenters[i].EstimatedModuleSize; + var centerValue=this.possibleCenters[i].EstimatedModuleSize; + totalModuleSize += centerValue; + square += (centerValue * centerValue); + } + var average = totalModuleSize / startSize; + this.possibleCenters.sort(function(center1,center2) { + var dA=Math.abs(center2.EstimatedModuleSize - average); + var dB=Math.abs(center1.EstimatedModuleSize - average); + if (dA < dB) { + return (-1); + } else if (dA == dB) { + return 0; + } else { + return 1; + } + }); + + var stdDev = Math.sqrt(square / startSize - average * average); + var limit = Math.max(0.2 * average, stdDev); + for (var i = 0; i < this.possibleCenters.length && this.possibleCenters.length > 3; i++) + { + var pattern = this.possibleCenters[i]; + //if (Math.abs(pattern.EstimatedModuleSize - average) > 0.2 * average) + if (Math.abs(pattern.EstimatedModuleSize - average) > limit) + { + this.possibleCenters.remove(i); + i--; + } + } + } + + if (this.possibleCenters.length > 3) + { + // Throw away all but those first size candidate points we found. + this.possibleCenters.sort(function(a, b){ + if (a.count > b.count){return -1;} + if (a.count < b.count){return 1;} + return 0; + }); + } + + return new Array( this.possibleCenters[0], this.possibleCenters[1], this.possibleCenters[2]); + } + + this.findRowSkip=function() + { + var max = this.possibleCenters.length; + if (max <= 1) + { + return 0; + } + var firstConfirmedCenter = null; + for (var i = 0; i < max; i++) + { + var center = this.possibleCenters[i]; + if (center.Count >= CENTER_QUORUM) + { + if (firstConfirmedCenter == null) + { + firstConfirmedCenter = center; + } + else + { + // We have two confirmed centers + // How far down can we skip before resuming looking for the next + // pattern? In the worst case, only the difference between the + // difference in the x / y coordinates of the two centers. + // This is the case where you find top left last. + this.hasSkipped = true; + return Math.floor ((Math.abs(firstConfirmedCenter.X - center.X) - Math.abs(firstConfirmedCenter.Y - center.Y)) / 2); + } + } + } + return 0; + } + + this.haveMultiplyConfirmedCenters=function() + { + var confirmedCount = 0; + var totalModuleSize = 0.0; + var max = this.possibleCenters.length; + for (var i = 0; i < max; i++) + { + var pattern = this.possibleCenters[i]; + if (pattern.Count >= CENTER_QUORUM) + { + confirmedCount++; + totalModuleSize += pattern.EstimatedModuleSize; + } + } + if (confirmedCount < 3) + { + return false; + } + // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" + // and that we need to keep looking. We detect this by asking if the estimated module sizes + // vary too much. We arbitrarily say that when the total deviation from average exceeds + // 5% of the total module size estimates, it's too much. + var average = totalModuleSize / max; + var totalDeviation = 0.0; + for (var i = 0; i < max; i++) + { + pattern = this.possibleCenters[i]; + totalDeviation += Math.abs(pattern.EstimatedModuleSize - average); + } + return totalDeviation <= 0.05 * totalModuleSize; + } + + this.findFinderPattern = function(image){ + var tryHarder = false; + this.image=image; + var maxI = qrcode.height; + var maxJ = qrcode.width; + var iSkip = Math.floor((3 * maxI) / (4 * MAX_MODULES)); + if (iSkip < MIN_SKIP || tryHarder) + { + iSkip = MIN_SKIP; + } + + var done = false; + var stateCount = new Array(5); + for (var i = iSkip - 1; i < maxI && !done; i += iSkip) + { + // Get a row of black/white values + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + stateCount[3] = 0; + stateCount[4] = 0; + var currentState = 0; + for (var j = 0; j < maxJ; j++) + { + if (image[j+i*qrcode.width] ) + { + // Black pixel + if ((currentState & 1) == 1) + { + // Counting white pixels + currentState++; + } + stateCount[currentState]++; + } + else + { + // White pixel + if ((currentState & 1) == 0) + { + // Counting black pixels + if (currentState == 4) + { + // A winner? + if (this.foundPatternCross(stateCount)) + { + // Yes + var confirmed = this.handlePossibleCenter(stateCount, i, j); + if (confirmed) + { + // Start examining every other line. Checking each line turned out to be too + // expensive and didn't improve performance. + iSkip = 2; + if (this.hasSkipped) + { + done = this.haveMultiplyConfirmedCenters(); + } + else + { + var rowSkip = this.findRowSkip(); + if (rowSkip > stateCount[2]) + { + // Skip rows between row of lower confirmed center + // and top of presumed third confirmed center + // but back up a bit to get a full chance of detecting + // it, entire width of center of finder pattern + + // Skip by rowSkip, but back off by stateCount[2] (size of last center + // of pattern we saw) to be conservative, and also back off by iSkip which + // is about to be re-added + i += rowSkip - stateCount[2] - iSkip; + j = maxJ - 1; + } + } + } + else + { + // Advance to next black pixel + do + { + j++; + } + while (j < maxJ && !image[j + i*qrcode.width]); + j--; // back up to that last white pixel + } + // Clear state to start looking again + currentState = 0; + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + stateCount[3] = 0; + stateCount[4] = 0; + } + else + { + // No, shift counts back by two + stateCount[0] = stateCount[2]; + stateCount[1] = stateCount[3]; + stateCount[2] = stateCount[4]; + stateCount[3] = 1; + stateCount[4] = 0; + currentState = 3; + } + } + else + { + stateCount[++currentState]++; + } + } + else + { + // Counting white pixels + stateCount[currentState]++; + } + } + } + if (this.foundPatternCross(stateCount)) + { + var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); + if (confirmed) + { + iSkip = stateCount[0]; + if (this.hasSkipped) + { + // Found a third one + done = haveMultiplyConfirmedCenters(); + } + } + } + } + + var patternInfo = this.selectBestPatterns(); + qrcode.orderBestPatterns(patternInfo); + + return new FinderPatternInfo(patternInfo); + }; +} diff --git a/src/main/webapp/vendor/jsqrcode/formatinf.js b/src/main/webapp/vendor/jsqrcode/formatinf.js @@ -0,0 +1,104 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +var FORMAT_INFO_MASK_QR = 0x5412; +var FORMAT_INFO_DECODE_LOOKUP = new Array(new Array(0x5412, 0x00), new Array(0x5125, 0x01), new Array(0x5E7C, 0x02), new Array(0x5B4B, 0x03), new Array(0x45F9, 0x04), new Array(0x40CE, 0x05), new Array(0x4F97, 0x06), new Array(0x4AA0, 0x07), new Array(0x77C4, 0x08), new Array(0x72F3, 0x09), new Array(0x7DAA, 0x0A), new Array(0x789D, 0x0B), new Array(0x662F, 0x0C), new Array(0x6318, 0x0D), new Array(0x6C41, 0x0E), new Array(0x6976, 0x0F), new Array(0x1689, 0x10), new Array(0x13BE, 0x11), new Array(0x1CE7, 0x12), new Array(0x19D0, 0x13), new Array(0x0762, 0x14), new Array(0x0255, 0x15), new Array(0x0D0C, 0x16), new Array(0x083B, 0x17), new Array(0x355F, 0x18), new Array(0x3068, 0x19), new Array(0x3F31, 0x1A), new Array(0x3A06, 0x1B), new Array(0x24B4, 0x1C), new Array(0x2183, 0x1D), new Array(0x2EDA, 0x1E), new Array(0x2BED, 0x1F)); +var BITS_SET_IN_HALF_BYTE = new Array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); + + +function FormatInformation(formatInfo) +{ + this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); + this.dataMask = (formatInfo & 0x07); + + this.__defineGetter__("ErrorCorrectionLevel", function() + { + return this.errorCorrectionLevel; + }); + this.__defineGetter__("DataMask", function() + { + return this.dataMask; + }); + this.GetHashCode=function() + { + return (this.errorCorrectionLevel.ordinal() << 3) | dataMask; + } + this.Equals=function( o) + { + var other = o; + return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask; + } +} + +FormatInformation.numBitsDiffering=function( a, b) +{ + a ^= b; // a now has a 1 bit exactly where its bit differs with b's + // Count bits set quickly with a series of lookups: + return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 28) & 0x0F)]; +} + +FormatInformation.decodeFormatInformation=function( maskedFormatInfo) +{ + var formatInfo = FormatInformation.doDecodeFormatInformation(maskedFormatInfo); + if (formatInfo != null) + { + return formatInfo; + } + // Should return null, but, some QR codes apparently + // do not mask this info. Try again by actually masking the pattern + // first + return FormatInformation.doDecodeFormatInformation(maskedFormatInfo ^ FORMAT_INFO_MASK_QR); +} +FormatInformation.doDecodeFormatInformation=function( maskedFormatInfo) +{ + // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing + var bestDifference = 0xffffffff; + var bestFormatInfo = 0; + for (var i = 0; i < FORMAT_INFO_DECODE_LOOKUP.length; i++) + { + var decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; + var targetInfo = decodeInfo[0]; + if (targetInfo == maskedFormatInfo) + { + // Found an exact match + return new FormatInformation(decodeInfo[1]); + } + var bitsDifference = this.numBitsDiffering(maskedFormatInfo, targetInfo); + if (bitsDifference < bestDifference) + { + bestFormatInfo = decodeInfo[1]; + bestDifference = bitsDifference; + } + } + // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits + // differing means we found a match + if (bestDifference <= 3) + { + return new FormatInformation(bestFormatInfo); + } + return null; +} + + +\ No newline at end of file diff --git a/src/main/webapp/vendor/jsqrcode/gf256.js b/src/main/webapp/vendor/jsqrcode/gf256.js @@ -0,0 +1,117 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function GF256( primitive) +{ + this.expTable = new Array(256); + this.logTable = new Array(256); + var x = 1; + for (var i = 0; i < 256; i++) + { + this.expTable[i] = x; + x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 + if (x >= 0x100) + { + x ^= primitive; + } + } + for (var i = 0; i < 255; i++) + { + this.logTable[this.expTable[i]] = i; + } + // logTable[0] == 0 but this should never be used + var at0=new Array(1);at0[0]=0; + this.zero = new GF256Poly(this, new Array(at0)); + var at1=new Array(1);at1[0]=1; + this.one = new GF256Poly(this, new Array(at1)); + + this.__defineGetter__("Zero", function() + { + return this.zero; + }); + this.__defineGetter__("One", function() + { + return this.one; + }); + this.buildMonomial=function( degree, coefficient) + { + if (degree < 0) + { + throw "System.ArgumentException"; + } + if (coefficient == 0) + { + return zero; + } + var coefficients = new Array(degree + 1); + for(var i=0;i<coefficients.length;i++)coefficients[i]=0; + coefficients[0] = coefficient; + return new GF256Poly(this, coefficients); + } + this.exp=function( a) + { + return this.expTable[a]; + } + this.log=function( a) + { + if (a == 0) + { + throw "System.ArgumentException"; + } + return this.logTable[a]; + } + this.inverse=function( a) + { + if (a == 0) + { + throw "System.ArithmeticException"; + } + return this.expTable[255 - this.logTable[a]]; + } + this.multiply=function( a, b) + { + if (a == 0 || b == 0) + { + return 0; + } + if (a == 1) + { + return b; + } + if (b == 1) + { + return a; + } + return this.expTable[(this.logTable[a] + this.logTable[b]) % 255]; + } +} + +GF256.QR_CODE_FIELD = new GF256(0x011D); +GF256.DATA_MATRIX_FIELD = new GF256(0x012D); + +GF256.addOrSubtract=function( a, b) +{ + return a ^ b; +} +\ No newline at end of file diff --git a/src/main/webapp/vendor/jsqrcode/gf256poly.js b/src/main/webapp/vendor/jsqrcode/gf256poly.js @@ -0,0 +1,230 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function GF256Poly(field, coefficients) +{ + if (coefficients == null || coefficients.length == 0) + { + throw "System.ArgumentException"; + } + this.field = field; + var coefficientsLength = coefficients.length; + if (coefficientsLength > 1 && coefficients[0] == 0) + { + // Leading term must be non-zero for anything except the constant polynomial "0" + var firstNonZero = 1; + while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) + { + firstNonZero++; + } + if (firstNonZero == coefficientsLength) + { + this.coefficients = field.Zero.coefficients; + } + else + { + this.coefficients = new Array(coefficientsLength - firstNonZero); + for(var i=0;i<this.coefficients.length;i++)this.coefficients[i]=0; + //Array.Copy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length); + for(var ci=0;ci<this.coefficients.length;ci++)this.coefficients[ci]=coefficients[firstNonZero+ci]; + } + } + else + { + this.coefficients = coefficients; + } + + this.__defineGetter__("Zero", function() + { + return this.coefficients[0] == 0; + }); + this.__defineGetter__("Degree", function() + { + return this.coefficients.length - 1; + }); + this.__defineGetter__("Coefficients", function() + { + return this.coefficients; + }); + + this.getCoefficient=function( degree) + { + return this.coefficients[this.coefficients.length - 1 - degree]; + } + + this.evaluateAt=function( a) + { + if (a == 0) + { + // Just return the x^0 coefficient + return this.getCoefficient(0); + } + var size = this.coefficients.length; + if (a == 1) + { + // Just the sum of the coefficients + var result = 0; + for (var i = 0; i < size; i++) + { + result = GF256.addOrSubtract(result, this.coefficients[i]); + } + return result; + } + var result2 = this.coefficients[0]; + for (var i = 1; i < size; i++) + { + result2 = GF256.addOrSubtract(this.field.multiply(a, result2), this.coefficients[i]); + } + return result2; + } + + this.addOrSubtract=function( other) + { + if (this.field != other.field) + { + throw "GF256Polys do not have same GF256 field"; + } + if (this.Zero) + { + return other; + } + if (other.Zero) + { + return this; + } + + var smallerCoefficients = this.coefficients; + var largerCoefficients = other.coefficients; + if (smallerCoefficients.length > largerCoefficients.length) + { + var temp = smallerCoefficients; + smallerCoefficients = largerCoefficients; + largerCoefficients = temp; + } + var sumDiff = new Array(largerCoefficients.length); + var lengthDiff = largerCoefficients.length - smallerCoefficients.length; + // Copy high-order terms only found in higher-degree polynomial's coefficients + //Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); + for(var ci=0;ci<lengthDiff;ci++)sumDiff[ci]=largerCoefficients[ci]; + + for (var i = lengthDiff; i < largerCoefficients.length; i++) + { + sumDiff[i] = GF256.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); + } + + return new GF256Poly(field, sumDiff); + } + this.multiply1=function( other) + { + if (this.field!=other.field) + { + throw "GF256Polys do not have same GF256 field"; + } + if (this.Zero || other.Zero) + { + return this.field.Zero; + } + var aCoefficients = this.coefficients; + var aLength = aCoefficients.length; + var bCoefficients = other.coefficients; + var bLength = bCoefficients.length; + var product = new Array(aLength + bLength - 1); + for (var i = 0; i < aLength; i++) + { + var aCoeff = aCoefficients[i]; + for (var j = 0; j < bLength; j++) + { + product[i + j] = GF256.addOrSubtract(product[i + j], this.field.multiply(aCoeff, bCoefficients[j])); + } + } + return new GF256Poly(this.field, product); + } + this.multiply2=function( scalar) + { + if (scalar == 0) + { + return this.field.Zero; + } + if (scalar == 1) + { + return this; + } + var size = this.coefficients.length; + var product = new Array(size); + for (var i = 0; i < size; i++) + { + product[i] = this.field.multiply(this.coefficients[i], scalar); + } + return new GF256Poly(this.field, product); + } + this.multiplyByMonomial=function( degree, coefficient) + { + if (degree < 0) + { + throw "System.ArgumentException"; + } + if (coefficient == 0) + { + return this.field.Zero; + } + var size = this.coefficients.length; + var product = new Array(size + degree); + for(var i=0;i<product.length;i++)product[i]=0; + for (var i = 0; i < size; i++) + { + product[i] = this.field.multiply(this.coefficients[i], coefficient); + } + return new GF256Poly(this.field, product); + } + this.divide=function( other) + { + if (this.field!=other.field) + { + throw "GF256Polys do not have same GF256 field"; + } + if (other.Zero) + { + throw "Divide by 0"; + } + + var quotient = this.field.Zero; + var remainder = this; + + var denominatorLeadingTerm = other.getCoefficient(other.Degree); + var inverseDenominatorLeadingTerm = this.field.inverse(denominatorLeadingTerm); + + while (remainder.Degree >= other.Degree && !remainder.Zero) + { + var degreeDifference = remainder.Degree - other.Degree; + var scale = this.field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm); + var term = other.multiplyByMonomial(degreeDifference, scale); + var iterationQuotient = this.field.buildMonomial(degreeDifference, scale); + quotient = quotient.addOrSubtract(iterationQuotient); + remainder = remainder.addOrSubtract(term); + } + + return new Array(quotient, remainder); + } +} +\ No newline at end of file diff --git a/src/main/webapp/vendor/jsqrcode/grid.js b/src/main/webapp/vendor/jsqrcode/grid.js @@ -0,0 +1,152 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +GridSampler = {}; + +GridSampler.checkAndNudgePoints=function( image, points) + { + var width = qrcode.width; + var height = qrcode.height; + // Check and nudge points from start until we see some that are OK: + var nudged = true; + for (var offset = 0; offset < points.length && nudged; offset += 2) + { + var x = Math.floor (points[offset]); + var y = Math.floor( points[offset + 1]); + if (x < - 1 || x > width || y < - 1 || y > height) + { + throw "Error.checkAndNudgePoints "; + } + nudged = false; + if (x == - 1) + { + points[offset] = 0.0; + nudged = true; + } + else if (x == width) + { + points[offset] = width - 1; + nudged = true; + } + if (y == - 1) + { + points[offset + 1] = 0.0; + nudged = true; + } + else if (y == height) + { + points[offset + 1] = height - 1; + nudged = true; + } + } + // Check and nudge points from end: + nudged = true; + for (var offset = points.length - 2; offset >= 0 && nudged; offset -= 2) + { + var x = Math.floor( points[offset]); + var y = Math.floor( points[offset + 1]); + if (x < - 1 || x > width || y < - 1 || y > height) + { + throw "Error.checkAndNudgePoints "; + } + nudged = false; + if (x == - 1) + { + points[offset] = 0.0; + nudged = true; + } + else if (x == width) + { + points[offset] = width - 1; + nudged = true; + } + if (y == - 1) + { + points[offset + 1] = 0.0; + nudged = true; + } + else if (y == height) + { + points[offset + 1] = height - 1; + nudged = true; + } + } + } + + + +GridSampler.sampleGrid3=function( image, dimension, transform) + { + var bits = new BitMatrix(dimension); + var points = new Array(dimension << 1); + for (var y = 0; y < dimension; y++) + { + var max = points.length; + var iValue = y + 0.5; + for (var x = 0; x < max; x += 2) + { + points[x] = (x >> 1) + 0.5; + points[x + 1] = iValue; + } + transform.transformPoints1(points); + // Quick check to see if points transformed to something inside the image; + // sufficient to check the endpoints + GridSampler.checkAndNudgePoints(image, points); + try + { + for (var x = 0; x < max; x += 2) + { + var xpoint = (Math.floor( points[x]) * 4) + (Math.floor( points[x + 1]) * qrcode.width * 4); + var bit = image[Math.floor( points[x])+ qrcode.width* Math.floor( points[x + 1])]; + qrcode.imagedata.data[xpoint] = bit?255:0; + qrcode.imagedata.data[xpoint+1] = bit?255:0; + qrcode.imagedata.data[xpoint+2] = 0; + qrcode.imagedata.data[xpoint+3] = 255; + //bits[x >> 1][ y]=bit; + if(bit) + bits.set_Renamed(x >> 1, y); + } + } + catch ( aioobe) + { + // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting + // transform gets "twisted" such that it maps a straight line of points to a set of points + // whose endpoints are in bounds, but others are not. There is probably some mathematical + // way to detect this about the transformation that I don't know yet. + // This results in an ugly runtime exception despite our clever checks above -- can't have + // that. We could check each point's coordinates but that feels duplicative. We settle for + // catching and wrapping ArrayIndexOutOfBoundsException. + throw "Error.checkAndNudgePoints"; + } + } + return bits; + } + +GridSampler.sampleGridx=function( image, dimension, p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY) +{ + var transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); + + return GridSampler.sampleGrid3(image, dimension, transform); +} diff --git a/src/main/webapp/vendor/jsqrcode/qrcode.js b/src/main/webapp/vendor/jsqrcode/qrcode.js @@ -0,0 +1,319 @@ +/* + Copyright 2011 Lazar Laszlo (lazarsoft@gmail.com, www.lazarsoft.info) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + + +qrcode = {}; +qrcode.imagedata = null; +qrcode.width = 0; +qrcode.height = 0; +qrcode.qrCodeSymbol = null; +qrcode.debug = false; +qrcode.maxImgSize = 1024*1024; + +qrcode.sizeOfDataLengthInfo = [ [ 10, 9, 8, 8 ], [ 12, 11, 16, 10 ], [ 14, 13, 16, 12 ] ]; + +qrcode.callback = null; + +qrcode.decode = function(src){ + + if(arguments.length==0) + { + var canvas_qr = document.getElementById("qr-canvas"); + var context = canvas_qr.getContext('2d'); + qrcode.width = canvas_qr.width; + qrcode.height = canvas_qr.height; + qrcode.imagedata = context.getImageData(0, 0, qrcode.width, qrcode.height); + qrcode.result = qrcode.process(context); + if(qrcode.callback!=null) + qrcode.callback(qrcode.result); + return qrcode.result; + } + else + { + var image = new Image(); + image.onload=function(){ + //var canvas_qr = document.getElementById("qr-canvas"); + var canvas_qr = document.createElement('canvas'); + var context = canvas_qr.getContext('2d'); + var nheight = image.height; + var nwidth = image.width; + if(image.width*image.height>qrcode.maxImgSize) + { + var ir = image.width / image.height; + nheight = Math.sqrt(qrcode.maxImgSize/ir); + nwidth=ir*nheight; + } + + canvas_qr.width = nwidth; + canvas_qr.height = nheight; + + context.drawImage(image, 0, 0, canvas_qr.width, canvas_qr.height ); + qrcode.width = canvas_qr.width; + qrcode.height = canvas_qr.height; + try{ + qrcode.imagedata = context.getImageData(0, 0, canvas_qr.width, canvas_qr.height); + }catch(e){ + qrcode.result = "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!"; + if(qrcode.callback!=null) + qrcode.callback(qrcode.result); + return; + } + + try + { + qrcode.result = qrcode.process(context); + } + catch(e) + { + console.log(e); + qrcode.result = "error decoding QR Code"; + } + if(qrcode.callback!=null) + qrcode.callback(qrcode.result); + } + image.src = src; + } +} + +qrcode.isUrl = function(s) +{ + var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; + return regexp.test(s); +} + +qrcode.decode_url = function (s) +{ + var escaped = ""; + try{ + escaped = escape( s ); + } + catch(e) + { + console.log(e); + escaped = s; + } + var ret = ""; + try{ + ret = decodeURIComponent( escaped ); + } + catch(e) + { + console.log(e); + ret = escaped; + } + return ret; +} + +qrcode.decode_utf8 = function ( s ) +{ + if(qrcode.isUrl(s)) + return qrcode.decode_url(s); + else + return s; +} + +qrcode.process = function(ctx){ + + var start = new Date().getTime(); + + var image = qrcode.grayScaleToBitmap(qrcode.grayscale()); + //var image = qrcode.binarize(128); + + if(qrcode.debug) + { + for (var y = 0; y < qrcode.height; y++) + { + for (var x = 0; x < qrcode.width; x++) + { + var point = (x * 4) + (y * qrcode.width * 4); + qrcode.imagedata.data[point] = image[x+y*qrcode.width]?0:0; + qrcode.imagedata.data[point+1] = image[x+y*qrcode.width]?0:0; + qrcode.imagedata.data[point+2] = image[x+y*qrcode.width]?255:0; + } + } + ctx.putImageData(qrcode.imagedata, 0, 0); + } + + //var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image); + + var detector = new Detector(image); + + var qRCodeMatrix = detector.detect(); + + /*for (var y = 0; y < qRCodeMatrix.bits.Height; y++) + { + for (var x = 0; x < qRCodeMatrix.bits.Width; x++) + { + var point = (x * 4*2) + (y*2 * qrcode.width * 4); + qrcode.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0; + qrcode.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0; + qrcode.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0; + } + }*/ + if(qrcode.debug) + ctx.putImageData(qrcode.imagedata, 0, 0); + + var reader = Decoder.decode(qRCodeMatrix.bits); + var data = reader.DataByte; + var str=""; + for(var i=0;i<data.length;i++) + { + for(var j=0;j<data[i].length;j++) + str+=String.fromCharCode(data[i][j]); + } + + var end = new Date().getTime(); + var time = end - start; + console.log(time); + + return qrcode.decode_utf8(str); + //alert("Time:" + time + " Code: "+str); +} + +qrcode.getPixel = function(x,y){ + if (qrcode.width < x) { + throw "point error"; + } + if (qrcode.height < y) { + throw "point error"; + } + point = (x * 4) + (y * qrcode.width * 4); + p = (qrcode.imagedata.data[point]*33 + qrcode.imagedata.data[point + 1]*34 + qrcode.imagedata.data[point + 2]*33)/100; + return p; +} + +qrcode.binarize = function(th){ + var ret = new Array(qrcode.width*qrcode.height); + for (var y = 0; y < qrcode.height; y++) + { + for (var x = 0; x < qrcode.width; x++) + { + var gray = qrcode.getPixel(x, y); + + ret[x+y*qrcode.width] = gray<=th?true:false; + } + } + return ret; +} + +qrcode.getMiddleBrightnessPerArea=function(image) +{ + var numSqrtArea = 4; + //obtain middle brightness((min + max) / 2) per area + var areaWidth = Math.floor(qrcode.width / numSqrtArea); + var areaHeight = Math.floor(qrcode.height / numSqrtArea); + var minmax = new Array(numSqrtArea); + for (var i = 0; i < numSqrtArea; i++) + { + minmax[i] = new Array(numSqrtArea); + for (var i2 = 0; i2 < numSqrtArea; i2++) + { + minmax[i][i2] = new Array(0,0); + } + } + for (var ay = 0; ay < numSqrtArea; ay++) + { + for (var ax = 0; ax < numSqrtArea; ax++) + { + minmax[ax][ay][0] = 0xFF; + for (var dy = 0; dy < areaHeight; dy++) + { + for (var dx = 0; dx < areaWidth; dx++) + { + var target = image[areaWidth * ax + dx+(areaHeight * ay + dy)*qrcode.width]; + if (target < minmax[ax][ay][0]) + minmax[ax][ay][0] = target; + if (target > minmax[ax][ay][1]) + minmax[ax][ay][1] = target; + } + } + //minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2; + } + } + var middle = new Array(numSqrtArea); + for (var i3 = 0; i3 < numSqrtArea; i3++) + { + middle[i3] = new Array(numSqrtArea); + } + for (var ay = 0; ay < numSqrtArea; ay++) + { + for (var ax = 0; ax < numSqrtArea; ax++) + { + middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2); + //Console.out.print(middle[ax][ay] + ","); + } + //Console.out.println(""); + } + //Console.out.println(""); + + return middle; +} + +qrcode.grayScaleToBitmap=function(grayScale) +{ + var middle = qrcode.getMiddleBrightnessPerArea(grayScale); + var sqrtNumArea = middle.length; + var areaWidth = Math.floor(qrcode.width / sqrtNumArea); + var areaHeight = Math.floor(qrcode.height / sqrtNumArea); + var bitmap = new Array(qrcode.height*qrcode.width); + + for (var ay = 0; ay < sqrtNumArea; ay++) + { + for (var ax = 0; ax < sqrtNumArea; ax++) + { + for (var dy = 0; dy < areaHeight; dy++) + { + for (var dx = 0; dx < areaWidth; dx++) + { + bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] < middle[ax][ay])?true:false; + } + } + } + } + return bitmap; +} + +qrcode.grayscale = function(){ + var ret = new Array(qrcode.width*qrcode.height); + for (var y = 0; y < qrcode.height; y++) + { + for (var x = 0; x < qrcode.width; x++) + { + var gray = qrcode.getPixel(x, y); + + ret[x+y*qrcode.width] = gray; + } + } + return ret; +} + + + + +function URShift( number, bits) +{ + if (number >= 0) + return number >> bits; + else + return (number >> bits) + (2 << ~bits); +} + + +Array.prototype.remove = function(from, to) { + var rest = this.slice((to || from) + 1 || this.length); + this.length = from < 0 ? this.length + from : from; + return this.push.apply(this, rest); +}; diff --git a/src/main/webapp/vendor/jsqrcode/rsdecoder.js b/src/main/webapp/vendor/jsqrcode/rsdecoder.js @@ -0,0 +1,178 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function ReedSolomonDecoder(field) +{ + this.field = field; + this.decode=function(received, twoS) + { + var poly = new GF256Poly(this.field, received); + var syndromeCoefficients = new Array(twoS); + for(var i=0;i<syndromeCoefficients.length;i++)syndromeCoefficients[i]=0; + var dataMatrix = false;//this.field.Equals(GF256.DATA_MATRIX_FIELD); + var noError = true; + for (var i = 0; i < twoS; i++) + { + // Thanks to sanfordsquires for this fix: + var eval = poly.evaluateAt(this.field.exp(dataMatrix?i + 1:i)); + syndromeCoefficients[syndromeCoefficients.length - 1 - i] = eval; + if (eval != 0) + { + noError = false; + } + } + if (noError) + { + return ; + } + var syndrome = new GF256Poly(this.field, syndromeCoefficients); + var sigmaOmega = this.runEuclideanAlgorithm(this.field.buildMonomial(twoS, 1), syndrome, twoS); + var sigma = sigmaOmega[0]; + var omega = sigmaOmega[1]; + var errorLocations = this.findErrorLocations(sigma); + var errorMagnitudes = this.findErrorMagnitudes(omega, errorLocations, dataMatrix); + for (var i = 0; i < errorLocations.length; i++) + { + var position = received.length - 1 - this.field.log(errorLocations[i]); + if (position < 0) + { + throw "ReedSolomonException Bad error location"; + } + received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]); + } + } + + this.runEuclideanAlgorithm=function( a, b, R) + { + // Assume a's degree is >= b's + if (a.Degree < b.Degree) + { + var temp = a; + a = b; + b = temp; + } + + var rLast = a; + var r = b; + var sLast = this.field.One; + var s = this.field.Zero; + var tLast = this.field.Zero; + var t = this.field.One; + + // Run Euclidean algorithm until r's degree is less than R/2 + while (r.Degree >= Math.floor(R / 2)) + { + var rLastLast = rLast; + var sLastLast = sLast; + var tLastLast = tLast; + rLast = r; + sLast = s; + tLast = t; + + // Divide rLastLast by rLast, with quotient in q and remainder in r + if (rLast.Zero) + { + // Oops, Euclidean algorithm already terminated? + throw "r_{i-1} was zero"; + } + r = rLastLast; + var q = this.field.Zero; + var denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree); + var dltInverse = this.field.inverse(denominatorLeadingTerm); + while (r.Degree >= rLast.Degree && !r.Zero) + { + var degreeDiff = r.Degree - rLast.Degree; + var scale = this.field.multiply(r.getCoefficient(r.Degree), dltInverse); + q = q.addOrSubtract(this.field.buildMonomial(degreeDiff, scale)); + r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); + //r.EXE(); + } + + s = q.multiply1(sLast).addOrSubtract(sLastLast); + t = q.multiply1(tLast).addOrSubtract(tLastLast); + } + + var sigmaTildeAtZero = t.getCoefficient(0); + if (sigmaTildeAtZero == 0) + { + throw "ReedSolomonException sigmaTilde(0) was zero"; + } + + var inverse = this.field.inverse(sigmaTildeAtZero); + var sigma = t.multiply2(inverse); + var omega = r.multiply2(inverse); + return new Array(sigma, omega); + } + this.findErrorLocations=function( errorLocator) + { + // This is a direct application of Chien's search + var numErrors = errorLocator.Degree; + if (numErrors == 1) + { + // shortcut + return new Array(errorLocator.getCoefficient(1)); + } + var result = new Array(numErrors); + var e = 0; + for (var i = 1; i < 256 && e < numErrors; i++) + { + if (errorLocator.evaluateAt(i) == 0) + { + result[e] = this.field.inverse(i); + e++; + } + } + if (e != numErrors) + { + throw "Error locator degree does not match number of roots"; + } + return result; + } + this.findErrorMagnitudes=function( errorEvaluator, errorLocations, dataMatrix) + { + // This is directly applying Forney's Formula + var s = errorLocations.length; + var result = new Array(s); + for (var i = 0; i < s; i++) + { + var xiInverse = this.field.inverse(errorLocations[i]); + var denominator = 1; + for (var j = 0; j < s; j++) + { + if (i != j) + { + denominator = this.field.multiply(denominator, GF256.addOrSubtract(1, this.field.multiply(errorLocations[j], xiInverse))); + } + } + result[i] = this.field.multiply(errorEvaluator.evaluateAt(xiInverse), this.field.inverse(denominator)); + // Thanks to sanfordsquires for this fix: + if (dataMatrix) + { + result[i] = this.field.multiply(result[i], xiInverse); + } + } + return result; + } +} +\ No newline at end of file diff --git a/src/main/webapp/vendor/jsqrcode/test.html b/src/main/webapp/vendor/jsqrcode/test.html @@ -0,0 +1,149 @@ +<html> +<head> +<title>QRCODE</title> + +<style type="text/css"> +</style> + + +<script type="text/javascript" src="grid.js"></script> +<script type="text/javascript" src="version.js"></script> +<script type="text/javascript" src="detector.js"></script> +<script type="text/javascript" src="formatinf.js"></script> +<script type="text/javascript" src="errorlevel.js"></script> +<script type="text/javascript" src="bitmat.js"></script> +<script type="text/javascript" src="datablock.js"></script> +<script type="text/javascript" src="bmparser.js"></script> +<script type="text/javascript" src="datamask.js"></script> +<script type="text/javascript" src="rsdecoder.js"></script> +<script type="text/javascript" src="gf256poly.js"></script> +<script type="text/javascript" src="gf256.js"></script> +<script type="text/javascript" src="decoder.js"></script> +<script type="text/javascript" src="qrcode.js"></script> +<script type="text/javascript" src="findpat.js"></script> +<script type="text/javascript" src="alignpat.js"></script> +<script type="text/javascript" src="databr.js"></script> + +<script type="text/javascript"> +var gCtx = null; + var gCanvas = null; + + var imageData = null; + var ii=0; + var jj=0; + var c=0; + + +function dragenter(e) { + e.stopPropagation(); + e.preventDefault(); +} + +function dragover(e) { + e.stopPropagation(); + e.preventDefault(); +} +function drop(e) { + e.stopPropagation(); + e.preventDefault(); + + var dt = e.dataTransfer; + var files = dt.files; + + handleFiles(files); +} + +function handleFiles(f) +{ + var o=[]; + for(var i =0;i<f.length;i++) + { + var reader = new FileReader(); + + reader.onload = (function(theFile) { + return function(e) { + qrcode.decode(e.target.result); + }; + })(f[i]); + + // Read in the image file as a data URL. + reader.readAsDataURL(f[i]); } +} + +function read(a) +{ + alert(a); +} + +function load() +{ + initCanvas(640,480); + qrcode.callback = read; + qrcode.decode("meqrthumb.png"); +} + +function initCanvas(ww,hh) + { + gCanvas = document.getElementById("qr-canvas"); + gCanvas.addEventListener("dragenter", dragenter, false); + gCanvas.addEventListener("dragover", dragover, false); + gCanvas.addEventListener("drop", drop, false); + var w = ww; + var h = hh; + gCanvas.style.width = w + "px"; + gCanvas.style.height = h + "px"; + gCanvas.width = w; + gCanvas.height = h; + gCtx = gCanvas.getContext("2d"); + gCtx.clearRect(0, 0, w, h); + imageData = gCtx.getImageData( 0,0,320,240); + } + + function passLine(stringPixels) { + //a = (intVal >> 24) & 0xff; + + var coll = stringPixels.split("-"); + + for(var i=0;i<320;i++) { + var intVal = parseInt(coll[i]); + r = (intVal >> 16) & 0xff; + g = (intVal >> 8) & 0xff; + b = (intVal ) & 0xff; + imageData.data[c+0]=r; + imageData.data[c+1]=g; + imageData.data[c+2]=b; + imageData.data[c+3]=255; + c+=4; + } + + if(c>=320*240*4) { + c=0; + gCtx.putImageData(imageData, 0,0); + } + } + + function captureToCanvas() { + flash = document.getElementById("embedflash"); + flash.ccCapture(); + qrcode.decode(); + } +</script> + +</head> + +<body onload="load()"> + <div class="container"> + + <object id="iembedflash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="320" height="240"> + <param name="movie" value="camcanvas.swf" /> + <param name="quality" value="high" /> + <param name="allowScriptAccess" value="always" /> + <embed allowScriptAccess="always" id="embedflash" src="camcanvas.swf" quality="high" width="320" height="240" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" mayscript="true" /> + </object> + + </div> +<button onclick="captureToCanvas()">Capture</button><br> +<canvas id="qr-canvas" width="640" height="480"></canvas> +</body> + +</html> +\ No newline at end of file diff --git a/src/main/webapp/vendor/jsqrcode/version.js b/src/main/webapp/vendor/jsqrcode/version.js @@ -0,0 +1,261 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + + +function ECB(count, dataCodewords) +{ + this.count = count; + this.dataCodewords = dataCodewords; + + this.__defineGetter__("Count", function() + { + return this.count; + }); + this.__defineGetter__("DataCodewords", function() + { + return this.dataCodewords; + }); +} + +function ECBlocks( ecCodewordsPerBlock, ecBlocks1, ecBlocks2) +{ + this.ecCodewordsPerBlock = ecCodewordsPerBlock; + if(ecBlocks2) + this.ecBlocks = new Array(ecBlocks1, ecBlocks2); + else + this.ecBlocks = new Array(ecBlocks1); + + this.__defineGetter__("ECCodewordsPerBlock", function() + { + return this.ecCodewordsPerBlock; + }); + + this.__defineGetter__("TotalECCodewords", function() + { + return this.ecCodewordsPerBlock * this.NumBlocks; + }); + + this.__defineGetter__("NumBlocks", function() + { + var total = 0; + for (var i = 0; i < this.ecBlocks.length; i++) + { + total += this.ecBlocks[i].length; + } + return total; + }); + + this.getECBlocks=function() + { + return this.ecBlocks; + } +} + +function Version( versionNumber, alignmentPatternCenters, ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4) +{ + this.versionNumber = versionNumber; + this.alignmentPatternCenters = alignmentPatternCenters; + this.ecBlocks = new Array(ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4); + + var total = 0; + var ecCodewords = ecBlocks1.ECCodewordsPerBlock; + var ecbArray = ecBlocks1.getECBlocks(); + for (var i = 0; i < ecbArray.length; i++) + { + var ecBlock = ecbArray[i]; + total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); + } + this.totalCodewords = total; + + this.__defineGetter__("VersionNumber", function() + { + return this.versionNumber; + }); + + this.__defineGetter__("AlignmentPatternCenters", function() + { + return this.alignmentPatternCenters; + }); + this.__defineGetter__("TotalCodewords", function() + { + return this.totalCodewords; + }); + this.__defineGetter__("DimensionForVersion", function() + { + return 17 + 4 * this.versionNumber; + }); + + this.buildFunctionPattern=function() + { + var dimension = this.DimensionForVersion; + var bitMatrix = new BitMatrix(dimension); + + // Top left finder pattern + separator + format + bitMatrix.setRegion(0, 0, 9, 9); + // Top right finder pattern + separator + format + bitMatrix.setRegion(dimension - 8, 0, 8, 9); + // Bottom left finder pattern + separator + format + bitMatrix.setRegion(0, dimension - 8, 9, 8); + + // Alignment patterns + var max = this.alignmentPatternCenters.length; + for (var x = 0; x < max; x++) + { + var i = this.alignmentPatternCenters[x] - 2; + for (var y = 0; y < max; y++) + { + if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) + { + // No alignment patterns near the three finder paterns + continue; + } + bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5); + } + } + + // Vertical timing pattern + bitMatrix.setRegion(6, 9, 1, dimension - 17); + // Horizontal timing pattern + bitMatrix.setRegion(9, 6, dimension - 17, 1); + + if (this.versionNumber > 6) + { + // Version info, top right + bitMatrix.setRegion(dimension - 11, 0, 3, 6); + // Version info, bottom left + bitMatrix.setRegion(0, dimension - 11, 6, 3); + } + + return bitMatrix; + } + this.getECBlocksForLevel=function( ecLevel) + { + return this.ecBlocks[ecLevel.ordinal()]; + } +} + +Version.VERSION_DECODE_INFO = new Array(0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69); + +Version.VERSIONS = buildVersions(); + +Version.getVersionForNumber=function( versionNumber) +{ + if (versionNumber < 1 || versionNumber > 40) + { + throw "ArgumentException"; + } + return Version.VERSIONS[versionNumber - 1]; +} + +Version.getProvisionalVersionForDimension=function(dimension) +{ + if (dimension % 4 != 1) + { + throw "Error getProvisionalVersionForDimension"; + } + try + { + return Version.getVersionForNumber((dimension - 17) >> 2); + } + catch ( iae) + { + throw "Error getVersionForNumber"; + } +} + +Version.decodeVersionInformation=function( versionBits) +{ + var bestDifference = 0xffffffff; + var bestVersion = 0; + for (var i = 0; i < Version.VERSION_DECODE_INFO.length; i++) + { + var targetVersion = Version.VERSION_DECODE_INFO[i]; + // Do the version info bits match exactly? done. + if (targetVersion == versionBits) + { + return this.getVersionForNumber(i + 7); + } + // Otherwise see if this is the closest to a real version info bit string + // we have seen so far + var bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); + if (bitsDifference < bestDifference) + { + bestVersion = i + 7; + bestDifference = bitsDifference; + } + } + // We can tolerate up to 3 bits of error since no two version info codewords will + // differ in less than 4 bits. + if (bestDifference <= 3) + { + return this.getVersionForNumber(bestVersion); + } + // If we didn't find a close enough match, fail + return null; +} + +function buildVersions() +{ + return new Array(new Version(1, new Array(), new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))), + new Version(2, new Array(6, 18), new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))), + new Version(3, new Array(6, 22), new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))), + new Version(4, new Array(6, 26), new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))), + new Version(5, new Array(6, 30), new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))), + new Version(6, new Array(6, 34), new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))), + new Version(7, new Array(6, 22, 38), new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))), + new Version(8, new Array(6, 24, 42), new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))), + new Version(9, new Array(6, 26, 46), new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))), + new Version(10, new Array(6, 28, 50), new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))), + new Version(11, new Array(6, 30, 54), new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), + new Version(12, new Array(6, 32, 58), new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), + new Version(13, new Array(6, 34, 62), new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), + new Version(14, new Array(6, 26, 46, 66), new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), + new Version(15, new Array(6, 26, 48, 70), new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), + new Version(16, new Array(6, 26, 50, 74), new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), + new Version(17, new Array(6, 30, 54, 78), new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), + new Version(18, new Array(6, 30, 56, 82), new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), + new Version(19, new Array(6, 30, 58, 86), new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), + new Version(20, new Array(6, 34, 62, 90), new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), + new Version(21, new Array(6, 28, 50, 72, 94), new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), + new Version(22, new Array(6, 26, 50, 74, 98), new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), + new Version(23, new Array(6, 30, 54, 74, 102), new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), + new Version(24, new Array(6, 28, 54, 80, 106), new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), + new Version(25, new Array(6, 32, 58, 84, 110), new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), + new Version(26, new Array(6, 30, 58, 86, 114), new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), + new Version(27, new Array(6, 34, 62, 90, 118), new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))), + new Version(28, new Array(6, 26, 50, 74, 98, 122), new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), + new Version(29, new Array(6, 30, 54, 78, 102, 126), new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), + new Version(30, new Array(6, 26, 52, 78, 104, 130), new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), + new Version(31, new Array(6, 30, 56, 82, 108, 134), new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), + new Version(32, new Array(6, 34, 60, 86, 112, 138), new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), + new Version(33, new Array(6, 30, 58, 86, 114, 142), new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), + new Version(34, new Array(6, 34, 62, 90, 118, 146), new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), + new Version(35, new Array(6, 30, 54, 78, 102, 126, 150), new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)),new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), + new Version(36, new Array(6, 24, 50, 76, 102, 128, 154), new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), + new Version(37, new Array(6, 28, 54, 80, 106, 132, 158), new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), + new Version(38, new Array(6, 32, 58, 84, 110, 136, 162), new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), + new Version(39, new Array(6, 26, 54, 82, 110, 138, 166), new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), + new Version(40, new Array(6, 30, 58, 86, 114, 142, 170), new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16)))); +} +\ No newline at end of file diff --git a/src/main/webapp/vendor/underscore.min.js b/src/main/webapp/vendor/underscore.min.js @@ -0,0 +1,5 @@ +// Underscore.js 1.6.0 +// http://underscorejs.org +// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. +(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,g=e.filter,d=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,w=Object.keys,_=i.bind,j=function(n){return n instanceof j?n:this instanceof j?void(this._wrapped=n):new j(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=j),exports._=j):n._=j,j.VERSION="1.6.0";var A=j.each=j.forEach=function(n,t,e){if(null==n)return n;if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a=j.keys(n),u=0,i=a.length;i>u;u++)if(t.call(e,n[a[u]],a[u],n)===r)return;return n};j.map=j.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e.push(t.call(r,n,u,i))}),e)};var O="Reduce of empty array with no initial value";j.reduce=j.foldl=j.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=j.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},j.reduceRight=j.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=j.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=j.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},j.find=j.detect=function(n,t,r){var e;return k(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},j.filter=j.select=function(n,t,r){var e=[];return null==n?e:g&&n.filter===g?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&e.push(n)}),e)},j.reject=function(n,t,r){return j.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},j.every=j.all=function(n,t,e){t||(t=j.identity);var u=!0;return null==n?u:d&&n.every===d?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var k=j.some=j.any=function(n,t,e){t||(t=j.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};j.contains=j.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:k(n,function(n){return n===t})},j.invoke=function(n,t){var r=o.call(arguments,2),e=j.isFunction(t);return j.map(n,function(n){return(e?t:n[t]).apply(n,r)})},j.pluck=function(n,t){return j.map(n,j.property(t))},j.where=function(n,t){return j.filter(n,j.matches(t))},j.findWhere=function(n,t){return j.find(n,j.matches(t))},j.max=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.max.apply(Math,n);var e=-1/0,u=-1/0;return A(n,function(n,i,a){var o=t?t.call(r,n,i,a):n;o>u&&(e=n,u=o)}),e},j.min=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.min.apply(Math,n);var e=1/0,u=1/0;return A(n,function(n,i,a){var o=t?t.call(r,n,i,a):n;u>o&&(e=n,u=o)}),e},j.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=j.random(r++),e[r-1]=e[t],e[t]=n}),e},j.sample=function(n,t,r){return null==t||r?(n.length!==+n.length&&(n=j.values(n)),n[j.random(n.length-1)]):j.shuffle(n).slice(0,Math.max(0,t))};var E=function(n){return null==n?j.identity:j.isFunction(n)?n:j.property(n)};j.sortBy=function(n,t,r){return t=E(t),j.pluck(j.map(n,function(n,e,u){return{value:n,index:e,criteria:t.call(r,n,e,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=E(r),A(t,function(i,a){var o=r.call(e,i,a,t);n(u,o,i)}),u}};j.groupBy=F(function(n,t,r){j.has(n,t)?n[t].push(r):n[t]=[r]}),j.indexBy=F(function(n,t,r){n[t]=r}),j.countBy=F(function(n,t){j.has(n,t)?n[t]++:n[t]=1}),j.sortedIndex=function(n,t,r,e){r=E(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;r.call(e,n[o])<u?i=o+1:a=o}return i},j.toArray=function(n){return n?j.isArray(n)?o.call(n):n.length===+n.length?j.map(n,j.identity):j.values(n):[]},j.size=function(n){return null==n?0:n.length===+n.length?n.length:j.keys(n).length},j.first=j.head=j.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:0>t?[]:o.call(n,0,t)},j.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},j.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},j.rest=j.tail=j.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},j.compact=function(n){return j.filter(n,j.identity)};var M=function(n,t,r){return t&&j.every(n,j.isArray)?c.apply(r,n):(A(n,function(n){j.isArray(n)||j.isArguments(n)?t?a.apply(r,n):M(n,t,r):r.push(n)}),r)};j.flatten=function(n,t){return M(n,t,[])},j.without=function(n){return j.difference(n,o.call(arguments,1))},j.partition=function(n,t){var r=[],e=[];return A(n,function(n){(t(n)?r:e).push(n)}),[r,e]},j.uniq=j.unique=function(n,t,r,e){j.isFunction(t)&&(e=r,r=t,t=!1);var u=r?j.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:j.contains(a,r))||(a.push(r),i.push(n[e]))}),i},j.union=function(){return j.uniq(j.flatten(arguments,!0))},j.intersection=function(n){var t=o.call(arguments,1);return j.filter(j.uniq(n),function(n){return j.every(t,function(t){return j.contains(t,n)})})},j.difference=function(n){var t=c.apply(e,o.call(arguments,1));return j.filter(n,function(n){return!j.contains(t,n)})},j.zip=function(){for(var n=j.max(j.pluck(arguments,"length").concat(0)),t=new Array(n),r=0;n>r;r++)t[r]=j.pluck(arguments,""+r);return t},j.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},j.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=j.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},j.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},j.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=new Array(e);e>u;)i[u++]=n,n+=r;return i};var R=function(){};j.bind=function(n,t){var r,e;if(_&&n.bind===_)return _.apply(n,o.call(arguments,1));if(!j.isFunction(n))throw new TypeError;return r=o.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(o.call(arguments)));R.prototype=n.prototype;var u=new R;R.prototype=null;var i=n.apply(u,r.concat(o.call(arguments)));return Object(i)===i?i:u}},j.partial=function(n){var t=o.call(arguments,1);return function(){for(var r=0,e=t.slice(),u=0,i=e.length;i>u;u++)e[u]===j&&(e[u]=arguments[r++]);for(;r<arguments.length;)e.push(arguments[r++]);return n.apply(this,e)}},j.bindAll=function(n){var t=o.call(arguments,1);if(0===t.length)throw new Error("bindAll must be passed function names");return A(t,function(t){n[t]=j.bind(n[t],n)}),n},j.memoize=function(n,t){var r={};return t||(t=j.identity),function(){var e=t.apply(this,arguments);return j.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},j.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},j.defer=function(n){return j.delay.apply(j,[n,1].concat(o.call(arguments,1)))},j.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var c=function(){o=r.leading===!1?0:j.now(),a=null,i=n.apply(e,u),e=u=null};return function(){var l=j.now();o||r.leading!==!1||(o=l);var f=t-(l-o);return e=this,u=arguments,0>=f?(clearTimeout(a),a=null,o=l,i=n.apply(e,u),e=u=null):a||r.trailing===!1||(a=setTimeout(c,f)),i}},j.debounce=function(n,t,r){var e,u,i,a,o,c=function(){var l=j.now()-a;t>l?e=setTimeout(c,t-l):(e=null,r||(o=n.apply(i,u),i=u=null))};return function(){i=this,u=arguments,a=j.now();var l=r&&!e;return e||(e=setTimeout(c,t)),l&&(o=n.apply(i,u),i=u=null),o}},j.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},j.wrap=function(n,t){return j.partial(t,n)},j.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},j.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},j.keys=function(n){if(!j.isObject(n))return[];if(w)return w(n);var t=[];for(var r in n)j.has(n,r)&&t.push(r);return t},j.values=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},j.pairs=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},j.invert=function(n){for(var t={},r=j.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},j.functions=j.methods=function(n){var t=[];for(var r in n)j.isFunction(n[r])&&t.push(r);return t.sort()},j.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},j.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},j.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)j.contains(r,u)||(t[u]=n[u]);return t},j.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]===void 0&&(n[r]=t[r])}),n},j.clone=function(n){return j.isObject(n)?j.isArray(n)?n.slice():j.extend({},n):n},j.tap=function(n,t){return t(n),n};var S=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof j&&(n=n._wrapped),t instanceof j&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==String(t);case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;var a=n.constructor,o=t.constructor;if(a!==o&&!(j.isFunction(a)&&a instanceof a&&j.isFunction(o)&&o instanceof o)&&"constructor"in n&&"constructor"in t)return!1;r.push(n),e.push(t);var c=0,f=!0;if("[object Array]"==u){if(c=n.length,f=c==t.length)for(;c--&&(f=S(n[c],t[c],r,e)););}else{for(var s in n)if(j.has(n,s)&&(c++,!(f=j.has(t,s)&&S(n[s],t[s],r,e))))break;if(f){for(s in t)if(j.has(t,s)&&!c--)break;f=!c}}return r.pop(),e.pop(),f};j.isEqual=function(n,t){return S(n,t,[],[])},j.isEmpty=function(n){if(null==n)return!0;if(j.isArray(n)||j.isString(n))return 0===n.length;for(var t in n)if(j.has(n,t))return!1;return!0},j.isElement=function(n){return!(!n||1!==n.nodeType)},j.isArray=x||function(n){return"[object Array]"==l.call(n)},j.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){j["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),j.isArguments(arguments)||(j.isArguments=function(n){return!(!n||!j.has(n,"callee"))}),"function"!=typeof/./&&(j.isFunction=function(n){return"function"==typeof n}),j.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},j.isNaN=function(n){return j.isNumber(n)&&n!=+n},j.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},j.isNull=function(n){return null===n},j.isUndefined=function(n){return n===void 0},j.has=function(n,t){return f.call(n,t)},j.noConflict=function(){return n._=t,this},j.identity=function(n){return n},j.constant=function(n){return function(){return n}},j.property=function(n){return function(t){return t[n]}},j.matches=function(n){return function(t){if(t===n)return!0;for(var r in n)if(n[r]!==t[r])return!1;return!0}},j.times=function(n,t,r){for(var e=Array(Math.max(0,n)),u=0;n>u;u++)e[u]=t.call(r,u);return e},j.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},j.now=Date.now||function(){return(new Date).getTime()};var T={escape:{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"}};T.unescape=j.invert(T.escape);var I={escape:new RegExp("["+j.keys(T.escape).join("")+"]","g"),unescape:new RegExp("("+j.keys(T.unescape).join("|")+")","g")};j.each(["escape","unescape"],function(n){j[n]=function(t){return null==t?"":(""+t).replace(I[n],function(t){return T[n][t]})}}),j.result=function(n,t){if(null==n)return void 0;var r=n[t];return j.isFunction(r)?r.call(n):r},j.mixin=function(n){A(j.functions(n),function(t){var r=j[t]=n[t];j.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),z.call(this,r.apply(j,n))}})};var N=0;j.uniqueId=function(n){var t=++N+"";return n?n+t:t},j.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var q=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\t|\u2028|\u2029/g;j.template=function(n,t,r){var e;r=j.defaults({},r,j.templateSettings);var u=new RegExp([(r.escape||q).source,(r.interpolate||q).source,(r.evaluate||q).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(D,function(n){return"\\"+B[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=new Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,j);var c=function(n){return e.call(this,n,j)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},j.chain=function(n){return j(n).chain()};var z=function(n){return this._chain?j(n).chain():n};j.mixin(j),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];j.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],z.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];j.prototype[n]=function(){return z.call(this,t.apply(this._wrapped,arguments))}}),j.extend(j.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}}),"function"==typeof define&&define.amd&&define("underscore",[],function(){return j})}).call(this); +\ No newline at end of file