repo
string
commit
string
message
string
diff
string
toretore/barby
56093048a9b5ce247b3f8a3e3962cfda1182eb1c
Remove deprecated #has_rdoc from gemspec
diff --git a/barby.gemspec b/barby.gemspec index e46d226..2ff0401 100644 --- a/barby.gemspec +++ b/barby.gemspec @@ -1,23 +1,22 @@ $:.push File.expand_path("../lib", __FILE__) require "barby/version" Gem::Specification.new do |s| s.name = "barby" s.version = Barby::VERSION::STRING s.platform = Gem::Platform::RUBY s.summary = "The Ruby barcode generator" s.email = "toredarell@gmail.com" s.homepage = "http://toretore.github.com/barby" s.description = "Barby creates barcodes." s.authors = ['Tore Darell'] s.rubyforge_project = "barby" - s.has_rdoc = true s.extra_rdoc_files = ["README.md"] s.files = Dir['CHANGELOG', 'README.md', 'LICENSE', 'lib/**/*', 'vendor/**/*', 'bin/*'] #s.executables = ['barby'] #WIP, doesn't really work that well s.require_paths = ["lib"] end
toretore/barby
2b8ab03c47bc868d7f8fe67d3dfa1c18c2f16026
add codabar_test to test/barcodes
diff --git a/test/barcodes.rb b/test/barcodes.rb index c0e6e82..c5d2243 100644 --- a/test/barcodes.rb +++ b/test/barcodes.rb @@ -1,18 +1,20 @@ require 'code_128_test' require 'code_25_test' require 'code_25_interleaved_test' require 'code_25_iata_test' require 'code_39_test' require 'code_93_test' +require 'codabar_test' + require 'ean13_test' require 'ean8_test' require 'bookland_test' require 'upc_supplemental_test' require 'data_matrix_test' require 'qr_code_test' #require 'pdf_417_test'
toretore/barby
89da45aea3b9f53e2103161c47a1e545322b9540
Added support for Codabar
diff --git a/lib/barby/barcode/codabar.rb b/lib/barby/barcode/codabar.rb new file mode 100644 index 0000000..fe35807 --- /dev/null +++ b/lib/barby/barcode/codabar.rb @@ -0,0 +1,82 @@ +require "barby/barcode" + +module Barby + # https://en.wikipedia.org/wiki/Codabar + class Codabar < Barcode1D + BLACK_NARROW_WIDTH = 1 + WHITE_NARROW_WIDTH = 2 + WIDE_WIDTH_RATE = 3 + SPACING = 5 # must be equal to or wider than white narrow width + CHARACTERS = "0123456789-$:/.+ABCD".freeze + # even: black, odd: white + # 0: narrow, 1: wide + BINARY_EXPRESSION = [ + "0000011", # 0 + "0000110", # 1 + "0001001", # 2 + "1100000", # 3 + "0010010", # 4 + "1000010", # 5 + "0100001", # 6 + "0100100", # 7 + "0110000", # 8 + "1001000", # 9 + "0001100", # - + "0011000", # $ + "1000101", # : + "1010001", # / + "1010100", # . + "0010101", # + + "0011010", # A + "0101001", # B + "0001011", # C + "0001110", # D + ].each(&:freeze) + CHARACTER_TO_BINARY = Hash[CHARACTERS.chars.zip(BINARY_EXPRESSION)].freeze + FORMAT = /\A[ABCD][0123456789\-\$:\/\.\+]+[ABCD]\z/.freeze + ONE = "1".freeze + ZERO = "0".freeze + + attr_accessor :data, :black_narrow_width, :white_narrow_width, :wide_width_rate, :spacing + + def initialize(data) + self.data = data + raise ArgumentError, 'data not valid' unless valid? + + self.black_narrow_width = BLACK_NARROW_WIDTH + self.white_narrow_width = WHITE_NARROW_WIDTH + self.wide_width_rate = WIDE_WIDTH_RATE + self.spacing = SPACING + end + + def encoding + data.chars.map{|c| binary_to_bars(CHARACTER_TO_BINARY[c]) }.join(ZERO * spacing) + end + + def valid? + data =~ FORMAT + end + + private + def binary_to_bars(bin) + bin.chars.each_with_index.map{|c, i| + black = i % 2 == 0 + narrow = c == ZERO + + if black + if narrow + ONE * black_narrow_width + else + ONE * (black_narrow_width * wide_width_rate).to_i + end + else + if narrow + ZERO * white_narrow_width + else + ZERO * (white_narrow_width * wide_width_rate).to_i + end + end + }.join + end + end +end diff --git a/test/codabar_test.rb b/test/codabar_test.rb new file mode 100644 index 0000000..1201dc5 --- /dev/null +++ b/test/codabar_test.rb @@ -0,0 +1,58 @@ +require 'test_helper' +require 'barby/barcode/codabar' + +class CodabarTest < Barby::TestCase + + describe 'validations' do + + before do + @valid = Codabar.new('A12345D') + end + + it "should be valid with alphabet rounded numbers" do + assert @valid.valid? + end + + it "should not be valid with unsupported characters" do + @valid.data = "A12345E" + refute @valid.valid? + end + + it "should raise an exception when data is invalid" do + lambda{ Codabar.new('A12345E') }.must_raise(ArgumentError) + end + end + + describe 'data' do + + before do + @data = 'A12345D' + @code = Codabar.new(@data) + end + + it "should have the same data as was passed to it" do + @code.data.must_equal @data + end + end + + describe 'encoding' do + + before do + @code = Codabar.new('A01D') + @code.white_narrow_width = 1 + @code.black_narrow_width = 1 + @code.wide_width_rate = 2 + @code.spacing = 2 + end + + it "should have the expected encoding" do + @code.encoding.must_equal [ + "1011001001", # A + "101010011", # 0 + "101011001", # 1 + "1010011001", # D + ].join("00") + end + end +end +
toretore/barby
8d493d773f0dfadc21ef6700f9592464c1aa66af
Provide development dependency to easily setup test run for gem maintainers
diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..d2fceab --- /dev/null +++ b/Gemfile @@ -0,0 +1,5 @@ +source "https://rubygems.org" + +git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } + +gemspec diff --git a/barby.gemspec b/barby.gemspec index e46d226..7b5754f 100644 --- a/barby.gemspec +++ b/barby.gemspec @@ -1,23 +1,32 @@ $:.push File.expand_path("../lib", __FILE__) require "barby/version" Gem::Specification.new do |s| s.name = "barby" s.version = Barby::VERSION::STRING s.platform = Gem::Platform::RUBY s.summary = "The Ruby barcode generator" s.email = "toredarell@gmail.com" s.homepage = "http://toretore.github.com/barby" s.description = "Barby creates barcodes." s.authors = ['Tore Darell'] s.rubyforge_project = "barby" s.has_rdoc = true s.extra_rdoc_files = ["README.md"] - s.files = Dir['CHANGELOG', 'README.md', 'LICENSE', 'lib/**/*', 'vendor/**/*', 'bin/*'] - #s.executables = ['barby'] #WIP, doesn't really work that well + s.files = `git ls-files`.split("\n") + s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") + s.test_files.delete("test/outputter/rmagick_outputter_test.rb") + s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] + s.add_development_dependency "minitest", "~> 5.11" + s.add_development_dependency "bundler", "~> 1.16" + s.add_development_dependency "rake", "~> 10.0" + s.add_development_dependency "semacode-ruby19", "~> 0.7" + s.add_development_dependency "rqrcode", "~> 0.10" + s.add_development_dependency "prawn", "~> 2.2" + s.add_development_dependency "cairo", "~> 1.15" end diff --git a/test/outputter/rmagick_outputter_test.rb b/test/outputter/rmagick_outputter_test.rb index 8424af5..41870c7 100644 --- a/test/outputter/rmagick_outputter_test.rb +++ b/test/outputter/rmagick_outputter_test.rb @@ -1,83 +1,83 @@ require 'test_helper' class RmagickTestBarcode < Barby::Barcode def initialize(data) @data = data end def encoding @data end end class RmagickOutputterTest < Barby::TestCase before do load_outputter('rmagick') @barcode = RmagickTestBarcode.new('10110011100011110000') @outputter = RmagickOutputter.new(@barcode) end - + it "should register to_png, to_gif, to_jpg, to_image" do Barcode.outputters.must_include(:to_png) Barcode.outputters.must_include(:to_gif) Barcode.outputters.must_include(:to_jpg) Barcode.outputters.must_include(:to_image) end it "should have defined to_png, to_gif, to_jpg, to_image" do @outputter.must_respond_to(:to_png) @outputter.must_respond_to(:to_gif) @outputter.must_respond_to(:to_jpg) @outputter.must_respond_to(:to_image) end it "should return a string on to_png and to_gif" do @outputter.to_png.must_be_instance_of(String) @outputter.to_gif.must_be_instance_of(String) end it "should return a Magick::Image instance on to_image" do @outputter.to_image.must_be_instance_of(Magick::Image) end it "should have a width equal to the length of the barcode encoding string * x dimension" do @outputter.xdim.must_equal 1#Default @outputter.width.must_equal @outputter.barcode.encoding.length @outputter.xdim = 2 @outputter.width.must_equal @outputter.barcode.encoding.length * 2 end it "should have a full_width equal to the width + left and right margins" do @outputter.xdim.must_equal 1 @outputter.margin.must_equal 10 @outputter.full_width.must_equal (@outputter.width + 10 + 10) end it "should have a default height of 100" do @outputter.height.must_equal 100 @outputter.height = 200 @outputter.height.must_equal 200 end it "should have a full_height equal to the height + top and bottom margins" do @outputter.full_height.must_equal @outputter.height + (@outputter.margin * 2) end - + describe "#to_image" do - before do + before do @barcode = RmagickTestBarcode.new('10110011100011110000') @outputter = RmagickOutputter.new(@barcode) @image = @outputter.to_image end it "should have a width and height equal to the outputter's full_width and full_height" do @image.columns.must_equal @outputter.full_width @image.rows.must_equal @outputter.full_height end end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 588b71e..09f7db5 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,23 +1,24 @@ require 'rubygems' require 'barby' require 'minitest/autorun' require 'minitest/spec' module Barby class TestCase < MiniTest::Spec include Barby private # So we can register outputter during an full test suite run. def load_outputter(outputter) @loaded_outputter ||= load "barby/outputter/#{outputter}_outputter.rb" + rescue LoadError => e + skip "#{outputter} not being installed properly" end def ruby_19_or_greater? RUBY_VERSION >= '1.9' end - end end
toretore/barby
f6dd5ed325060c60c9979c96a6668ecd7eab8e4f
Why should we document a dependency for Ruby >=1.9
diff --git a/README.md b/README.md index cbeb9ee..003c6ef 100644 --- a/README.md +++ b/README.md @@ -1,108 +1,108 @@ # Barby Barby is a Ruby library that generates barcodes in a variety of symbologies. Its functionality is split into _barcode_ and "_outputter_" objects: * [`Barby::Barcode` objects] [symbologies] turn data into a binary representation for a given symbology. * [`Barby::Outputter`] [outputters] then takes this representation and turns it into images, PDF, etc. You can easily add a symbology without having to worry about graphical representation. If it can be represented as the usual 1D or 2D matrix of lines or squares, outputters will do that for you. Likewise, you can easily add an outputter for a format that doesn't have one yet, and it will work with all existing symbologies. For more information, check out [the Barby wiki][wiki]. ### New require policy Barcode symbologies are no longer required automatically, so you'll have to require the ones you need. If you need EAN-13, `require 'barby/barcode/ean_13'`. Full list of symbologies and filenames below. ## Example ```ruby require 'barby' require 'barby/barcode/code_128' require 'barby/outputter/ascii_outputter' barcode = Barby::Code128B.new('BARBY') puts barcode.to_ascii #Implicitly uses the AsciiOutputter ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## B A R B Y ``` ## Supported symbologies ```ruby require 'barby/barcode/<filename>' ``` -| Name | Filename | Dependencies | -| ----------------------------------- | --------------------- | ------------- | -| Code 25 | `code_25` | ─ | -| ├─ Interleaved | `code_25_interleaved` | ─ | -| └─ IATA | `code_25_iata` | ─ | -| Code 39 | `code_39` | ─ | -| └─ Extended | `code_39` | ─ | -| Code 93 | `code_93` | ─ | -| Code 128 (A, B, and C) | `code_128` | ─ | -| └─ GS1 128 | `gs1_128` | ─ | -| EAN-13 | `ean_13` | ─ | -| ├─ Bookland | `bookland` | ─ | -| └─ UPC-A | `ean_13` | ─ | -| EAN-8 | `ean_8` | ─ | -| UPC/EAN supplemental, 2 & 5 digits | `upc_supplemental` | ─ | -| QR Code | `qr_code` | `rqrcode` | -| DataMatrix (Semacode) | `data_matrix` | `semacode` | -| PDF417 | `pdf_417` | JRuby | +| Name | Filename | Dependencies | +| ----------------------------------- | --------------------- | ---------------------------------- | +| Code 25 | `code_25` | ─ | +| ├─ Interleaved | `code_25_interleaved` | ─ | +| └─ IATA | `code_25_iata` | ─ | +| Code 39 | `code_39` | ─ | +| └─ Extended | `code_39` | ─ | +| Code 93 | `code_93` | ─ | +| Code 128 (A, B, and C) | `code_128` | ─ | +| └─ GS1 128 | `gs1_128` | ─ | +| EAN-13 | `ean_13` | ─ | +| ├─ Bookland | `bookland` | ─ | +| └─ UPC-A | `ean_13` | ─ | +| EAN-8 | `ean_8` | ─ | +| UPC/EAN supplemental, 2 & 5 digits | `upc_supplemental` | ─ | +| QR Code | `qr_code` | `rqrcode` | +| DataMatrix (Semacode) | `data_matrix` | `semacode` or `semacode-ruby19` | +| PDF417 | `pdf_417` | JRuby | ## Outputters ```ruby require 'barby/outputter/<filename>_outputter' ``` | filename | dependencies | | ----------- | ------------- | | `ascii` | ─ | | `cairo` | cairo | | `html` | ─ | | `pdfwriter` | ─ | | `png` | chunky_png | | `prawn` | prawn | | `rmagick` | rmagick | | `svg` | ─ | ### Formats supported by outputters * Text (mostly for testing) * PNG, JPEG, GIF * PS, EPS * SVG * PDF * HTML --- For more information, check out [the Barby wiki][wiki]. [wiki]: https://github.com/toretore/barby/wiki [symbologies]: https://github.com/toretore/barby/wiki/Symbologies [outputters]: https://github.com/toretore/barby/wiki/Outputters
toretore/barby
22416627c454cdaa2e0046436615683702e5e025
whitespace
diff --git a/test/code_128_test.rb b/test/code_128_test.rb index 97728c1..81f60ef 100644 --- a/test/code_128_test.rb +++ b/test/code_128_test.rb @@ -1,471 +1,470 @@ # encoding: UTF-8 require 'test_helper' require 'barby/barcode/code_128' class Code128Test < Barby::TestCase %w[CODEA CODEB CODEC FNC1 FNC2 FNC3 FNC4 SHIFT].each do |const| const_set const, Code128.const_get(const) end before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do @code.send(:stop_encoding).must_equal '1100011101011' end it "should find the right class for a character A, B or C" do @code.send(:class_for, 'A').must_equal Code128A @code.send(:class_for, 'B').must_equal Code128B @code.send(:class_for, 'C').must_equal Code128C end it "should find the right change code for a class" do @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC end it "should not allow empty data" do lambda{ Code128B.new("") }.must_raise(ArgumentError) end describe "single encoding" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do @code.data.must_equal @data end it "should be able to change its data" do @code.data = '123ABC' @code.data.must_equal '123ABC' @code.data.wont_equal @data end it "should not have an extra" do assert @code.extra.nil? end it "should have empty extra encoding" do @code.extra_encoding.must_equal '' end it "should have the correct checksum" do @code.checksum.must_equal 66 end it "should return all data for to_s" do @code.to_s.must_equal @data end end describe "multiple encodings" do before do @data = binary_encode("ABC123\306def\3074567") @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do @code.full_data.must_equal "ABC123def4567" end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do @code.full_data_with_change_codes.must_equal @data end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = binary_encode("\3071234") code.full_data.must_equal "ABC1234" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234") code.extra.extra = binary_encode("\306abc") code.full_data.must_equal "ABC1234abc" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc") code.extra.extra.data = binary_encode("abc\305DEF") code.full_data.must_equal "ABC1234abcDEF" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc\305DEF") code.extra.extra.full_data.must_equal "abcDEF" code.extra.extra.full_data_with_change_codes.must_equal binary_encode("abc\305DEF") code.extra.full_data.must_equal "1234abcDEF" code.extra.full_data_with_change_codes.must_equal binary_encode("1234\306abc\305DEF") end it "should have a Code B extra" do @code.extra.must_be_instance_of(Code128B) end it "should have a valid extra" do assert @code.extra.valid? end it "the extra should also have an extra of type C" do @code.extra.extra.must_be_instance_of(Code128C) end it "the extra's extra should be valid" do assert @code.extra.extra.valid? end it "should not have more than two extras" do assert @code.extra.extra.extra.nil? end it "should split extra data from string on data assignment" do @code.data = binary_encode("123\306abc") @code.data.must_equal '123' @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal 'abc' end it "should be be able to change its extra" do @code.extra = binary_encode("\3071234") @code.extra.must_be_instance_of(Code128C) @code.extra.data.must_equal '1234' end it "should split extra data from string on extra assignment" do @code.extra = binary_encode("\306123\3074567") @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal '123' @code.extra.extra.must_be_instance_of(Code128C) @code.extra.extra.data.must_equal '4567' end it "should not fail on newlines in extras" do code = Code128B.new(binary_encode("ABC\305\n")) code.data.must_equal "ABC" code.extra.must_be_instance_of(Code128A) code.extra.data.must_equal "\n" code.extra.extra = binary_encode("\305\n\n\n\n\n\nVALID") code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" end it "should raise an exception when extra string doesn't start with the special code character" do lambda{ @code.extra = '123' }.must_raise ArgumentError end it "should have the correct checksum" do @code.checksum.must_equal 84 end it "should have the expected encoding" do - #STARTA A B C 1 2 3 + #STARTA A B C 1 2 3 @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ - #CODEB d e f - '10111101110100001001101011001000010110000100'+ - #CODEC 45 67 - '101110111101011101100010000101100'+ - #CHECK=84 STOP - '100111101001100011101011' + #CODEB d e f + '10111101110100001001101011001000010110000100'+ + #CODEC 45 67 + '101110111101011101100010000101100'+ + #CHECK=84 STOP + '100111101001100011101011' end it "should return all data including extras, except change codes for to_s" do @code.to_s.must_equal "ABC123def4567" end end describe "128A" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = 'abc123' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(A B C 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010000100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10010000110' end end describe "128B" do before do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = binary_encode("abc£123") refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(a b c 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010010000' end it "should have the expected data encoding" do @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '11011101110' end end describe "128C" do before do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = '123' refute @code.valid? @code.data = 'abc' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(12 34 56) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010011100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101100111001000101100011100010110' end it "should have the expected encoding" do @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10001101110' end end describe "Function characters" do it "should retain the special symbols in the data accessor" do Code128A.new(binary_encode("\301ABC\301DEF")).data.must_equal binary_encode("\301ABC\301DEF") Code128B.new(binary_encode("\301ABC\302DEF")).data.must_equal binary_encode("\301ABC\302DEF") Code128C.new(binary_encode("\301123456")).data.must_equal binary_encode("\301123456") Code128C.new(binary_encode("12\30134\30156")).data.must_equal binary_encode("12\30134\30156") end it "should keep the special symbols as characters" do Code128A.new(binary_encode("\301ABC\301DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \301 D E F)) Code128B.new(binary_encode("\301ABC\302DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \302 D E F)) Code128C.new(binary_encode("\301123456")).characters.must_equal binary_encode_array(%W(\301 12 34 56)) Code128C.new(binary_encode("12\30134\30156")).characters.must_equal binary_encode_array(%W(12 \301 34 \301 56)) end it "should not allow FNC > 1 for Code C" do lambda{ Code128C.new("12\302") }.must_raise ArgumentError lambda{ Code128C.new("\30312") }.must_raise ArgumentError lambda{ Code128C.new("12\304") }.must_raise ArgumentError end it "should be included in the encoding" do a = Code128A.new(binary_encode("\301AB")) a.data_encoding.must_equal '111101011101010001100010001011000' a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' end end describe "Code128 with type" do #it "should raise an exception when not given a type" do # lambda{ Code128.new('abc') }.must_raise(ArgumentError) #end it "should raise an exception when given a non-existent type" do lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) end it "should not fail on frozen type" do Code128.new('123456', 'C'.freeze) # not failing Code128.new('123456', 'c'.freeze) # not failing even when upcasing end it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end end describe "Code128 automatic charset" do =begin 5.4.7.7. Use of Start, Code Set, and Shift Characters to Minimize Symbol Length (Informative) - + The same data may be represented by different GS1-128 barcodes through the use of different combinations of Start, code set, and shift characters. - + The following rules should normally be implemented in printer control software to minimise the number of symbol characters needed to represent a given data string (and, therefore, reduce the overall symbol length). - + * Determine the Start Character: - If the data consists of two digits, use Start Character C. - If the data begins with four or more numeric data characters, use Start Character C. - If an ASCII symbology element (e.g., NUL) occurs in the data before any lowercase character, use Start Character A. - Otherwise, use Start Character B. * If Start Character C is used and the data begins with an odd number of numeric data characters, insert a code set A or code set B character before the last digit, following rules 1c and 1d to determine between code sets A and B. * If four or more numeric data characters occur together when in code sets A or B and: - If there is an even number of numeric data characters, then insert a code set C character before the first numeric digit to change to code set C. - If there is an odd number of numeric data characters, then insert a code set C character immediately after the first numeric digit to change to code set C. * When in code set B and an ASCII symbology element occurs in the data: - If following that character, a lowercase character occurs in the data before the occurrence of another symbology element, then insert a shift character before the symbology element. - Otherwise, insert a code set A character before the symbology element to change to code set A. * When in code set A and a lowercase character occurs in the data: - If following that character, a symbology element occurs in the data before the occurrence of another lowercase character, then insert a shift character before the lowercase character. - Otherwise, insert a code set B character before the lowercase character to change to code set B. When in code set C and a non-numeric character occurs in the data, insert a code set A or code set B character before that character, and follow rules 1c and 1d to determine between code sets A and B. - + Note: In these rules, the term “lowercase” is used for convenience to mean any code set B character with Code 128 Symbol character values 64 to 95 (ASCII values 96 to 127) (e.g., all lowercase alphanumeric characters plus `{|}~DEL). The term “symbology element” means any code set A character with Code 128 Symbol character values 64 to 95 (ASCII values 00 to 31). Note 2: If the Function 1 Symbol Character (FNC1) occurs in the first position following the Start Character, or in an odd-numbered position in a numeric field, it should be treated as two digits for the purpose of determining the appropriate code set. =end it "should minimize symbol length according to GS1-128 guidelines" do # Determine the Start Character. Code128.apply_shortest_encoding_for_data("#{FNC1}10").must_equal "#{CODEC}#{FNC1}10" Code128.apply_shortest_encoding_for_data("#{FNC1}101234").must_equal "#{CODEC}#{FNC1}101234" Code128.apply_shortest_encoding_for_data("10\001LOT").must_equal "#{CODEA}10\001LOT" Code128.apply_shortest_encoding_for_data("lot1").must_equal "#{CODEB}lot1" # Switching to codeset B from codeset C Code128.apply_shortest_encoding_for_data("#{FNC1}101").must_equal "#{CODEC}#{FNC1}10#{CODEB}1" # Switching to codeset A from codeset C Code128.apply_shortest_encoding_for_data("#{FNC1}10\001a").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}a" # Switching to codeset C from codeset A Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT#{CODEC}1234" Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT1#{CODEC}2345" # Switching to codeset C from codeset B Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}1234" Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT1#{CODEC}2345" # Switching to codeset A from codeset B Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001a").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{SHIFT}\001a" Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001\001").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{CODEA}\001\001" # Switching to codeset B from codeset A Code128.apply_shortest_encoding_for_data("#{FNC1}10\001l\001").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{SHIFT}l\001" Code128.apply_shortest_encoding_for_data("#{FNC1}10\001ll").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}ll" # testing "Note 2" from the GS1 specification Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}0101").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}#{FNC1}0101" Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}01010").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{FNC1}0#{CODEC}1010" Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT01#{FNC1}0101").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}01#{FNC1}0101" end it "should know how to extract CODEC segments properly from a data string" do Code128.send(:extract_codec, "1234abcd5678\r\n\r\n").must_equal ["1234", "abcd", "5678", "\r\n\r\n"] Code128.send(:extract_codec, "12345abc6").must_equal ["1234", "5abc6"] Code128.send(:extract_codec, "abcdef").must_equal ["abcdef"] Code128.send(:extract_codec, "123abcdef45678").must_equal ["123abcdef4", "5678"] Code128.send(:extract_codec, "abcd12345").must_equal ["abcd1", "2345"] Code128.send(:extract_codec, "abcd12345efg").must_equal ["abcd1", "2345", "efg"] Code128.send(:extract_codec, "12345").must_equal ["1234", "5"] Code128.send(:extract_codec, "12345abc").must_equal ["1234", "5abc"] Code128.send(:extract_codec, "abcdef1234567").must_equal ["abcdef1", "234567"] end it "should know how to most efficiently apply different encodings to a data string" do Code128.apply_shortest_encoding_for_data("123456").must_equal "#{CODEC}123456" Code128.apply_shortest_encoding_for_data("abcdef").must_equal "#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("ABCDEF").must_equal "#{CODEB}ABCDEF" Code128.apply_shortest_encoding_for_data("\n\t\r").must_equal "#{CODEA}\n\t\r" Code128.apply_shortest_encoding_for_data("123456abcdef").must_equal "#{CODEC}123456#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("abcdef123456").must_equal "#{CODEB}abcdef#{CODEC}123456" Code128.apply_shortest_encoding_for_data("1234567").must_equal "#{CODEC}123456#{CODEB}7" Code128.apply_shortest_encoding_for_data("123b456").must_equal "#{CODEB}123b456" Code128.apply_shortest_encoding_for_data("abc123def45678gh").must_equal "#{CODEB}abc123def4#{CODEC}5678#{CODEB}gh" Code128.apply_shortest_encoding_for_data("12345AB\nEEasdgr12EE\r\n").must_equal "#{CODEC}1234#{CODEA}5AB\nEE#{CODEB}asdgr12EE#{CODEA}\r\n" Code128.apply_shortest_encoding_for_data("123456QWERTY\r\n\tAAbbcc12XX34567").must_equal "#{CODEC}123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl" Code128.apply_shortest_encoding_for_data("ABC\rb\nDEF12gHI3456").must_equal "#{CODEA}ABC\r#{SHIFT}b\nDEF12#{CODEB}gHI#{CODEC}3456" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl\tMNop\nqRs").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl#{SHIFT}\tMNop#{SHIFT}\nqRs" end it "should apply automatic charset when no charset is given" do b = Code128.new("123456QWERTY\r\n\tAAbbcc12XX34567") b.type.must_equal 'C' b.full_data_with_change_codes.must_equal "123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" end end private def binary_encode_array(datas) datas.each { |data| binary_encode(data) } end def binary_encode(data) ruby_19_or_greater? ? data.force_encoding('BINARY') : data end end -
toretore/barby
01141e616b15c6a75c214c9c88ffb3e62521a63b
Remove commented assertion.
diff --git a/test/code_128_test.rb b/test/code_128_test.rb index 3fca166..97728c1 100644 --- a/test/code_128_test.rb +++ b/test/code_128_test.rb @@ -1,472 +1,471 @@ # encoding: UTF-8 require 'test_helper' require 'barby/barcode/code_128' class Code128Test < Barby::TestCase %w[CODEA CODEB CODEC FNC1 FNC2 FNC3 FNC4 SHIFT].each do |const| const_set const, Code128.const_get(const) end before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do @code.send(:stop_encoding).must_equal '1100011101011' end it "should find the right class for a character A, B or C" do @code.send(:class_for, 'A').must_equal Code128A @code.send(:class_for, 'B').must_equal Code128B @code.send(:class_for, 'C').must_equal Code128C end it "should find the right change code for a class" do @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC end it "should not allow empty data" do lambda{ Code128B.new("") }.must_raise(ArgumentError) end describe "single encoding" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do @code.data.must_equal @data end it "should be able to change its data" do @code.data = '123ABC' @code.data.must_equal '123ABC' @code.data.wont_equal @data end it "should not have an extra" do assert @code.extra.nil? end it "should have empty extra encoding" do @code.extra_encoding.must_equal '' end it "should have the correct checksum" do @code.checksum.must_equal 66 end it "should return all data for to_s" do @code.to_s.must_equal @data end end describe "multiple encodings" do before do @data = binary_encode("ABC123\306def\3074567") @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do @code.full_data.must_equal "ABC123def4567" end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do @code.full_data_with_change_codes.must_equal @data end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = binary_encode("\3071234") code.full_data.must_equal "ABC1234" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234") code.extra.extra = binary_encode("\306abc") code.full_data.must_equal "ABC1234abc" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc") code.extra.extra.data = binary_encode("abc\305DEF") code.full_data.must_equal "ABC1234abcDEF" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc\305DEF") code.extra.extra.full_data.must_equal "abcDEF" code.extra.extra.full_data_with_change_codes.must_equal binary_encode("abc\305DEF") code.extra.full_data.must_equal "1234abcDEF" code.extra.full_data_with_change_codes.must_equal binary_encode("1234\306abc\305DEF") end it "should have a Code B extra" do @code.extra.must_be_instance_of(Code128B) end it "should have a valid extra" do assert @code.extra.valid? end it "the extra should also have an extra of type C" do @code.extra.extra.must_be_instance_of(Code128C) end it "the extra's extra should be valid" do assert @code.extra.extra.valid? end it "should not have more than two extras" do assert @code.extra.extra.extra.nil? end it "should split extra data from string on data assignment" do @code.data = binary_encode("123\306abc") @code.data.must_equal '123' @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal 'abc' end it "should be be able to change its extra" do @code.extra = binary_encode("\3071234") @code.extra.must_be_instance_of(Code128C) @code.extra.data.must_equal '1234' end it "should split extra data from string on extra assignment" do @code.extra = binary_encode("\306123\3074567") @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal '123' @code.extra.extra.must_be_instance_of(Code128C) @code.extra.extra.data.must_equal '4567' end it "should not fail on newlines in extras" do code = Code128B.new(binary_encode("ABC\305\n")) code.data.must_equal "ABC" code.extra.must_be_instance_of(Code128A) code.extra.data.must_equal "\n" code.extra.extra = binary_encode("\305\n\n\n\n\n\nVALID") code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" end it "should raise an exception when extra string doesn't start with the special code character" do lambda{ @code.extra = '123' }.must_raise ArgumentError end it "should have the correct checksum" do @code.checksum.must_equal 84 end it "should have the expected encoding" do #STARTA A B C 1 2 3 @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ #CODEB d e f '10111101110100001001101011001000010110000100'+ #CODEC 45 67 '101110111101011101100010000101100'+ #CHECK=84 STOP '100111101001100011101011' end it "should return all data including extras, except change codes for to_s" do @code.to_s.must_equal "ABC123def4567" end end describe "128A" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = 'abc123' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(A B C 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010000100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10010000110' end end describe "128B" do before do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = binary_encode("abc£123") refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(a b c 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010010000' end it "should have the expected data encoding" do @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '11011101110' end end describe "128C" do before do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = '123' refute @code.valid? @code.data = 'abc' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(12 34 56) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010011100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101100111001000101100011100010110' end it "should have the expected encoding" do @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10001101110' end end describe "Function characters" do it "should retain the special symbols in the data accessor" do Code128A.new(binary_encode("\301ABC\301DEF")).data.must_equal binary_encode("\301ABC\301DEF") Code128B.new(binary_encode("\301ABC\302DEF")).data.must_equal binary_encode("\301ABC\302DEF") Code128C.new(binary_encode("\301123456")).data.must_equal binary_encode("\301123456") Code128C.new(binary_encode("12\30134\30156")).data.must_equal binary_encode("12\30134\30156") end it "should keep the special symbols as characters" do Code128A.new(binary_encode("\301ABC\301DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \301 D E F)) Code128B.new(binary_encode("\301ABC\302DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \302 D E F)) Code128C.new(binary_encode("\301123456")).characters.must_equal binary_encode_array(%W(\301 12 34 56)) Code128C.new(binary_encode("12\30134\30156")).characters.must_equal binary_encode_array(%W(12 \301 34 \301 56)) end it "should not allow FNC > 1 for Code C" do lambda{ Code128C.new("12\302") }.must_raise ArgumentError lambda{ Code128C.new("\30312") }.must_raise ArgumentError lambda{ Code128C.new("12\304") }.must_raise ArgumentError end it "should be included in the encoding" do a = Code128A.new(binary_encode("\301AB")) a.data_encoding.must_equal '111101011101010001100010001011000' a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' end end describe "Code128 with type" do #it "should raise an exception when not given a type" do # lambda{ Code128.new('abc') }.must_raise(ArgumentError) #end it "should raise an exception when given a non-existent type" do lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) end it "should not fail on frozen type" do Code128.new('123456', 'C'.freeze) # not failing Code128.new('123456', 'c'.freeze) # not failing even when upcasing end it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end end describe "Code128 automatic charset" do =begin 5.4.7.7. Use of Start, Code Set, and Shift Characters to Minimize Symbol Length (Informative) The same data may be represented by different GS1-128 barcodes through the use of different combinations of Start, code set, and shift characters. The following rules should normally be implemented in printer control software to minimise the number of symbol characters needed to represent a given data string (and, therefore, reduce the overall symbol length). * Determine the Start Character: - If the data consists of two digits, use Start Character C. - If the data begins with four or more numeric data characters, use Start Character C. - If an ASCII symbology element (e.g., NUL) occurs in the data before any lowercase character, use Start Character A. - Otherwise, use Start Character B. * If Start Character C is used and the data begins with an odd number of numeric data characters, insert a code set A or code set B character before the last digit, following rules 1c and 1d to determine between code sets A and B. * If four or more numeric data characters occur together when in code sets A or B and: - If there is an even number of numeric data characters, then insert a code set C character before the first numeric digit to change to code set C. - If there is an odd number of numeric data characters, then insert a code set C character immediately after the first numeric digit to change to code set C. * When in code set B and an ASCII symbology element occurs in the data: - If following that character, a lowercase character occurs in the data before the occurrence of another symbology element, then insert a shift character before the symbology element. - Otherwise, insert a code set A character before the symbology element to change to code set A. * When in code set A and a lowercase character occurs in the data: - If following that character, a symbology element occurs in the data before the occurrence of another lowercase character, then insert a shift character before the lowercase character. - Otherwise, insert a code set B character before the lowercase character to change to code set B. When in code set C and a non-numeric character occurs in the data, insert a code set A or code set B character before that character, and follow rules 1c and 1d to determine between code sets A and B. Note: In these rules, the term “lowercase” is used for convenience to mean any code set B character with Code 128 Symbol character values 64 to 95 (ASCII values 96 to 127) (e.g., all lowercase alphanumeric characters plus `{|}~DEL). The term “symbology element” means any code set A character with Code 128 Symbol character values 64 to 95 (ASCII values 00 to 31). Note 2: If the Function 1 Symbol Character (FNC1) occurs in the first position following the Start Character, or in an odd-numbered position in a numeric field, it should be treated as two digits for the purpose of determining the appropriate code set. =end it "should minimize symbol length according to GS1-128 guidelines" do # Determine the Start Character. Code128.apply_shortest_encoding_for_data("#{FNC1}10").must_equal "#{CODEC}#{FNC1}10" Code128.apply_shortest_encoding_for_data("#{FNC1}101234").must_equal "#{CODEC}#{FNC1}101234" Code128.apply_shortest_encoding_for_data("10\001LOT").must_equal "#{CODEA}10\001LOT" Code128.apply_shortest_encoding_for_data("lot1").must_equal "#{CODEB}lot1" # Switching to codeset B from codeset C Code128.apply_shortest_encoding_for_data("#{FNC1}101").must_equal "#{CODEC}#{FNC1}10#{CODEB}1" # Switching to codeset A from codeset C Code128.apply_shortest_encoding_for_data("#{FNC1}10\001a").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}a" # Switching to codeset C from codeset A Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT#{CODEC}1234" Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT1#{CODEC}2345" # Switching to codeset C from codeset B Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}1234" Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT1#{CODEC}2345" # Switching to codeset A from codeset B Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001a").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{SHIFT}\001a" Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001\001").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{CODEA}\001\001" # Switching to codeset B from codeset A Code128.apply_shortest_encoding_for_data("#{FNC1}10\001l\001").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{SHIFT}l\001" Code128.apply_shortest_encoding_for_data("#{FNC1}10\001ll").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}ll" # testing "Note 2" from the GS1 specification Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}0101").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}#{FNC1}0101" Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}01010").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{FNC1}0#{CODEC}1010" Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT01#{FNC1}0101").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}01#{FNC1}0101" end it "should know how to extract CODEC segments properly from a data string" do Code128.send(:extract_codec, "1234abcd5678\r\n\r\n").must_equal ["1234", "abcd", "5678", "\r\n\r\n"] Code128.send(:extract_codec, "12345abc6").must_equal ["1234", "5abc6"] Code128.send(:extract_codec, "abcdef").must_equal ["abcdef"] Code128.send(:extract_codec, "123abcdef45678").must_equal ["123abcdef4", "5678"] Code128.send(:extract_codec, "abcd12345").must_equal ["abcd1", "2345"] Code128.send(:extract_codec, "abcd12345efg").must_equal ["abcd1", "2345", "efg"] Code128.send(:extract_codec, "12345").must_equal ["1234", "5"] Code128.send(:extract_codec, "12345abc").must_equal ["1234", "5abc"] Code128.send(:extract_codec, "abcdef1234567").must_equal ["abcdef1", "234567"] end it "should know how to most efficiently apply different encodings to a data string" do - #Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT" Code128.apply_shortest_encoding_for_data("123456").must_equal "#{CODEC}123456" Code128.apply_shortest_encoding_for_data("abcdef").must_equal "#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("ABCDEF").must_equal "#{CODEB}ABCDEF" Code128.apply_shortest_encoding_for_data("\n\t\r").must_equal "#{CODEA}\n\t\r" Code128.apply_shortest_encoding_for_data("123456abcdef").must_equal "#{CODEC}123456#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("abcdef123456").must_equal "#{CODEB}abcdef#{CODEC}123456" Code128.apply_shortest_encoding_for_data("1234567").must_equal "#{CODEC}123456#{CODEB}7" Code128.apply_shortest_encoding_for_data("123b456").must_equal "#{CODEB}123b456" Code128.apply_shortest_encoding_for_data("abc123def45678gh").must_equal "#{CODEB}abc123def4#{CODEC}5678#{CODEB}gh" Code128.apply_shortest_encoding_for_data("12345AB\nEEasdgr12EE\r\n").must_equal "#{CODEC}1234#{CODEA}5AB\nEE#{CODEB}asdgr12EE#{CODEA}\r\n" Code128.apply_shortest_encoding_for_data("123456QWERTY\r\n\tAAbbcc12XX34567").must_equal "#{CODEC}123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl" Code128.apply_shortest_encoding_for_data("ABC\rb\nDEF12gHI3456").must_equal "#{CODEA}ABC\r#{SHIFT}b\nDEF12#{CODEB}gHI#{CODEC}3456" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl\tMNop\nqRs").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl#{SHIFT}\tMNop#{SHIFT}\nqRs" end it "should apply automatic charset when no charset is given" do b = Code128.new("123456QWERTY\r\n\tAAbbcc12XX34567") b.type.must_equal 'C' b.full_data_with_change_codes.must_equal "123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" end end private def binary_encode_array(datas) datas.each { |data| binary_encode(data) } end def binary_encode(data) ruby_19_or_greater? ? data.force_encoding('BINARY') : data end end
toretore/barby
54d876de2788c766fe0d7136935206f7be4cc77b
Add docstring from GS1 specification and corresponding tests
diff --git a/test/code_128_test.rb b/test/code_128_test.rb index ef77d1e..3fca166 100644 --- a/test/code_128_test.rb +++ b/test/code_128_test.rb @@ -1,441 +1,472 @@ # encoding: UTF-8 require 'test_helper' require 'barby/barcode/code_128' class Code128Test < Barby::TestCase %w[CODEA CODEB CODEC FNC1 FNC2 FNC3 FNC4 SHIFT].each do |const| const_set const, Code128.const_get(const) end before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do @code.send(:stop_encoding).must_equal '1100011101011' end it "should find the right class for a character A, B or C" do @code.send(:class_for, 'A').must_equal Code128A @code.send(:class_for, 'B').must_equal Code128B @code.send(:class_for, 'C').must_equal Code128C end it "should find the right change code for a class" do @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC end it "should not allow empty data" do lambda{ Code128B.new("") }.must_raise(ArgumentError) end describe "single encoding" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do @code.data.must_equal @data end it "should be able to change its data" do @code.data = '123ABC' @code.data.must_equal '123ABC' @code.data.wont_equal @data end it "should not have an extra" do assert @code.extra.nil? end it "should have empty extra encoding" do @code.extra_encoding.must_equal '' end it "should have the correct checksum" do @code.checksum.must_equal 66 end it "should return all data for to_s" do @code.to_s.must_equal @data end end describe "multiple encodings" do before do @data = binary_encode("ABC123\306def\3074567") @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do @code.full_data.must_equal "ABC123def4567" end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do @code.full_data_with_change_codes.must_equal @data end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = binary_encode("\3071234") code.full_data.must_equal "ABC1234" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234") code.extra.extra = binary_encode("\306abc") code.full_data.must_equal "ABC1234abc" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc") code.extra.extra.data = binary_encode("abc\305DEF") code.full_data.must_equal "ABC1234abcDEF" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc\305DEF") code.extra.extra.full_data.must_equal "abcDEF" code.extra.extra.full_data_with_change_codes.must_equal binary_encode("abc\305DEF") code.extra.full_data.must_equal "1234abcDEF" code.extra.full_data_with_change_codes.must_equal binary_encode("1234\306abc\305DEF") end it "should have a Code B extra" do @code.extra.must_be_instance_of(Code128B) end it "should have a valid extra" do assert @code.extra.valid? end it "the extra should also have an extra of type C" do @code.extra.extra.must_be_instance_of(Code128C) end it "the extra's extra should be valid" do assert @code.extra.extra.valid? end it "should not have more than two extras" do assert @code.extra.extra.extra.nil? end it "should split extra data from string on data assignment" do @code.data = binary_encode("123\306abc") @code.data.must_equal '123' @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal 'abc' end it "should be be able to change its extra" do @code.extra = binary_encode("\3071234") @code.extra.must_be_instance_of(Code128C) @code.extra.data.must_equal '1234' end it "should split extra data from string on extra assignment" do @code.extra = binary_encode("\306123\3074567") @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal '123' @code.extra.extra.must_be_instance_of(Code128C) @code.extra.extra.data.must_equal '4567' end it "should not fail on newlines in extras" do code = Code128B.new(binary_encode("ABC\305\n")) code.data.must_equal "ABC" code.extra.must_be_instance_of(Code128A) code.extra.data.must_equal "\n" code.extra.extra = binary_encode("\305\n\n\n\n\n\nVALID") code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" end it "should raise an exception when extra string doesn't start with the special code character" do lambda{ @code.extra = '123' }.must_raise ArgumentError end it "should have the correct checksum" do @code.checksum.must_equal 84 end it "should have the expected encoding" do #STARTA A B C 1 2 3 @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ #CODEB d e f '10111101110100001001101011001000010110000100'+ #CODEC 45 67 '101110111101011101100010000101100'+ #CHECK=84 STOP '100111101001100011101011' end it "should return all data including extras, except change codes for to_s" do @code.to_s.must_equal "ABC123def4567" end end describe "128A" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = 'abc123' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(A B C 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010000100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10010000110' end end describe "128B" do before do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = binary_encode("abc£123") refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(a b c 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010010000' end it "should have the expected data encoding" do @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '11011101110' end end describe "128C" do before do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = '123' refute @code.valid? @code.data = 'abc' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(12 34 56) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010011100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101100111001000101100011100010110' end it "should have the expected encoding" do @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10001101110' end end describe "Function characters" do it "should retain the special symbols in the data accessor" do Code128A.new(binary_encode("\301ABC\301DEF")).data.must_equal binary_encode("\301ABC\301DEF") Code128B.new(binary_encode("\301ABC\302DEF")).data.must_equal binary_encode("\301ABC\302DEF") Code128C.new(binary_encode("\301123456")).data.must_equal binary_encode("\301123456") Code128C.new(binary_encode("12\30134\30156")).data.must_equal binary_encode("12\30134\30156") end it "should keep the special symbols as characters" do Code128A.new(binary_encode("\301ABC\301DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \301 D E F)) Code128B.new(binary_encode("\301ABC\302DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \302 D E F)) Code128C.new(binary_encode("\301123456")).characters.must_equal binary_encode_array(%W(\301 12 34 56)) Code128C.new(binary_encode("12\30134\30156")).characters.must_equal binary_encode_array(%W(12 \301 34 \301 56)) end it "should not allow FNC > 1 for Code C" do lambda{ Code128C.new("12\302") }.must_raise ArgumentError lambda{ Code128C.new("\30312") }.must_raise ArgumentError lambda{ Code128C.new("12\304") }.must_raise ArgumentError end it "should be included in the encoding" do a = Code128A.new(binary_encode("\301AB")) a.data_encoding.must_equal '111101011101010001100010001011000' a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' end end describe "Code128 with type" do #it "should raise an exception when not given a type" do # lambda{ Code128.new('abc') }.must_raise(ArgumentError) #end it "should raise an exception when given a non-existent type" do lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) end it "should not fail on frozen type" do Code128.new('123456', 'C'.freeze) # not failing Code128.new('123456', 'c'.freeze) # not failing even when upcasing end it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end end describe "Code128 automatic charset" do - +=begin + 5.4.7.7. Use of Start, Code Set, and Shift Characters to Minimize Symbol Length (Informative) + + The same data may be represented by different GS1-128 barcodes through the use of different combinations of Start, code set, and shift characters. + + The following rules should normally be implemented in printer control software to minimise the number of symbol characters needed to represent a given data string (and, therefore, reduce the overall symbol length). + + * Determine the Start Character: + - If the data consists of two digits, use Start Character C. + - If the data begins with four or more numeric data characters, use Start Character C. + - If an ASCII symbology element (e.g., NUL) occurs in the data before any lowercase character, use Start Character A. + - Otherwise, use Start Character B. + * If Start Character C is used and the data begins with an odd number of numeric data characters, insert a code set A or code set B character before the last digit, following rules 1c and 1d to determine between code sets A and B. + * If four or more numeric data characters occur together when in code sets A or B and: + - If there is an even number of numeric data characters, then insert a code set C character before the first numeric digit to change to code set C. + - If there is an odd number of numeric data characters, then insert a code set C character immediately after the first numeric digit to change to code set C. + * When in code set B and an ASCII symbology element occurs in the data: + - If following that character, a lowercase character occurs in the data before the occurrence of another symbology element, then insert a shift character before the symbology element. + - Otherwise, insert a code set A character before the symbology element to change to code set A. + * When in code set A and a lowercase character occurs in the data: + - If following that character, a symbology element occurs in the data before the occurrence of another lowercase character, then insert a shift character before the lowercase character. + - Otherwise, insert a code set B character before the lowercase character to change to code set B. + When in code set C and a non-numeric character occurs in the data, insert a code set A or code set B character before that character, and follow rules 1c and 1d to determine between code sets A and B. + + Note: In these rules, the term “lowercase” is used for convenience to mean any code set B character with Code 128 Symbol character values 64 to 95 (ASCII values 96 to 127) (e.g., all lowercase alphanumeric characters plus `{|}~DEL). The term “symbology element” means any code set A character with Code 128 Symbol character values 64 to 95 (ASCII values 00 to 31). + Note 2: If the Function 1 Symbol Character (FNC1) occurs in the first position following the Start Character, or in an odd-numbered position in a numeric field, it should be treated as two digits for the purpose of determining the appropriate code set. +=end it "should minimize symbol length according to GS1-128 guidelines" do # Determine the Start Character. Code128.apply_shortest_encoding_for_data("#{FNC1}10").must_equal "#{CODEC}#{FNC1}10" Code128.apply_shortest_encoding_for_data("#{FNC1}101234").must_equal "#{CODEC}#{FNC1}101234" Code128.apply_shortest_encoding_for_data("10\001LOT").must_equal "#{CODEA}10\001LOT" Code128.apply_shortest_encoding_for_data("lot1").must_equal "#{CODEB}lot1" # Switching to codeset B from codeset C Code128.apply_shortest_encoding_for_data("#{FNC1}101").must_equal "#{CODEC}#{FNC1}10#{CODEB}1" # Switching to codeset A from codeset C Code128.apply_shortest_encoding_for_data("#{FNC1}10\001a").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}a" # Switching to codeset C from codeset A Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT#{CODEC}1234" Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT1#{CODEC}2345" # Switching to codeset C from codeset B Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}1234" Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT1#{CODEC}2345" # Switching to codeset A from codeset B Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001a").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{SHIFT}\001a" Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001\001").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{CODEA}\001\001" # Switching to codeset B from codeset A Code128.apply_shortest_encoding_for_data("#{FNC1}10\001l\001").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{SHIFT}l\001" Code128.apply_shortest_encoding_for_data("#{FNC1}10\001ll").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}ll" + + # testing "Note 2" from the GS1 specification + Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}0101").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}#{FNC1}0101" + Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT#{FNC1}01010").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{FNC1}0#{CODEC}1010" + Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT01#{FNC1}0101").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}01#{FNC1}0101" end it "should know how to extract CODEC segments properly from a data string" do Code128.send(:extract_codec, "1234abcd5678\r\n\r\n").must_equal ["1234", "abcd", "5678", "\r\n\r\n"] Code128.send(:extract_codec, "12345abc6").must_equal ["1234", "5abc6"] Code128.send(:extract_codec, "abcdef").must_equal ["abcdef"] Code128.send(:extract_codec, "123abcdef45678").must_equal ["123abcdef4", "5678"] Code128.send(:extract_codec, "abcd12345").must_equal ["abcd1", "2345"] Code128.send(:extract_codec, "abcd12345efg").must_equal ["abcd1", "2345", "efg"] Code128.send(:extract_codec, "12345").must_equal ["1234", "5"] Code128.send(:extract_codec, "12345abc").must_equal ["1234", "5abc"] Code128.send(:extract_codec, "abcdef1234567").must_equal ["abcdef1", "234567"] end it "should know how to most efficiently apply different encodings to a data string" do #Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT" Code128.apply_shortest_encoding_for_data("123456").must_equal "#{CODEC}123456" Code128.apply_shortest_encoding_for_data("abcdef").must_equal "#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("ABCDEF").must_equal "#{CODEB}ABCDEF" Code128.apply_shortest_encoding_for_data("\n\t\r").must_equal "#{CODEA}\n\t\r" Code128.apply_shortest_encoding_for_data("123456abcdef").must_equal "#{CODEC}123456#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("abcdef123456").must_equal "#{CODEB}abcdef#{CODEC}123456" Code128.apply_shortest_encoding_for_data("1234567").must_equal "#{CODEC}123456#{CODEB}7" Code128.apply_shortest_encoding_for_data("123b456").must_equal "#{CODEB}123b456" Code128.apply_shortest_encoding_for_data("abc123def45678gh").must_equal "#{CODEB}abc123def4#{CODEC}5678#{CODEB}gh" Code128.apply_shortest_encoding_for_data("12345AB\nEEasdgr12EE\r\n").must_equal "#{CODEC}1234#{CODEA}5AB\nEE#{CODEB}asdgr12EE#{CODEA}\r\n" Code128.apply_shortest_encoding_for_data("123456QWERTY\r\n\tAAbbcc12XX34567").must_equal "#{CODEC}123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl" Code128.apply_shortest_encoding_for_data("ABC\rb\nDEF12gHI3456").must_equal "#{CODEA}ABC\r#{SHIFT}b\nDEF12#{CODEB}gHI#{CODEC}3456" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl\tMNop\nqRs").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl#{SHIFT}\tMNop#{SHIFT}\nqRs" end it "should apply automatic charset when no charset is given" do b = Code128.new("123456QWERTY\r\n\tAAbbcc12XX34567") b.type.must_equal 'C' b.full_data_with_change_codes.must_equal "123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" end end private def binary_encode_array(datas) datas.each { |data| binary_encode(data) } end def binary_encode(data) ruby_19_or_greater? ? data.force_encoding('BINARY') : data end end
toretore/barby
3bae82ebf17261beadd7d474d31b3dbb45b5ce8f
Write tests for cases in 5.4.7.7 of the GS1 spec version 15
diff --git a/test/code_128_test.rb b/test/code_128_test.rb index 807e196..ef77d1e 100644 --- a/test/code_128_test.rb +++ b/test/code_128_test.rb @@ -1,412 +1,441 @@ # encoding: UTF-8 require 'test_helper' require 'barby/barcode/code_128' class Code128Test < Barby::TestCase %w[CODEA CODEB CODEC FNC1 FNC2 FNC3 FNC4 SHIFT].each do |const| const_set const, Code128.const_get(const) end before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do @code.send(:stop_encoding).must_equal '1100011101011' end it "should find the right class for a character A, B or C" do @code.send(:class_for, 'A').must_equal Code128A @code.send(:class_for, 'B').must_equal Code128B @code.send(:class_for, 'C').must_equal Code128C end it "should find the right change code for a class" do @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC end it "should not allow empty data" do lambda{ Code128B.new("") }.must_raise(ArgumentError) end describe "single encoding" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do @code.data.must_equal @data end it "should be able to change its data" do @code.data = '123ABC' @code.data.must_equal '123ABC' @code.data.wont_equal @data end it "should not have an extra" do assert @code.extra.nil? end it "should have empty extra encoding" do @code.extra_encoding.must_equal '' end it "should have the correct checksum" do @code.checksum.must_equal 66 end it "should return all data for to_s" do @code.to_s.must_equal @data end end describe "multiple encodings" do before do @data = binary_encode("ABC123\306def\3074567") @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do @code.full_data.must_equal "ABC123def4567" end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do @code.full_data_with_change_codes.must_equal @data end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = binary_encode("\3071234") code.full_data.must_equal "ABC1234" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234") code.extra.extra = binary_encode("\306abc") code.full_data.must_equal "ABC1234abc" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc") code.extra.extra.data = binary_encode("abc\305DEF") code.full_data.must_equal "ABC1234abcDEF" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc\305DEF") code.extra.extra.full_data.must_equal "abcDEF" code.extra.extra.full_data_with_change_codes.must_equal binary_encode("abc\305DEF") code.extra.full_data.must_equal "1234abcDEF" code.extra.full_data_with_change_codes.must_equal binary_encode("1234\306abc\305DEF") end it "should have a Code B extra" do @code.extra.must_be_instance_of(Code128B) end it "should have a valid extra" do assert @code.extra.valid? end it "the extra should also have an extra of type C" do @code.extra.extra.must_be_instance_of(Code128C) end it "the extra's extra should be valid" do assert @code.extra.extra.valid? end it "should not have more than two extras" do assert @code.extra.extra.extra.nil? end it "should split extra data from string on data assignment" do @code.data = binary_encode("123\306abc") @code.data.must_equal '123' @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal 'abc' end it "should be be able to change its extra" do @code.extra = binary_encode("\3071234") @code.extra.must_be_instance_of(Code128C) @code.extra.data.must_equal '1234' end it "should split extra data from string on extra assignment" do @code.extra = binary_encode("\306123\3074567") @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal '123' @code.extra.extra.must_be_instance_of(Code128C) @code.extra.extra.data.must_equal '4567' end it "should not fail on newlines in extras" do code = Code128B.new(binary_encode("ABC\305\n")) code.data.must_equal "ABC" code.extra.must_be_instance_of(Code128A) code.extra.data.must_equal "\n" code.extra.extra = binary_encode("\305\n\n\n\n\n\nVALID") code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" end it "should raise an exception when extra string doesn't start with the special code character" do lambda{ @code.extra = '123' }.must_raise ArgumentError end it "should have the correct checksum" do @code.checksum.must_equal 84 end it "should have the expected encoding" do #STARTA A B C 1 2 3 @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ #CODEB d e f '10111101110100001001101011001000010110000100'+ #CODEC 45 67 '101110111101011101100010000101100'+ #CHECK=84 STOP '100111101001100011101011' end it "should return all data including extras, except change codes for to_s" do @code.to_s.must_equal "ABC123def4567" end end describe "128A" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = 'abc123' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(A B C 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010000100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10010000110' end end describe "128B" do before do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = binary_encode("abc£123") refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(a b c 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010010000' end it "should have the expected data encoding" do @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '11011101110' end end describe "128C" do before do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = '123' refute @code.valid? @code.data = 'abc' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(12 34 56) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010011100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101100111001000101100011100010110' end it "should have the expected encoding" do @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10001101110' end end describe "Function characters" do it "should retain the special symbols in the data accessor" do Code128A.new(binary_encode("\301ABC\301DEF")).data.must_equal binary_encode("\301ABC\301DEF") Code128B.new(binary_encode("\301ABC\302DEF")).data.must_equal binary_encode("\301ABC\302DEF") Code128C.new(binary_encode("\301123456")).data.must_equal binary_encode("\301123456") Code128C.new(binary_encode("12\30134\30156")).data.must_equal binary_encode("12\30134\30156") end it "should keep the special symbols as characters" do Code128A.new(binary_encode("\301ABC\301DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \301 D E F)) Code128B.new(binary_encode("\301ABC\302DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \302 D E F)) Code128C.new(binary_encode("\301123456")).characters.must_equal binary_encode_array(%W(\301 12 34 56)) Code128C.new(binary_encode("12\30134\30156")).characters.must_equal binary_encode_array(%W(12 \301 34 \301 56)) end it "should not allow FNC > 1 for Code C" do lambda{ Code128C.new("12\302") }.must_raise ArgumentError lambda{ Code128C.new("\30312") }.must_raise ArgumentError lambda{ Code128C.new("12\304") }.must_raise ArgumentError end it "should be included in the encoding" do a = Code128A.new(binary_encode("\301AB")) a.data_encoding.must_equal '111101011101010001100010001011000' a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' end end describe "Code128 with type" do #it "should raise an exception when not given a type" do # lambda{ Code128.new('abc') }.must_raise(ArgumentError) #end it "should raise an exception when given a non-existent type" do lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) end it "should not fail on frozen type" do Code128.new('123456', 'C'.freeze) # not failing Code128.new('123456', 'c'.freeze) # not failing even when upcasing end it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end end describe "Code128 automatic charset" do + it "should minimize symbol length according to GS1-128 guidelines" do + # Determine the Start Character. + Code128.apply_shortest_encoding_for_data("#{FNC1}10").must_equal "#{CODEC}#{FNC1}10" + Code128.apply_shortest_encoding_for_data("#{FNC1}101234").must_equal "#{CODEC}#{FNC1}101234" + Code128.apply_shortest_encoding_for_data("10\001LOT").must_equal "#{CODEA}10\001LOT" + Code128.apply_shortest_encoding_for_data("lot1").must_equal "#{CODEB}lot1" + + # Switching to codeset B from codeset C + Code128.apply_shortest_encoding_for_data("#{FNC1}101").must_equal "#{CODEC}#{FNC1}10#{CODEB}1" + # Switching to codeset A from codeset C + Code128.apply_shortest_encoding_for_data("#{FNC1}10\001a").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}a" + + # Switching to codeset C from codeset A + Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT#{CODEC}1234" + Code128.apply_shortest_encoding_for_data("#{FNC1}10\001LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001LOT1#{CODEC}2345" + + # Switching to codeset C from codeset B + Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT1234").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT#{CODEC}1234" + Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT12345").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT1#{CODEC}2345" + + # Switching to codeset A from codeset B + Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001a").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{SHIFT}\001a" + Code128.apply_shortest_encoding_for_data("#{FNC1}10lot\001\001").must_equal "#{CODEC}#{FNC1}10#{CODEB}lot#{CODEA}\001\001" + + # Switching to codeset B from codeset A + Code128.apply_shortest_encoding_for_data("#{FNC1}10\001l\001").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{SHIFT}l\001" + Code128.apply_shortest_encoding_for_data("#{FNC1}10\001ll").must_equal "#{CODEC}#{FNC1}10#{CODEA}\001#{CODEB}ll" + end + it "should know how to extract CODEC segments properly from a data string" do Code128.send(:extract_codec, "1234abcd5678\r\n\r\n").must_equal ["1234", "abcd", "5678", "\r\n\r\n"] Code128.send(:extract_codec, "12345abc6").must_equal ["1234", "5abc6"] Code128.send(:extract_codec, "abcdef").must_equal ["abcdef"] Code128.send(:extract_codec, "123abcdef45678").must_equal ["123abcdef4", "5678"] Code128.send(:extract_codec, "abcd12345").must_equal ["abcd1", "2345"] Code128.send(:extract_codec, "abcd12345efg").must_equal ["abcd1", "2345", "efg"] Code128.send(:extract_codec, "12345").must_equal ["1234", "5"] Code128.send(:extract_codec, "12345abc").must_equal ["1234", "5abc"] Code128.send(:extract_codec, "abcdef1234567").must_equal ["abcdef1", "234567"] end it "should know how to most efficiently apply different encodings to a data string" do - Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT" + #Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT" Code128.apply_shortest_encoding_for_data("123456").must_equal "#{CODEC}123456" Code128.apply_shortest_encoding_for_data("abcdef").must_equal "#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("ABCDEF").must_equal "#{CODEB}ABCDEF" Code128.apply_shortest_encoding_for_data("\n\t\r").must_equal "#{CODEA}\n\t\r" Code128.apply_shortest_encoding_for_data("123456abcdef").must_equal "#{CODEC}123456#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("abcdef123456").must_equal "#{CODEB}abcdef#{CODEC}123456" Code128.apply_shortest_encoding_for_data("1234567").must_equal "#{CODEC}123456#{CODEB}7" Code128.apply_shortest_encoding_for_data("123b456").must_equal "#{CODEB}123b456" Code128.apply_shortest_encoding_for_data("abc123def45678gh").must_equal "#{CODEB}abc123def4#{CODEC}5678#{CODEB}gh" Code128.apply_shortest_encoding_for_data("12345AB\nEEasdgr12EE\r\n").must_equal "#{CODEC}1234#{CODEA}5AB\nEE#{CODEB}asdgr12EE#{CODEA}\r\n" Code128.apply_shortest_encoding_for_data("123456QWERTY\r\n\tAAbbcc12XX34567").must_equal "#{CODEC}123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl" Code128.apply_shortest_encoding_for_data("ABC\rb\nDEF12gHI3456").must_equal "#{CODEA}ABC\r#{SHIFT}b\nDEF12#{CODEB}gHI#{CODEC}3456" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl\tMNop\nqRs").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl#{SHIFT}\tMNop#{SHIFT}\nqRs" end it "should apply automatic charset when no charset is given" do b = Code128.new("123456QWERTY\r\n\tAAbbcc12XX34567") b.type.must_equal 'C' b.full_data_with_change_codes.must_equal "123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" end end private def binary_encode_array(datas) datas.each { |data| binary_encode(data) } end def binary_encode(data) ruby_19_or_greater? ? data.force_encoding('BINARY') : data end end
toretore/barby
fcebe95005c83b8a995cacffc54f8a381a43c689
uses the codec characters regex in one more spot
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index 8e9de86..1c2221c 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,572 +1,572 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") # # #GS1-128/EAN-128/UCC-128 # #To make a GS1-128 code, prefix the data with FNC1 and the Application Identifier: # # #AI=00, data=12345 # Code128.new("#{Code128::FNC1}0012345") class Code128 < Barcode1D FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" SHIFT = "\xc8" STARTA = "\xc9" STARTB = "\xca" STARTC = "\xcb" STOP = '11000111010' TERMINATE = '11' ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => CODEB, 101 => FNC4, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type def initialize(data, type=nil) if type self.type = type self.data = "#{data}" else self.type, self.data = self.class.determine_best_type_for_data("#{data}") end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type = type.upcase raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra return @extra if defined?(@extra) @extra = nil end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_character case type when 'A' then STARTA when 'B' then STARTB when 'C' then STARTC end end def start_num values[start_character] end def start_encoding encodings[start_num] end CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ LOWR_RE = /[a-z]/ DGTS_RE = /\d{4,}/ - # pairs of digits and FNC characters + # pairs of digits and FNC1 characters CODEC_CHARS_RE = /(?:\d{2}|#{FNC1}){2,}/ class << self def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Insert code shift and switch characters where appropriate to get the #shortest encoding possible def apply_shortest_encoding_for_data(data) extract_codec(data).map do |block| if codec_segment?(block) "#{CODEC}#{block}" else if control_before_lowercase?(block) handle_code_a(block) else handle_code_b(block) end end end.join end def determine_best_type_for_data(data) data = apply_shortest_encoding_for_data(data) type = case data.slice!(0) when CODEA then 'A' when CODEB then 'B' when CODEC then 'C' end [type, data] end private #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. # # # C A or B C A or B # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] def extract_codec(data) data.split(/ (^(?:#{CODEC_CHARS_RE})) # matches digits that appear at the beginning of the barcode | ((?:#{CODEC_CHARS_RE})(?!\d)) # matches digits that appear later in the barcode /x).reject(&:empty?) end def codec_segment?(data) - data =~ /\A(?:\d{2}|#{FNC1}){2,}\Z/ + data =~ /\A#{CODEC_CHARS_RE}\Z/ end def control_character?(char) char =~ CTRL_RE end def lowercase_character?(char) char =~ LOWR_RE end #Handle a Code A segment which may contain Code B parts, but may not #contain any Code C parts. def handle_code_a(data) indata = data.dup outdata = CODEA.dup #We know it'll be A while char = indata.slice!(0) if lowercase_character?(char) #Found a lower case character (Code B) if control_before_lowercase?(indata) outdata << SHIFT << char #Control character appears before a new lowercase, use shift else outdata << handle_code_b(char+indata) #Switch to Code B break end else outdata << char end end#while outdata end #Handle a Code B segment which may contain Code A parts, but may not #contain any Code C parts. def handle_code_b(data) indata = data.dup outdata = CODEB.dup #We know this is going to start with Code B while char = indata.slice!(0) if control_character?(char) #Found a control character (Code A) if control_before_lowercase?(indata) #There is another control character before any lowercase, so outdata << handle_code_a(char+indata) #switch over to Code A. break else outdata << SHIFT << char #Can use a shift to only encode this char as Code A end else outdata << char end end#while outdata end #Test str to see if a control character (Code A) appears #before a lower case character (Code B). # #Returns true only if it contains a control character and a lower case #character doesn't appear before it. def control_before_lowercase?(str) ctrl = str =~ CTRL_RE char = str =~ LOWR_RE ctrl && (!char || ctrl < char) end end#class << self end#class Code128 class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end
toretore/barby
a2819bfb9c594232a954852e07fda321bab8dbcf
ignores unnecessary non-capturing groups
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index 8022443..8e9de86 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,572 +1,572 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") # # #GS1-128/EAN-128/UCC-128 # #To make a GS1-128 code, prefix the data with FNC1 and the Application Identifier: # # #AI=00, data=12345 # Code128.new("#{Code128::FNC1}0012345") class Code128 < Barcode1D FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" SHIFT = "\xc8" STARTA = "\xc9" STARTB = "\xca" STARTC = "\xcb" STOP = '11000111010' TERMINATE = '11' ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => CODEB, 101 => FNC4, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type def initialize(data, type=nil) if type self.type = type self.data = "#{data}" else self.type, self.data = self.class.determine_best_type_for_data("#{data}") end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type = type.upcase raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra return @extra if defined?(@extra) @extra = nil end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_character case type when 'A' then STARTA when 'B' then STARTB when 'C' then STARTC end end def start_num values[start_character] end def start_encoding encodings[start_num] end CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ LOWR_RE = /[a-z]/ DGTS_RE = /\d{4,}/ # pairs of digits and FNC characters CODEC_CHARS_RE = /(?:\d{2}|#{FNC1}){2,}/ class << self def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Insert code shift and switch characters where appropriate to get the #shortest encoding possible def apply_shortest_encoding_for_data(data) extract_codec(data).map do |block| if codec_segment?(block) "#{CODEC}#{block}" else if control_before_lowercase?(block) handle_code_a(block) else handle_code_b(block) end end end.join end def determine_best_type_for_data(data) data = apply_shortest_encoding_for_data(data) type = case data.slice!(0) when CODEA then 'A' when CODEB then 'B' when CODEC then 'C' end [type, data] end private #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. # # # C A or B C A or B # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] def extract_codec(data) data.split(/ - ((?:^(?:#{CODEC_CHARS_RE}))) # matches digits that appear at the beginning of the barcode + (^(?:#{CODEC_CHARS_RE})) # matches digits that appear at the beginning of the barcode | - ((?:(?:#{CODEC_CHARS_RE})(?!\d))) # matches digits that appear later in the barcode + ((?:#{CODEC_CHARS_RE})(?!\d)) # matches digits that appear later in the barcode /x).reject(&:empty?) end def codec_segment?(data) data =~ /\A(?:\d{2}|#{FNC1}){2,}\Z/ end def control_character?(char) char =~ CTRL_RE end def lowercase_character?(char) char =~ LOWR_RE end #Handle a Code A segment which may contain Code B parts, but may not #contain any Code C parts. def handle_code_a(data) indata = data.dup outdata = CODEA.dup #We know it'll be A while char = indata.slice!(0) if lowercase_character?(char) #Found a lower case character (Code B) if control_before_lowercase?(indata) outdata << SHIFT << char #Control character appears before a new lowercase, use shift else outdata << handle_code_b(char+indata) #Switch to Code B break end else outdata << char end end#while outdata end #Handle a Code B segment which may contain Code A parts, but may not #contain any Code C parts. def handle_code_b(data) indata = data.dup outdata = CODEB.dup #We know this is going to start with Code B while char = indata.slice!(0) if control_character?(char) #Found a control character (Code A) if control_before_lowercase?(indata) #There is another control character before any lowercase, so outdata << handle_code_a(char+indata) #switch over to Code A. break else outdata << SHIFT << char #Can use a shift to only encode this char as Code A end else outdata << char end end#while outdata end #Test str to see if a control character (Code A) appears #before a lower case character (Code B). # #Returns true only if it contains a control character and a lower case #character doesn't appear before it. def control_before_lowercase?(str) ctrl = str =~ CTRL_RE char = str =~ LOWR_RE ctrl && (!char || ctrl < char) end end#class << self end#class Code128 class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end
toretore/barby
0162d9bf334dd93ca33a7c1a1f19ec052d58d716
extracts some constants for clarity
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index 76b44b1..8022443 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,569 +1,572 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") # # #GS1-128/EAN-128/UCC-128 # #To make a GS1-128 code, prefix the data with FNC1 and the Application Identifier: # # #AI=00, data=12345 # Code128.new("#{Code128::FNC1}0012345") class Code128 < Barcode1D FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" SHIFT = "\xc8" STARTA = "\xc9" STARTB = "\xca" STARTC = "\xcb" STOP = '11000111010' TERMINATE = '11' ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => CODEB, 101 => FNC4, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type def initialize(data, type=nil) if type self.type = type self.data = "#{data}" else self.type, self.data = self.class.determine_best_type_for_data("#{data}") end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type = type.upcase raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra return @extra if defined?(@extra) @extra = nil end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_character case type when 'A' then STARTA when 'B' then STARTB when 'C' then STARTC end end def start_num values[start_character] end def start_encoding encodings[start_num] end CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ LOWR_RE = /[a-z]/ DGTS_RE = /\d{4,}/ + # pairs of digits and FNC characters + CODEC_CHARS_RE = /(?:\d{2}|#{FNC1}){2,}/ + class << self def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Insert code shift and switch characters where appropriate to get the #shortest encoding possible def apply_shortest_encoding_for_data(data) extract_codec(data).map do |block| if codec_segment?(block) "#{CODEC}#{block}" else if control_before_lowercase?(block) handle_code_a(block) else handle_code_b(block) end end end.join end def determine_best_type_for_data(data) data = apply_shortest_encoding_for_data(data) type = case data.slice!(0) when CODEA then 'A' when CODEB then 'B' when CODEC then 'C' end [type, data] end private #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. # # # C A or B C A or B # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] def extract_codec(data) data.split(/ - ((?:^(?:(?:\d{2}|#{FNC1}){2,}))) # matches digits that appear at the beginning of the barcode + ((?:^(?:#{CODEC_CHARS_RE}))) # matches digits that appear at the beginning of the barcode | - ((?:(?:(?:\d{2}|#{FNC1}){2,})(?!\d))) # matches digits that appear later in the barcode + ((?:(?:#{CODEC_CHARS_RE})(?!\d))) # matches digits that appear later in the barcode /x).reject(&:empty?) end def codec_segment?(data) data =~ /\A(?:\d{2}|#{FNC1}){2,}\Z/ end def control_character?(char) char =~ CTRL_RE end def lowercase_character?(char) char =~ LOWR_RE end #Handle a Code A segment which may contain Code B parts, but may not #contain any Code C parts. def handle_code_a(data) indata = data.dup outdata = CODEA.dup #We know it'll be A while char = indata.slice!(0) if lowercase_character?(char) #Found a lower case character (Code B) if control_before_lowercase?(indata) outdata << SHIFT << char #Control character appears before a new lowercase, use shift else outdata << handle_code_b(char+indata) #Switch to Code B break end else outdata << char end end#while outdata end #Handle a Code B segment which may contain Code A parts, but may not #contain any Code C parts. def handle_code_b(data) indata = data.dup outdata = CODEB.dup #We know this is going to start with Code B while char = indata.slice!(0) if control_character?(char) #Found a control character (Code A) if control_before_lowercase?(indata) #There is another control character before any lowercase, so outdata << handle_code_a(char+indata) #switch over to Code A. break else outdata << SHIFT << char #Can use a shift to only encode this char as Code A end else outdata << char end end#while outdata end #Test str to see if a control character (Code A) appears #before a lower case character (Code B). # #Returns true only if it contains a control character and a lower case #character doesn't appear before it. def control_before_lowercase?(str) ctrl = str =~ CTRL_RE char = str =~ LOWR_RE ctrl && (!char || ctrl < char) end end#class << self end#class Code128 class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end
toretore/barby
6adbce76da7cb5a101a82ec393f3efcb805ff195
handles FNC1
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index 2e9a841..76b44b1 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,569 +1,569 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") # # #GS1-128/EAN-128/UCC-128 # #To make a GS1-128 code, prefix the data with FNC1 and the Application Identifier: # # #AI=00, data=12345 # Code128.new("#{Code128::FNC1}0012345") class Code128 < Barcode1D FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" SHIFT = "\xc8" STARTA = "\xc9" STARTB = "\xca" STARTC = "\xcb" STOP = '11000111010' TERMINATE = '11' ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => CODEB, 101 => FNC4, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type def initialize(data, type=nil) if type self.type = type self.data = "#{data}" else self.type, self.data = self.class.determine_best_type_for_data("#{data}") end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type = type.upcase raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra return @extra if defined?(@extra) @extra = nil end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_character case type when 'A' then STARTA when 'B' then STARTB when 'C' then STARTC end end def start_num values[start_character] end def start_encoding encodings[start_num] end CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ LOWR_RE = /[a-z]/ DGTS_RE = /\d{4,}/ class << self def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Insert code shift and switch characters where appropriate to get the #shortest encoding possible def apply_shortest_encoding_for_data(data) extract_codec(data).map do |block| if codec_segment?(block) "#{CODEC}#{block}" else if control_before_lowercase?(block) handle_code_a(block) else handle_code_b(block) end end end.join end def determine_best_type_for_data(data) data = apply_shortest_encoding_for_data(data) type = case data.slice!(0) when CODEA then 'A' when CODEB then 'B' when CODEC then 'C' end [type, data] end private #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. # # # C A or B C A or B # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] def extract_codec(data) data.split(/ - ((?:^(?:(?:\d{2}){2,}))) + ((?:^(?:(?:\d{2}|#{FNC1}){2,}))) # matches digits that appear at the beginning of the barcode | - ((?:(?:(?:\d{2}){2,})(?!\d))) + ((?:(?:(?:\d{2}|#{FNC1}){2,})(?!\d))) # matches digits that appear later in the barcode /x).reject(&:empty?) end def codec_segment?(data) data =~ /\A(?:\d{2}|#{FNC1}){2,}\Z/ end def control_character?(char) char =~ CTRL_RE end def lowercase_character?(char) char =~ LOWR_RE end #Handle a Code A segment which may contain Code B parts, but may not #contain any Code C parts. def handle_code_a(data) indata = data.dup outdata = CODEA.dup #We know it'll be A while char = indata.slice!(0) if lowercase_character?(char) #Found a lower case character (Code B) if control_before_lowercase?(indata) outdata << SHIFT << char #Control character appears before a new lowercase, use shift else outdata << handle_code_b(char+indata) #Switch to Code B break end else outdata << char end end#while outdata end #Handle a Code B segment which may contain Code A parts, but may not #contain any Code C parts. def handle_code_b(data) indata = data.dup outdata = CODEB.dup #We know this is going to start with Code B while char = indata.slice!(0) if control_character?(char) #Found a control character (Code A) if control_before_lowercase?(indata) #There is another control character before any lowercase, so outdata << handle_code_a(char+indata) #switch over to Code A. break else outdata << SHIFT << char #Can use a shift to only encode this char as Code A end else outdata << char end end#while outdata end #Test str to see if a control character (Code A) appears #before a lower case character (Code B). # #Returns true only if it contains a control character and a lower case #character doesn't appear before it. def control_before_lowercase?(str) ctrl = str =~ CTRL_RE char = str =~ LOWR_RE ctrl && (!char || ctrl < char) end end#class << self end#class Code128 class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end
toretore/barby
c482c7320b8f085ff0172bc9658f46caf6b49842
handles everything except fnc1, with simpler logic
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index 3d48d7c..2e9a841 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,579 +1,569 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") # # #GS1-128/EAN-128/UCC-128 # #To make a GS1-128 code, prefix the data with FNC1 and the Application Identifier: # # #AI=00, data=12345 # Code128.new("#{Code128::FNC1}0012345") class Code128 < Barcode1D FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" SHIFT = "\xc8" STARTA = "\xc9" STARTB = "\xca" STARTC = "\xcb" STOP = '11000111010' TERMINATE = '11' ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => CODEB, 101 => FNC4, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type def initialize(data, type=nil) if type self.type = type self.data = "#{data}" else self.type, self.data = self.class.determine_best_type_for_data("#{data}") end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type = type.upcase raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra return @extra if defined?(@extra) @extra = nil end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_character case type when 'A' then STARTA when 'B' then STARTB when 'C' then STARTC end end def start_num values[start_character] end def start_encoding encodings[start_num] end CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ LOWR_RE = /[a-z]/ DGTS_RE = /\d{4,}/ class << self def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Insert code shift and switch characters where appropriate to get the #shortest encoding possible def apply_shortest_encoding_for_data(data) extract_codec(data).map do |block| - if possible_codec_segment?(block) + if codec_segment?(block) "#{CODEC}#{block}" else if control_before_lowercase?(block) handle_code_a(block) else handle_code_b(block) end end end.join end def determine_best_type_for_data(data) data = apply_shortest_encoding_for_data(data) type = case data.slice!(0) when CODEA then 'A' when CODEB then 'B' when CODEC then 'C' end [type, data] end private #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. # # # C A or B C A or B # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] def extract_codec(data) - segments = data.split(/(\d{4,})/).reject(&:empty?) - segments.each_with_index do |s,i| - if possible_codec_segment?(s) && s.size.odd? - if i == 0 - if segments[1] - segments[1].insert(0, s.slice!(-1)) - else - segments[1] = s.slice!(-1) - end - else - segments[i-1].insert(-1, s.slice!(0)) if segments[i-1] - end - end - end - segments + data.split(/ + ((?:^(?:(?:\d{2}){2,}))) + | + ((?:(?:(?:\d{2}){2,})(?!\d))) + /x).reject(&:empty?) end - def possible_codec_segment?(data) - data =~ /\A\d{4,}\Z/ + def codec_segment?(data) + data =~ /\A(?:\d{2}|#{FNC1}){2,}\Z/ end def control_character?(char) char =~ CTRL_RE end def lowercase_character?(char) char =~ LOWR_RE end #Handle a Code A segment which may contain Code B parts, but may not #contain any Code C parts. def handle_code_a(data) indata = data.dup outdata = CODEA.dup #We know it'll be A while char = indata.slice!(0) if lowercase_character?(char) #Found a lower case character (Code B) if control_before_lowercase?(indata) outdata << SHIFT << char #Control character appears before a new lowercase, use shift else outdata << handle_code_b(char+indata) #Switch to Code B break end else outdata << char end end#while outdata end #Handle a Code B segment which may contain Code A parts, but may not #contain any Code C parts. def handle_code_b(data) indata = data.dup outdata = CODEB.dup #We know this is going to start with Code B while char = indata.slice!(0) if control_character?(char) #Found a control character (Code A) if control_before_lowercase?(indata) #There is another control character before any lowercase, so outdata << handle_code_a(char+indata) #switch over to Code A. break else outdata << SHIFT << char #Can use a shift to only encode this char as Code A end else outdata << char end end#while outdata end #Test str to see if a control character (Code A) appears #before a lower case character (Code B). # #Returns true only if it contains a control character and a lower case #character doesn't appear before it. def control_before_lowercase?(str) ctrl = str =~ CTRL_RE char = str =~ LOWR_RE ctrl && (!char || ctrl < char) end end#class << self end#class Code128 class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end diff --git a/test/code_128_test.rb b/test/code_128_test.rb index 5e51538..807e196 100644 --- a/test/code_128_test.rb +++ b/test/code_128_test.rb @@ -1,411 +1,412 @@ # encoding: UTF-8 require 'test_helper' require 'barby/barcode/code_128' class Code128Test < Barby::TestCase %w[CODEA CODEB CODEC FNC1 FNC2 FNC3 FNC4 SHIFT].each do |const| const_set const, Code128.const_get(const) end before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do @code.send(:stop_encoding).must_equal '1100011101011' end it "should find the right class for a character A, B or C" do @code.send(:class_for, 'A').must_equal Code128A @code.send(:class_for, 'B').must_equal Code128B @code.send(:class_for, 'C').must_equal Code128C end it "should find the right change code for a class" do @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC end it "should not allow empty data" do lambda{ Code128B.new("") }.must_raise(ArgumentError) end describe "single encoding" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do @code.data.must_equal @data end it "should be able to change its data" do @code.data = '123ABC' @code.data.must_equal '123ABC' @code.data.wont_equal @data end it "should not have an extra" do assert @code.extra.nil? end it "should have empty extra encoding" do @code.extra_encoding.must_equal '' end it "should have the correct checksum" do @code.checksum.must_equal 66 end it "should return all data for to_s" do @code.to_s.must_equal @data end end describe "multiple encodings" do before do @data = binary_encode("ABC123\306def\3074567") @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do @code.full_data.must_equal "ABC123def4567" end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do @code.full_data_with_change_codes.must_equal @data end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = binary_encode("\3071234") code.full_data.must_equal "ABC1234" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234") code.extra.extra = binary_encode("\306abc") code.full_data.must_equal "ABC1234abc" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc") code.extra.extra.data = binary_encode("abc\305DEF") code.full_data.must_equal "ABC1234abcDEF" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc\305DEF") code.extra.extra.full_data.must_equal "abcDEF" code.extra.extra.full_data_with_change_codes.must_equal binary_encode("abc\305DEF") code.extra.full_data.must_equal "1234abcDEF" code.extra.full_data_with_change_codes.must_equal binary_encode("1234\306abc\305DEF") end it "should have a Code B extra" do @code.extra.must_be_instance_of(Code128B) end it "should have a valid extra" do assert @code.extra.valid? end it "the extra should also have an extra of type C" do @code.extra.extra.must_be_instance_of(Code128C) end it "the extra's extra should be valid" do assert @code.extra.extra.valid? end it "should not have more than two extras" do assert @code.extra.extra.extra.nil? end it "should split extra data from string on data assignment" do @code.data = binary_encode("123\306abc") @code.data.must_equal '123' @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal 'abc' end it "should be be able to change its extra" do @code.extra = binary_encode("\3071234") @code.extra.must_be_instance_of(Code128C) @code.extra.data.must_equal '1234' end it "should split extra data from string on extra assignment" do @code.extra = binary_encode("\306123\3074567") @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal '123' @code.extra.extra.must_be_instance_of(Code128C) @code.extra.extra.data.must_equal '4567' end it "should not fail on newlines in extras" do code = Code128B.new(binary_encode("ABC\305\n")) code.data.must_equal "ABC" code.extra.must_be_instance_of(Code128A) code.extra.data.must_equal "\n" code.extra.extra = binary_encode("\305\n\n\n\n\n\nVALID") code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" end it "should raise an exception when extra string doesn't start with the special code character" do lambda{ @code.extra = '123' }.must_raise ArgumentError end it "should have the correct checksum" do @code.checksum.must_equal 84 end it "should have the expected encoding" do #STARTA A B C 1 2 3 @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ #CODEB d e f '10111101110100001001101011001000010110000100'+ #CODEC 45 67 '101110111101011101100010000101100'+ #CHECK=84 STOP '100111101001100011101011' end it "should return all data including extras, except change codes for to_s" do @code.to_s.must_equal "ABC123def4567" end end describe "128A" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = 'abc123' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(A B C 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010000100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10010000110' end end describe "128B" do before do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = binary_encode("abc£123") refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(a b c 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010010000' end it "should have the expected data encoding" do @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '11011101110' end end describe "128C" do before do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = '123' refute @code.valid? @code.data = 'abc' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(12 34 56) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010011100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101100111001000101100011100010110' end it "should have the expected encoding" do @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10001101110' end end describe "Function characters" do it "should retain the special symbols in the data accessor" do Code128A.new(binary_encode("\301ABC\301DEF")).data.must_equal binary_encode("\301ABC\301DEF") Code128B.new(binary_encode("\301ABC\302DEF")).data.must_equal binary_encode("\301ABC\302DEF") Code128C.new(binary_encode("\301123456")).data.must_equal binary_encode("\301123456") Code128C.new(binary_encode("12\30134\30156")).data.must_equal binary_encode("12\30134\30156") end it "should keep the special symbols as characters" do Code128A.new(binary_encode("\301ABC\301DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \301 D E F)) Code128B.new(binary_encode("\301ABC\302DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \302 D E F)) Code128C.new(binary_encode("\301123456")).characters.must_equal binary_encode_array(%W(\301 12 34 56)) Code128C.new(binary_encode("12\30134\30156")).characters.must_equal binary_encode_array(%W(12 \301 34 \301 56)) end it "should not allow FNC > 1 for Code C" do lambda{ Code128C.new("12\302") }.must_raise ArgumentError lambda{ Code128C.new("\30312") }.must_raise ArgumentError lambda{ Code128C.new("12\304") }.must_raise ArgumentError end it "should be included in the encoding" do a = Code128A.new(binary_encode("\301AB")) a.data_encoding.must_equal '111101011101010001100010001011000' a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' end end describe "Code128 with type" do #it "should raise an exception when not given a type" do # lambda{ Code128.new('abc') }.must_raise(ArgumentError) #end it "should raise an exception when given a non-existent type" do lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) end it "should not fail on frozen type" do Code128.new('123456', 'C'.freeze) # not failing Code128.new('123456', 'c'.freeze) # not failing even when upcasing end it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end end describe "Code128 automatic charset" do it "should know how to extract CODEC segments properly from a data string" do Code128.send(:extract_codec, "1234abcd5678\r\n\r\n").must_equal ["1234", "abcd", "5678", "\r\n\r\n"] Code128.send(:extract_codec, "12345abc6").must_equal ["1234", "5abc6"] Code128.send(:extract_codec, "abcdef").must_equal ["abcdef"] Code128.send(:extract_codec, "123abcdef45678").must_equal ["123abcdef4", "5678"] Code128.send(:extract_codec, "abcd12345").must_equal ["abcd1", "2345"] Code128.send(:extract_codec, "abcd12345efg").must_equal ["abcd1", "2345", "efg"] Code128.send(:extract_codec, "12345").must_equal ["1234", "5"] Code128.send(:extract_codec, "12345abc").must_equal ["1234", "5abc"] Code128.send(:extract_codec, "abcdef1234567").must_equal ["abcdef1", "234567"] end it "should know how to most efficiently apply different encodings to a data string" do + Code128.apply_shortest_encoding_for_data("#{FNC1}10LOT").must_equal "#{CODEC}#{FNC1}10#{CODEB}LOT" Code128.apply_shortest_encoding_for_data("123456").must_equal "#{CODEC}123456" Code128.apply_shortest_encoding_for_data("abcdef").must_equal "#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("ABCDEF").must_equal "#{CODEB}ABCDEF" Code128.apply_shortest_encoding_for_data("\n\t\r").must_equal "#{CODEA}\n\t\r" Code128.apply_shortest_encoding_for_data("123456abcdef").must_equal "#{CODEC}123456#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("abcdef123456").must_equal "#{CODEB}abcdef#{CODEC}123456" Code128.apply_shortest_encoding_for_data("1234567").must_equal "#{CODEC}123456#{CODEB}7" Code128.apply_shortest_encoding_for_data("123b456").must_equal "#{CODEB}123b456" Code128.apply_shortest_encoding_for_data("abc123def45678gh").must_equal "#{CODEB}abc123def4#{CODEC}5678#{CODEB}gh" Code128.apply_shortest_encoding_for_data("12345AB\nEEasdgr12EE\r\n").must_equal "#{CODEC}1234#{CODEA}5AB\nEE#{CODEB}asdgr12EE#{CODEA}\r\n" Code128.apply_shortest_encoding_for_data("123456QWERTY\r\n\tAAbbcc12XX34567").must_equal "#{CODEC}123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl" Code128.apply_shortest_encoding_for_data("ABC\rb\nDEF12gHI3456").must_equal "#{CODEA}ABC\r#{SHIFT}b\nDEF12#{CODEB}gHI#{CODEC}3456" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl\tMNop\nqRs").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl#{SHIFT}\tMNop#{SHIFT}\nqRs" end it "should apply automatic charset when no charset is given" do b = Code128.new("123456QWERTY\r\n\tAAbbcc12XX34567") b.type.must_equal 'C' b.full_data_with_change_codes.must_equal "123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" end end private def binary_encode_array(datas) datas.each { |data| binary_encode(data) } end def binary_encode(data) ruby_19_or_greater? ? data.force_encoding('BINARY') : data end end
toretore/barby
64bf7df827b4d01d73f640d8c6197fa33cedd83e
Added preserveAspectRatio="none" to svg_outputter
diff --git a/lib/barby/outputter/svg_outputter.rb b/lib/barby/outputter/svg_outputter.rb index fd440a7..0987082 100644 --- a/lib/barby/outputter/svg_outputter.rb +++ b/lib/barby/outputter/svg_outputter.rb @@ -1,230 +1,219 @@ require 'barby/outputter' module Barby #Renders the barcode to a simple SVG image using pure ruby # #Registers the to_svg, bars_to_path, and bars_to_rects method # #Bars can be rendered as a stroked path or as filled rectangles. Path #generally yields smaller files, but this doesn't render cleanly in Firefox #3 for odd xdims. My guess is that the renderer tries to put half a pixel #on one side of the path and half on the other, leading to fuzzy dithering #instead of sharp, clean b&w. # #Therefore, default behavior is to use a path for even xdims, and #rectangles for odd. This can be overridden by calling with explicit #:use => 'rects' or :use => 'path' options. class SvgOutputter < Outputter register :to_svg, :bars_to_rects, :bars_to_path attr_writer :title, :xdim, :ydim, :height, :rmargin, :lmargin, :tmargin, :bmargin, :xmargin, :ymargin, :margin - def initialize(*) super @title, @xdim, @ydim, @height, @rmargin, @lmargin, @tmargin, @bmargin, @xmargin, @ymargin, @margin = nil end def to_svg(opts={}) with_options opts do case opts[:use] when 'rects' then bars = bars_to_rects when 'path' then bars = bars_to_path else xdim_odd = (xdim % 2 == 1) bars = xdim_odd ? bars_to_rects : bars_to_path end <<-"EOT" <?xml version="1.0" encoding="UTF-8"?> -<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="#{svg_width(opts)}px" height="#{svg_height(opts)}px" viewBox="0 0 #{svg_width(opts)} #{svg_height(opts)}" version="1.1"> +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="#{svg_width(opts)}px" height="#{svg_height(opts)}px" viewBox="0 0 #{svg_width(opts)} #{svg_height(opts)}" version="1.1" preserveAspectRatio="none" > <title>#{escape title}</title> <g id="canvas" #{transform(opts)}> <rect x="0" y="0" width="#{full_width}px" height="#{full_height}px" fill="white" /> <g id="barcode" fill="black"> #{bars} </g></g> </svg> EOT end end - def bars_to_rects(opts={}) rects = '' with_options opts do x, y = lmargin, tmargin if barcode.two_dimensional? boolean_groups.each do |line| line.each do |bar, amount| bar_width = xdim * amount if bar rects << %Q|<rect x="#{x}" y="#{y}" width="#{bar_width}px" height="#{ydim}px" />\n| end x += bar_width end y += ydim x = lmargin end else boolean_groups.each do |bar, amount| bar_width = xdim * amount if bar rects << %Q|<rect x="#{x}" y="#{y}" width="#{bar_width}px" height="#{height}px" />\n| end x += bar_width end end end # with_options rects end - def bars_to_path(opts={}) with_options opts do %Q|<path stroke="black" stroke-width="#{xdim}" d="#{bars_to_path_data(opts)}" />| end end - def bars_to_path_data(opts={}) path_data = '' with_options opts do x, y = lmargin+(xdim/2), tmargin if barcode.two_dimensional? booleans.each do |line| line.each do |bar| if bar path_data << "M#{x} #{y}V #{y+ydim}" end x += xdim end y += ydim x = lmargin+(xdim/2) end else booleans.each do |bar| if bar path_data << "M#{x} #{y}V#{y+height}" end x += xdim end end end # with_options path_data end - def title @title || barcode.to_s end - def width length * xdim end def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end def full_width width + lmargin + rmargin end def full_height height + tmargin + bmargin end def xdim @xdim || 1 end def ydim @ydim || xdim end def lmargin @lmargin || _xmargin end def rmargin @rmargin || _xmargin end def tmargin @tmargin || _ymargin end def bmargin @bmargin || _ymargin end def xmargin return nil if @lmargin || @rmargin _margin end def ymargin return nil if @tmargin || @bmargin _margin end def margin return nil if @ymargin || @xmargin || @tmargin || @bmargin || @lmargin || @rmargin _margin end def length barcode.two_dimensional? ? encoding.first.length : encoding.length end - def svg_width(opts={}) opts[:rot] ? full_height : full_width end def svg_height(opts={}) opts[:rot] ? full_width : full_height end - def transform(opts={}) opts[:rot] ? %Q|transform="rotate(-90) translate(-#{full_width}, 0)"| : nil end - private def _xmargin @xmargin || _margin end def _ymargin @ymargin || _margin end def _margin @margin || 10 end #Escape XML special characters <, & and > def escape(str) str.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;') end - end - end
toretore/barby
714ad0981159504350fd1c47a7657fbf11c413ba
Support multi-byte character in QR code
diff --git a/lib/barby/barcode/qr_code.rb b/lib/barby/barcode/qr_code.rb index 82ae0f6..83f9c98 100644 --- a/lib/barby/barcode/qr_code.rb +++ b/lib/barby/barcode/qr_code.rb @@ -1,102 +1,102 @@ require 'rqrcode' require 'barby/barcode' module Barby #QrCode is a thin wrapper around the RQRCode library class QrCode < Barcode2D #Maximum sizes for each correction level for binary data #It's an array SIZES = { #L M Q H 1 => [17, 14, 11, 7], 2 => [32, 26, 20, 14], 3 => [53, 42, 32, 24], 4 => [78, 62, 46, 34], 5 => [106, 84, 60, 44], 6 => [134, 106, 74, 58], 7 => [154, 122, 86, 64], 8 => [192, 152, 108, 84], 9 => [230, 180, 130, 98], 10 => [271, 213, 151, 119], 11 => [321, 251, 177, 137], 12 => [367, 287, 203, 155], 13 => [425, 331, 241, 177], 14 => [458, 362, 258, 194], 15 => [520, 412, 292, 220], 16 => [586, 450, 322, 250], 17 => [644, 504, 364, 280], 18 => [718, 560, 394, 310], 19 => [792, 624, 442, 338], 20 => [858, 666, 482, 382], 21 => [929, 711, 509, 403], 22 => [1003, 779, 565, 439], 23 => [1091, 857, 611, 461], 24 => [1171, 911, 661, 511], 25 => [1273, 997, 715, 535], 26 => [1367, 1059, 751, 593], 27 => [1465, 1125, 805, 625], 28 => [1528, 1190, 868, 658], 29 => [1628, 1264, 908, 698], 30 => [1732, 1370, 982, 742], 31 => [1840, 1452, 1030, 790], 32 => [1952, 1538, 1112, 842], 33 => [2068, 1628, 1168, 898], 34 => [2188, 1722, 1228, 958], 35 => [2303, 1809, 1283, 983], 36 => [2431, 1911, 1351, 1051], 37 => [2563, 1989, 1423, 1093], 38 => [2699, 2099, 1499, 1139], 39 => [2809, 2213, 1579, 1219], 40 => [2953, 2331, 1663, 1273] }.sort LEVELS = { :l => 0, :m => 1, :q => 2, :h => 3 } attr_reader :data attr_writer :level, :size def initialize(data, options={}) self.data = data @level, @size = nil options.each{|k,v| send("#{k}=", v) } raise(ArgumentError, "data too large") unless size end def data=(data) @data = data end def encoding rqrcode.modules.map{|r| r.inject(''){|s,m| s << (m ? '1' : '0') } } end #Error correction level #Can be one of [:l, :m, :q, :h] (7%, 15%, 25%, 30%) def level @level || :l end def size #@size is only used for manual override, if it's not set #manually the size is always dynamic, calculated from the #length of the data return @size if @size level_index = LEVELS[level] - length = data.length + length = data.bytesize found_size = nil SIZES.each do |size,max_values| if max_values[level_index] >= length found_size = size break end end found_size end def to_s data[0,20] end private #Generate an RQRCode object with the available values def rqrcode RQRCode::QRCode.new(data, :level => level, :size => size) end end end
toretore/barby
0be718abfad77bcffec409ed22c12ada5c4f2390
ISBN: self.class
diff --git a/lib/barby/barcode/bookland.rb b/lib/barby/barcode/bookland.rb index 8263777..04c5a98 100644 --- a/lib/barby/barcode/bookland.rb +++ b/lib/barby/barcode/bookland.rb @@ -1,146 +1,145 @@ #encoding: ASCII require 'barby/barcode/ean_13' module Barby # Bookland barcodes are EAN-13 barcodes with number system # 978/979 (hence "Bookland"). The data they encode is an ISBN # with its check digit removed. This is a convenience class # that takes an ISBN number instead of "pure" EAN-13 data. # # #These are all the same: # barcode = Bookland.new('978-0-306-40615-7') # barcode = Bookland.new('978-0-306-40615') # barcode = Bookland.new('0-306-40615-7') # barcode = Bookland.new('0-306-40615') # # If a prefix is not given, a default of 978 is used. class Bookland < EAN13 # isbn should be an ISBN number string, with or without an EAN prefix and an ISBN checksum # non-number formatting like hyphens or spaces are ignored # # If a prefix is not given, a default of 978 is used. def initialize(isbn) self.isbn = isbn raise ArgumentError, 'data not valid' unless valid? end def data isbn.isbn end def isbn=(isbn) @isbn = ISBN.new(isbn) end #An instance of ISBN def isbn @isbn end # Encapsulates an ISBN number # # isbn = ISBN.new('978-0-306-40615') class ISBN DEFAULT_PREFIX = '978' PATTERN = /\A(?<prefix>\d\d\d)?(?<number>\d{9})(?<checksum>\d)?\Z/ attr_reader :number # Takes one argument, which is the ISBN string with or without prefix and/or check digit. # Non-digit characters like hyphens and spaces are ignored. # # Prefix is 978 if not given. def initialize(isbn) self.isbn = isbn end def isbn=(isbn) if match = PATTERN.match(isbn.gsub(/\D/, '')) @number = match[:number] @prefix = match[:prefix] else raise ArgumentError, "Not a valid ISBN: #{isbn}" end end def isbn "#{prefix}#{number}" end def isbn_with_checksum "#{isbn}#{checksum}" end def isbn_10 number end def isbn_10_with_checksum "#{number}#{checksum}" end def formatted_isbn "#{prefix}-#{number}-#{checksum}" end def formatted_isbn_10 "#{number}-#{checksum}" end def prefix @prefix || DEFAULT_PREFIX end def digits (prefix+number).split('').map(&:to_i) end def isbn_10_digits number.split('').map(&:to_i) end # Calculates the ISBN 13-digit checksum following the algorithm from: # http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-13_check_digit_calculation def checksum (10 - (digits.each_with_index.inject(0) do |sum, (digit, index)| sum + (digit * (index.even? ? 1 : 3)) end % 10)) % 10 end ISBN_10_CHECKSUM_MULTIPLIERS = [10,9,8,7,6,5,4,3,2] # Calculates the ISBN 10-digit checksum following the algorithm from: # http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digit_calculation def isbn_10_checksum isbn_10_digits.zip(ISBN_10_CHECKSUM_MULTIPLIERS).inject(0) do |sum, (digit, multiplier)| sum + (digit * multiplier) end end def to_s isbn_with_checksum end def inspect - klass = (self.class.ancestors + [self.class.name]).join(':') - "#<#{klass}:0x#{'%014x' % object_id} #{formatted_isbn}>" + "#<#{self.class}:0x#{'%014x' % object_id} #{formatted_isbn}>" end end#class ISBN end#class Bookland end#module Barby
toretore/barby
fdb53d1a0fa669fe1a3f602e855ff4c17e7766cb
rmagick
diff --git a/README.md b/README.md index e237402..f71a19c 100644 --- a/README.md +++ b/README.md @@ -1,106 +1,106 @@ # Barby Barby is a Ruby library that generates barcodes in a variety of symbologies. Its functionality is split into _barcode_ and "_outputter_" objects: * [`Barby::Barcode` objects] [symbologies] turn data into a binary representation for a given symbology. * [`Barby::Outputter`] [outputters] then takes this representation and turns it into images, PDF, etc. You can easily add a symbology without having to worry about graphical representation. If it can be represented as the usual 1D or 2D matrix of lines or squares, outputters will do that for you. Likewise, you can easily add an outputter for a format that doesn't have one yet, and it will work with all existing symbologies. For more information, check out [the Barby wiki] [wiki]. ### New require policy Barcode symbologies are no longer required automatically, so you'll have to require the ones you need. If you need EAN-13, `require 'barby/barcode/ean_13'`. Full list of symbologies and filenames below. ## Example ```ruby require 'barby' require 'barby/barcode/code_128' require 'barby/outputter/ascii_outputter' barcode = Barby::Code128B.new('BARBY') puts barcode.to_ascii #Implicitly uses the AsciiOutputter ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## B A R B Y ``` ## Supported symbologies ```ruby require 'barby/barcode/<filename>' ``` | Name | Filename | Dependencies | | ----------------------------------- | --------------------- | ------------- | | Code 25 | `code_25` | ─ | | ├─ Interleaved | `code_25_interleaved` | ─ | | └─ IATA | `code_25_iata` | ─ | | Code 39 | `code_39` | ─ | | Code 93 | `code_93` | ─ | | Code 128 | `code_128` | ─ | | └─ GS1 128 | `gs1_128` | ─ | | EAN-13 | `ean_13` | ─ | | ├─ Bookland | `bookland` | ─ | | └─ UPC-A | `ean_13` | ─ | | EAN-8 | `ean_8` | ─ | | UPC/EAN supplemental, 2 & 5 digits | `upc_supplemental` | ─ | | QR Code | `qr_code` | `rqrcode` | | DataMatrix (Semacode) | `data_matrix` | `semacode` | | PDF417 | `pdf_417` | JRuby | ## Outputters ```ruby require 'barby/outputter/<filename>_outputter' ``` | filename | dependencies | | ----------- | ------------- | | `ascii` | ─ | | `cairo` | cairo | | `html` | ─ | | `pdfwriter` | ─ | | `png` | chunky_png | | `prawn` | prawn | -| `rmagick` | RMagick | +| `rmagick` | rmagick | | `svg` | ─ | ### Formats supported by outputters * Text (mostly for testing) * PNG, JPEG, GIF * PS, EPS * SVG * PDF * HTML --- For more information, check out [the Barby wiki] [wiki]. [wiki]: https://github.com/toretore/barby/wiki [symbologies]: https://github.com/toretore/barby/wiki/Symbologies [outputters]: https://github.com/toretore/barby/wiki/Outputters
toretore/barby
ace7a8c105596cff0bd7e8e0fdd979ec49e114e4
require 'rmagick' not 'RMagick'
diff --git a/lib/barby/outputter/rmagick_outputter.rb b/lib/barby/outputter/rmagick_outputter.rb index 6e5d7a1..5f6bded 100644 --- a/lib/barby/outputter/rmagick_outputter.rb +++ b/lib/barby/outputter/rmagick_outputter.rb @@ -1,140 +1,140 @@ require 'barby/outputter' -require 'RMagick' +require 'rmagick' module Barby #Renders images from barcodes using RMagick # #Registers the to_png, to_gif, to_jpg and to_image methods class RmagickOutputter < Outputter - + register :to_png, :to_gif, :to_jpg, :to_image attr_writer :height, :xdim, :ydim, :margin def initialize(*) super @height, @xdim, @ydim, @margin = nil end #Returns a string containing a PNG image def to_png(*a) to_blob('png', *a) end #Returns a string containint a GIF image def to_gif(*a) to_blob('gif', *a) end #Returns a string containing a JPEG image def to_jpg(*a) to_blob('jpg', *a) end - + def to_blob(format, *a) img = to_image(*a) blob = img.to_blob{|i| i.format = format } - + #Release the memory used by RMagick explicitly. Ruby's GC #isn't aware of it and can't clean it up automatically img.destroy! if img.respond_to?(:destroy!) - + blob end #Returns an instance of Magick::Image def to_image(opts={}) with_options opts do canvas = Magick::Image.new(full_width, full_height) bars = Magick::Draw.new x1 = margin y1 = margin if barcode.two_dimensional? encoding.each do |line| line.split(//).map{|c| c == '1' }.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(ydim-1) # For single pixels use point if x1 == x2 && y1 == y2 bars.point(x1,y1) else bars.rectangle(x1, y1, x2, y2) end end x1 += xdim end x1 = margin y1 += ydim end else booleans.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(height-1) bars.rectangle(x1, y1, x2, y2) end x1 += xdim end end bars.draw(canvas) canvas end end #The height of the barcode in px #For 2D barcodes this is the number of "lines" * ydim def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end #The width of the barcode in px def width length * xdim end #Number of modules (xdims) on the x axis def length barcode.two_dimensional? ? encoding.first.length : encoding.length end #X dimension. 1X == 1px def xdim @xdim || 1 end #Y dimension. Only for 2D codes def ydim @ydim || xdim end #The margin of each edge surrounding the barcode in pixels def margin @margin || 10 end #The full width of the image. This is the width of the #barcode + the left and right margin def full_width width + (margin * 2) end #The height of the image. This is the height of the #barcode + the top and bottom margin def full_height height + (margin * 2) end end end
toretore/barby
eee81bb4da26ca553451cb7513e4a261a3f55560
Use defined? to avoid reassignment to nil
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index fb0eb63..3d48d7c 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,578 +1,579 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") # # #GS1-128/EAN-128/UCC-128 # #To make a GS1-128 code, prefix the data with FNC1 and the Application Identifier: # # #AI=00, data=12345 # Code128.new("#{Code128::FNC1}0012345") class Code128 < Barcode1D FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" SHIFT = "\xc8" STARTA = "\xc9" STARTB = "\xca" STARTC = "\xcb" STOP = '11000111010' TERMINATE = '11' ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => CODEB, 101 => FNC4, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type def initialize(data, type=nil) if type self.type = type self.data = "#{data}" else self.type, self.data = self.class.determine_best_type_for_data("#{data}") end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type = type.upcase raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra - @extra ||= nil + return @extra if defined?(@extra) + @extra = nil end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_character case type when 'A' then STARTA when 'B' then STARTB when 'C' then STARTC end end def start_num values[start_character] end def start_encoding encodings[start_num] end CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ LOWR_RE = /[a-z]/ DGTS_RE = /\d{4,}/ class << self def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Insert code shift and switch characters where appropriate to get the #shortest encoding possible def apply_shortest_encoding_for_data(data) extract_codec(data).map do |block| if possible_codec_segment?(block) "#{CODEC}#{block}" else if control_before_lowercase?(block) handle_code_a(block) else handle_code_b(block) end end end.join end def determine_best_type_for_data(data) data = apply_shortest_encoding_for_data(data) type = case data.slice!(0) when CODEA then 'A' when CODEB then 'B' when CODEC then 'C' end [type, data] end private #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. # # # C A or B C A or B # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] def extract_codec(data) segments = data.split(/(\d{4,})/).reject(&:empty?) segments.each_with_index do |s,i| if possible_codec_segment?(s) && s.size.odd? if i == 0 if segments[1] segments[1].insert(0, s.slice!(-1)) else segments[1] = s.slice!(-1) end else segments[i-1].insert(-1, s.slice!(0)) if segments[i-1] end end end segments end def possible_codec_segment?(data) data =~ /\A\d{4,}\Z/ end def control_character?(char) char =~ CTRL_RE end def lowercase_character?(char) char =~ LOWR_RE end #Handle a Code A segment which may contain Code B parts, but may not #contain any Code C parts. def handle_code_a(data) indata = data.dup outdata = CODEA.dup #We know it'll be A while char = indata.slice!(0) if lowercase_character?(char) #Found a lower case character (Code B) if control_before_lowercase?(indata) outdata << SHIFT << char #Control character appears before a new lowercase, use shift else outdata << handle_code_b(char+indata) #Switch to Code B break end else outdata << char end end#while outdata end #Handle a Code B segment which may contain Code A parts, but may not #contain any Code C parts. def handle_code_b(data) indata = data.dup outdata = CODEB.dup #We know this is going to start with Code B while char = indata.slice!(0) if control_character?(char) #Found a control character (Code A) if control_before_lowercase?(indata) #There is another control character before any lowercase, so outdata << handle_code_a(char+indata) #switch over to Code A. break else outdata << SHIFT << char #Can use a shift to only encode this char as Code A end else outdata << char end end#while outdata end #Test str to see if a control character (Code A) appears #before a lower case character (Code B). # #Returns true only if it contains a control character and a lower case #character doesn't appear before it. def control_before_lowercase?(str) ctrl = str =~ CTRL_RE char = str =~ LOWR_RE ctrl && (!char || ctrl < char) end end#class << self end#class Code128 class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end diff --git a/lib/barby/barcode/code_25.rb b/lib/barby/barcode/code_25.rb index 7470357..62a97b4 100644 --- a/lib/barby/barcode/code_25.rb +++ b/lib/barby/barcode/code_25.rb @@ -1,196 +1,196 @@ require 'barby/barcode' module Barby #Standard/Industrial 2 of 5, non-interleaved # #Checksum not included by default, to include it, #set include_checksum = true class Code25 < Barcode1D WIDE = W = true NARROW = N = false START_ENCODING = [W,W,N] STOP_ENCODING = [W,N,W] ENCODINGS = { 0 => [N,N,W,W,N], 1 => [W,N,N,N,W], 2 => [N,W,N,N,W], 3 => [W,W,N,N,N], 4 => [N,N,W,N,W], 5 => [W,N,W,N,N], 6 => [N,W,W,N,N], 7 => [N,N,N,W,W], 8 => [W,N,N,W,N], 9 => [N,W,N,W,N] } attr_accessor :include_checksum attr_writer :narrow_width, :wide_width, :space_width attr_reader :data - + def initialize(data) self.data = data @narrow_width, @wide_width, @space_width = nil end def data_encoding digit_encodings.join end def data_encoding_with_checksum digit_encodings_with_checksum.join end def encoding start_encoding+(include_checksum? ? data_encoding_with_checksum : data_encoding)+stop_encoding end def characters data.split(//) end def characters_with_checksum characters.push(checksum.to_s) end def digits characters.map{|c| c.to_i } end def digits_with_checksum digits.push(checksum) end def even_and_odd_digits alternater = false digits.reverse.partition{ alternater = !alternater } end def digit_encodings raise_invalid unless valid? digits.map{|d| encoding_for(d) } end alias character_encodings digit_encodings def digit_encodings_with_checksum raise_invalid unless valid? digits_with_checksum.map{|d| encoding_for(d) } end alias character_encodings_with_checksum digit_encodings_with_checksum #Returns the encoding for a single digit def encoding_for(digit) encoding_for_bars(ENCODINGS[digit]) end #Generate encoding for an array of W,N def encoding_for_bars(*bars) wide, narrow, space = wide_encoding, narrow_encoding, space_encoding bars.flatten.inject '' do |enc,bar| enc + (bar == WIDE ? wide : narrow) + space end end def encoding_for_bars_without_end_space(*a) encoding_for_bars(*a).gsub(/0+$/, '') end #Mod10 def checksum evens, odds = even_and_odd_digits sum = odds.inject(0){|s,d| s + d } + evens.inject(0){|s,d| s + (d*3) } sum %= 10 sum.zero? ? 0 : 10-sum end def checksum_encoding encoding_for(checksum) end #The width of a narrow bar in xdims def narrow_width @narrow_width || 1 end #The width of a wide bar in xdims #By default three times as wide as a narrow bar def wide_width @wide_width || narrow_width*3 end #The width of the space between the bars in xdims #By default the same width as a narrow bar # #A space serves only as a separator for the bars, #there is no encoded meaning in them def space_width @space_width || narrow_width end #2 of 5 doesn't require a checksum, but you can include a Mod10 checksum #by setting +include_checksum+ to true def include_checksum? include_checksum end def data=(data) @data = "#{data}" end def start_encoding encoding_for_bars(START_ENCODING) end def stop_encoding encoding_for_bars_without_end_space(STOP_ENCODING) end def narrow_encoding '1' * narrow_width end def wide_encoding '1' * wide_width end def space_encoding '0' * space_width end def valid? data =~ /^[0-9]*$/ end def to_s (include_checksum? ? characters_with_checksum : characters).join end private def raise_invalid raise ArgumentError, "data not valid" end end end
toretore/barby
3a96b01e43f2ce22c69bce624fb8ac4a1729fb4e
Remove tests for GS1128
diff --git a/test/barcodes.rb b/test/barcodes.rb index 61b8ae2..c0e6e82 100644 --- a/test/barcodes.rb +++ b/test/barcodes.rb @@ -1,19 +1,18 @@ require 'code_128_test' -require 'gs1_128_test' require 'code_25_test' require 'code_25_interleaved_test' require 'code_25_iata_test' require 'code_39_test' require 'code_93_test' require 'ean13_test' require 'ean8_test' require 'bookland_test' require 'upc_supplemental_test' require 'data_matrix_test' require 'qr_code_test' #require 'pdf_417_test' diff --git a/test/gs1_128_test.rb b/test/gs1_128_test.rb deleted file mode 100644 index e66e2ee..0000000 --- a/test/gs1_128_test.rb +++ /dev/null @@ -1,68 +0,0 @@ -#encoding: ASCII -require 'test_helper' -require 'barby/barcode/gs1_128' - -class GS1128Test < Barby::TestCase - - before do - @code = GS1128.new('071230', 'C', '11') - end - - it "should inherit Code128" do - GS1128.superclass.must_equal Code128 - end - - it "should have an application_identifier attribute" do - @code.must_respond_to(:application_identifier) - @code.must_respond_to(:application_identifier=) - end - - it "should have the given application identifier" do - @code.application_identifier.must_equal '11' - end - - it "should have an application_identifier_encoding" do - @code.must_respond_to(:application_identifier_encoding) - end - - it "should have the expected application_identifier_number" do - @code.application_identifier_number.must_equal 11 - end - - it "should have the expected application identifier encoding" do - @code.application_identifier_encoding.must_equal '11000100100'#Code C number 11 - end - - it "should have data with FNC1 and AI" do - @code.data.must_equal "\30111071230" - end - - it "should have partial_data without FNC1 or AI" do - @code.partial_data.must_equal '071230' - end - - it "should have characters that include FNC1 and AI" do - @code.characters.must_equal %W(\301 11 07 12 30) - end - - it "should have data_encoding that includes FNC1 and the AI" do - @code.data_encoding.must_equal '1111010111011000100100100110001001011001110011011011000' - end - - it "should have the expected checksum" do - @code.checksum.must_equal 36 - end - - it "should have the expected checksum encoding" do - @code.checksum_encoding == '10110001000' - end - - it "should have the expected encoding" do - @code.encoding.must_equal '110100111001111010111011000100100100110001001011001110011011011000101100010001100011101011' - end - - it "should return full data excluding change codes, including AI on to_s" do - @code.to_s.must_equal '(11) 071230' - end - -end
toretore/barby
de61b8ca38143a7640ca642d1b47875bcee55882
Deprecate GS1128 class
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index 8c50678..af35e34 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,532 +1,540 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") + # + # + #GS1-128/EAN-128/UCC-128 + # + #To make a GS1-128 code, prefix the data with FNC1 and the Application Identifier: + # + # #AI=00, data=12345 + # Code128.new("#{Code128::FNC1}0012345") class Code128 < Barcode1D FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" SHIFT = "\xc8" STARTA = "\xc9" STARTB = "\xca" STARTC = "\xcb" STOP = '11000111010' TERMINATE = '11' ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => CODEB, 101 => FNC4, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type def initialize(data, type=nil) if type self.type = type self.data = "#{data}" else self.type, self.data = self.class.determine_best_type_for_data("#{data}") end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type = type.upcase raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra @extra end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_character case type when 'A' then STARTA when 'B' then STARTB when 'C' then STARTC end end def start_num values[start_character] end def start_encoding encodings[start_num] end CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ LOWR_RE = /[a-z]/ DGTS_RE = /\d{4,}/ class << self def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Insert code shift and switch characters where appropriate to get the #shortest encoding possible def apply_shortest_encoding_for_data(data) extract_codec(data).map do |block| if possible_codec_segment?(block) "#{CODEC}#{block}" else if control_before_lowercase?(block) handle_code_a(block) else handle_code_b(block) end end end.join end def determine_best_type_for_data(data) data = apply_shortest_encoding_for_data(data) type = case data.slice!(0) when CODEA then 'A' when CODEB then 'B' when CODEC then 'C' end [type, data] end private #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. # # # C A or B C A or B # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] def extract_codec(data) segments = data.split(/(\d{4,})/).reject(&:empty?) segments.each_with_index do |s,i| if possible_codec_segment?(s) && s.size.odd? if i == 0 if segments[1] segments[1].insert(0, s.slice!(-1)) else segments[1] = s.slice!(-1) end else segments[i-1].insert(-1, s.slice!(0)) if segments[i-1] end end end segments end def possible_codec_segment?(data) data =~ /\A\d{4,}\Z/ end def control_character?(char) char =~ CTRL_RE end def lowercase_character?(char) char =~ LOWR_RE end #Handle a Code A segment which may contain Code B parts, but may not #contain any Code C parts. def handle_code_a(data) indata = data.dup outdata = CODEA.dup #We know it'll be A while char = indata.slice!(0) if lowercase_character?(char) #Found a lower case character (Code B) if control_before_lowercase?(indata) outdata << SHIFT << char #Control character appears before a new lowercase, use shift else outdata << handle_code_b(char+indata) #Switch to Code B break end else outdata << char end end#while outdata end #Handle a Code B segment which may contain Code A parts, but may not #contain any Code C parts. def handle_code_b(data) indata = data.dup outdata = CODEB.dup #We know this is going to start with Code B while char = indata.slice!(0) if control_character?(char) #Found a control character (Code A) if control_before_lowercase?(indata) #There is another control character before any lowercase, so outdata << handle_code_a(char+indata) #switch over to Code A. break else outdata << SHIFT << char #Can use a shift to only encode this char as Code A end else outdata << char end end#while outdata end #Test str to see if a control character (Code A) appears #before a lower case character (Code B). # #Returns true only if it contains a control character and a lower case #character doesn't appear before it. def control_before_lowercase?(str) ctrl = str =~ CTRL_RE char = str =~ LOWR_RE ctrl && (!char || ctrl < char) end diff --git a/lib/barby/barcode/gs1_128.rb b/lib/barby/barcode/gs1_128.rb index 52621ce..94cacbd 100644 --- a/lib/barby/barcode/gs1_128.rb +++ b/lib/barby/barcode/gs1_128.rb @@ -1,42 +1,46 @@ require 'barby/barcode/code_128' module Barby + #DEPRECATED - Use the Code128 class directly instead: + # + # Code128.new("#{Code128::FNC1}#{application_identifier}#{data}") + # #AKA EAN-128, UCC-128 class GS1128 < Code128 attr_accessor :application_identifier def initialize(data, type, ai) + warn "DEPRECATED: The GS1128 class has been deprecated, use Code128 directly instead (called from #{caller[0]})" self.application_identifier = ai super(data, type) end - #TODO: Not sure this is entirely right def data FNC1+application_identifier+super end def partial_data @data end def application_identifier_number values[application_identifier] end def application_identifier_encoding encodings[application_identifier_number] end def to_s "(#{application_identifier}) #{partial_data}" end end end
toretore/barby
0978800da4e4d02e64334a5db7234f7c77916213
FIX Code 128 type= should not modify its arguments
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index cfe6c25..8c50678 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,570 +1,570 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") class Code128 < Barcode1D FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" SHIFT = "\xc8" STARTA = "\xc9" STARTB = "\xca" STARTC = "\xcb" STOP = '11000111010' TERMINATE = '11' ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => CODEB, 101 => FNC4, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type def initialize(data, type=nil) if type self.type = type self.data = "#{data}" else self.type, self.data = self.class.determine_best_type_for_data("#{data}") end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) - type.upcase! + type = type.upcase raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra @extra end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_character case type when 'A' then STARTA when 'B' then STARTB when 'C' then STARTC end end def start_num values[start_character] end def start_encoding encodings[start_num] end CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ LOWR_RE = /[a-z]/ DGTS_RE = /\d{4,}/ class << self def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Insert code shift and switch characters where appropriate to get the #shortest encoding possible def apply_shortest_encoding_for_data(data) extract_codec(data).map do |block| if possible_codec_segment?(block) "#{CODEC}#{block}" else if control_before_lowercase?(block) handle_code_a(block) else handle_code_b(block) end end end.join end def determine_best_type_for_data(data) data = apply_shortest_encoding_for_data(data) type = case data.slice!(0) when CODEA then 'A' when CODEB then 'B' when CODEC then 'C' end [type, data] end private #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. # # # C A or B C A or B # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] def extract_codec(data) segments = data.split(/(\d{4,})/).reject(&:empty?) segments.each_with_index do |s,i| if possible_codec_segment?(s) && s.size.odd? if i == 0 if segments[1] segments[1].insert(0, s.slice!(-1)) else segments[1] = s.slice!(-1) end else segments[i-1].insert(-1, s.slice!(0)) if segments[i-1] end end end segments end def possible_codec_segment?(data) data =~ /\A\d{4,}\Z/ end def control_character?(char) char =~ CTRL_RE end def lowercase_character?(char) char =~ LOWR_RE end #Handle a Code A segment which may contain Code B parts, but may not #contain any Code C parts. def handle_code_a(data) indata = data.dup outdata = CODEA.dup #We know it'll be A while char = indata.slice!(0) if lowercase_character?(char) #Found a lower case character (Code B) if control_before_lowercase?(indata) outdata << SHIFT << char #Control character appears before a new lowercase, use shift else outdata << handle_code_b(char+indata) #Switch to Code B break end else outdata << char end end#while outdata end #Handle a Code B segment which may contain Code A parts, but may not #contain any Code C parts. def handle_code_b(data) indata = data.dup outdata = CODEB.dup #We know this is going to start with Code B while char = indata.slice!(0) if control_character?(char) #Found a control character (Code A) if control_before_lowercase?(indata) #There is another control character before any lowercase, so outdata << handle_code_a(char+indata) #switch over to Code A. break else outdata << SHIFT << char #Can use a shift to only encode this char as Code A end else outdata << char end end#while outdata end #Test str to see if a control character (Code A) appears #before a lower case character (Code B). # #Returns true only if it contains a control character and a lower case #character doesn't appear before it. def control_before_lowercase?(str) ctrl = str =~ CTRL_RE char = str =~ LOWR_RE ctrl && (!char || ctrl < char) end end#class << self end#class Code128 class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end diff --git a/test/code_128_test.rb b/test/code_128_test.rb index 29c6203..5e51538 100644 --- a/test/code_128_test.rb +++ b/test/code_128_test.rb @@ -1,406 +1,411 @@ # encoding: UTF-8 require 'test_helper' require 'barby/barcode/code_128' class Code128Test < Barby::TestCase %w[CODEA CODEB CODEC FNC1 FNC2 FNC3 FNC4 SHIFT].each do |const| const_set const, Code128.const_get(const) end before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do @code.send(:stop_encoding).must_equal '1100011101011' end it "should find the right class for a character A, B or C" do @code.send(:class_for, 'A').must_equal Code128A @code.send(:class_for, 'B').must_equal Code128B @code.send(:class_for, 'C').must_equal Code128C end it "should find the right change code for a class" do @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC end it "should not allow empty data" do lambda{ Code128B.new("") }.must_raise(ArgumentError) end describe "single encoding" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do @code.data.must_equal @data end it "should be able to change its data" do @code.data = '123ABC' @code.data.must_equal '123ABC' @code.data.wont_equal @data end it "should not have an extra" do assert @code.extra.nil? end it "should have empty extra encoding" do @code.extra_encoding.must_equal '' end it "should have the correct checksum" do @code.checksum.must_equal 66 end it "should return all data for to_s" do @code.to_s.must_equal @data end end describe "multiple encodings" do before do @data = binary_encode("ABC123\306def\3074567") @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do @code.full_data.must_equal "ABC123def4567" end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do @code.full_data_with_change_codes.must_equal @data end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = binary_encode("\3071234") code.full_data.must_equal "ABC1234" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234") code.extra.extra = binary_encode("\306abc") code.full_data.must_equal "ABC1234abc" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc") code.extra.extra.data = binary_encode("abc\305DEF") code.full_data.must_equal "ABC1234abcDEF" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc\305DEF") code.extra.extra.full_data.must_equal "abcDEF" code.extra.extra.full_data_with_change_codes.must_equal binary_encode("abc\305DEF") code.extra.full_data.must_equal "1234abcDEF" code.extra.full_data_with_change_codes.must_equal binary_encode("1234\306abc\305DEF") end it "should have a Code B extra" do @code.extra.must_be_instance_of(Code128B) end it "should have a valid extra" do assert @code.extra.valid? end it "the extra should also have an extra of type C" do @code.extra.extra.must_be_instance_of(Code128C) end it "the extra's extra should be valid" do assert @code.extra.extra.valid? end it "should not have more than two extras" do assert @code.extra.extra.extra.nil? end it "should split extra data from string on data assignment" do @code.data = binary_encode("123\306abc") @code.data.must_equal '123' @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal 'abc' end it "should be be able to change its extra" do @code.extra = binary_encode("\3071234") @code.extra.must_be_instance_of(Code128C) @code.extra.data.must_equal '1234' end it "should split extra data from string on extra assignment" do @code.extra = binary_encode("\306123\3074567") @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal '123' @code.extra.extra.must_be_instance_of(Code128C) @code.extra.extra.data.must_equal '4567' end it "should not fail on newlines in extras" do code = Code128B.new(binary_encode("ABC\305\n")) code.data.must_equal "ABC" code.extra.must_be_instance_of(Code128A) code.extra.data.must_equal "\n" code.extra.extra = binary_encode("\305\n\n\n\n\n\nVALID") code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" end it "should raise an exception when extra string doesn't start with the special code character" do lambda{ @code.extra = '123' }.must_raise ArgumentError end it "should have the correct checksum" do @code.checksum.must_equal 84 end it "should have the expected encoding" do #STARTA A B C 1 2 3 @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ #CODEB d e f '10111101110100001001101011001000010110000100'+ #CODEC 45 67 '101110111101011101100010000101100'+ #CHECK=84 STOP '100111101001100011101011' end it "should return all data including extras, except change codes for to_s" do @code.to_s.must_equal "ABC123def4567" end end describe "128A" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = 'abc123' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(A B C 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010000100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10010000110' end end describe "128B" do before do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = binary_encode("abc£123") refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(a b c 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010010000' end it "should have the expected data encoding" do @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '11011101110' end end describe "128C" do before do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = '123' refute @code.valid? @code.data = 'abc' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(12 34 56) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010011100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101100111001000101100011100010110' end it "should have the expected encoding" do @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10001101110' end end describe "Function characters" do it "should retain the special symbols in the data accessor" do Code128A.new(binary_encode("\301ABC\301DEF")).data.must_equal binary_encode("\301ABC\301DEF") Code128B.new(binary_encode("\301ABC\302DEF")).data.must_equal binary_encode("\301ABC\302DEF") Code128C.new(binary_encode("\301123456")).data.must_equal binary_encode("\301123456") Code128C.new(binary_encode("12\30134\30156")).data.must_equal binary_encode("12\30134\30156") end it "should keep the special symbols as characters" do Code128A.new(binary_encode("\301ABC\301DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \301 D E F)) Code128B.new(binary_encode("\301ABC\302DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \302 D E F)) Code128C.new(binary_encode("\301123456")).characters.must_equal binary_encode_array(%W(\301 12 34 56)) Code128C.new(binary_encode("12\30134\30156")).characters.must_equal binary_encode_array(%W(12 \301 34 \301 56)) end it "should not allow FNC > 1 for Code C" do lambda{ Code128C.new("12\302") }.must_raise ArgumentError lambda{ Code128C.new("\30312") }.must_raise ArgumentError lambda{ Code128C.new("12\304") }.must_raise ArgumentError end it "should be included in the encoding" do a = Code128A.new(binary_encode("\301AB")) a.data_encoding.must_equal '111101011101010001100010001011000' a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' end end describe "Code128 with type" do #it "should raise an exception when not given a type" do # lambda{ Code128.new('abc') }.must_raise(ArgumentError) #end it "should raise an exception when given a non-existent type" do lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) end + it "should not fail on frozen type" do + Code128.new('123456', 'C'.freeze) # not failing + Code128.new('123456', 'c'.freeze) # not failing even when upcasing + end + it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end end describe "Code128 automatic charset" do it "should know how to extract CODEC segments properly from a data string" do Code128.send(:extract_codec, "1234abcd5678\r\n\r\n").must_equal ["1234", "abcd", "5678", "\r\n\r\n"] Code128.send(:extract_codec, "12345abc6").must_equal ["1234", "5abc6"] Code128.send(:extract_codec, "abcdef").must_equal ["abcdef"] Code128.send(:extract_codec, "123abcdef45678").must_equal ["123abcdef4", "5678"] Code128.send(:extract_codec, "abcd12345").must_equal ["abcd1", "2345"] Code128.send(:extract_codec, "abcd12345efg").must_equal ["abcd1", "2345", "efg"] Code128.send(:extract_codec, "12345").must_equal ["1234", "5"] Code128.send(:extract_codec, "12345abc").must_equal ["1234", "5abc"] Code128.send(:extract_codec, "abcdef1234567").must_equal ["abcdef1", "234567"] end it "should know how to most efficiently apply different encodings to a data string" do Code128.apply_shortest_encoding_for_data("123456").must_equal "#{CODEC}123456" Code128.apply_shortest_encoding_for_data("abcdef").must_equal "#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("ABCDEF").must_equal "#{CODEB}ABCDEF" Code128.apply_shortest_encoding_for_data("\n\t\r").must_equal "#{CODEA}\n\t\r" Code128.apply_shortest_encoding_for_data("123456abcdef").must_equal "#{CODEC}123456#{CODEB}abcdef" Code128.apply_shortest_encoding_for_data("abcdef123456").must_equal "#{CODEB}abcdef#{CODEC}123456" Code128.apply_shortest_encoding_for_data("1234567").must_equal "#{CODEC}123456#{CODEB}7" Code128.apply_shortest_encoding_for_data("123b456").must_equal "#{CODEB}123b456" Code128.apply_shortest_encoding_for_data("abc123def45678gh").must_equal "#{CODEB}abc123def4#{CODEC}5678#{CODEB}gh" Code128.apply_shortest_encoding_for_data("12345AB\nEEasdgr12EE\r\n").must_equal "#{CODEC}1234#{CODEA}5AB\nEE#{CODEB}asdgr12EE#{CODEA}\r\n" Code128.apply_shortest_encoding_for_data("123456QWERTY\r\n\tAAbbcc12XX34567").must_equal "#{CODEC}123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl" Code128.apply_shortest_encoding_for_data("ABC\rb\nDEF12gHI3456").must_equal "#{CODEA}ABC\r#{SHIFT}b\nDEF12#{CODEB}gHI#{CODEC}3456" Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl\tMNop\nqRs").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl#{SHIFT}\tMNop#{SHIFT}\nqRs" end it "should apply automatic charset when no charset is given" do b = Code128.new("123456QWERTY\r\n\tAAbbcc12XX34567") b.type.must_equal 'C' b.full_data_with_change_codes.must_equal "123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" end end private def binary_encode_array(datas) datas.each { |data| binary_encode(data) } end def binary_encode(data) ruby_19_or_greater? ? data.force_encoding('BINARY') : data end end
toretore/barby
6d0cb73ea03edf768e11fdbbb961eb2802b2f583
:warning: instance variable @x, @y, @xdim, @height, @margin not initialized
diff --git a/lib/barby/outputter/cairo_outputter.rb b/lib/barby/outputter/cairo_outputter.rb index ab26eae..2434100 100644 --- a/lib/barby/outputter/cairo_outputter.rb +++ b/lib/barby/outputter/cairo_outputter.rb @@ -1,185 +1,190 @@ require 'barby/outputter' require 'cairo' require 'stringio' module Barby #Uses Cairo to render a barcode to a number of formats: PNG, PS, EPS, PDF and SVG # #Registers methods render_to_cairo_context, to_png, to_ps, to_eps, to_pdf and to_svg class CairoOutputter < Outputter register :render_to_cairo_context register :to_png if Cairo.const_defined?(:PSSurface) register :to_ps register :to_eps if Cairo::PSSurface.method_defined?(:eps=) end register :to_pdf if Cairo.const_defined?(:PDFSurface) register :to_svg if Cairo.const_defined?(:SVGSurface) attr_writer :x, :y, :xdim, :height, :margin + def initialize(*) + super + @x, @y, @xdim, @height, @margin = nil + end + #Render the barcode onto a Cairo context def render_to_cairo_context(context, options={}) if context.respond_to?(:have_current_point?) and context.have_current_point? current_x, current_y = context.current_point else current_x = x(options) || margin(options) current_y = y(options) || margin(options) end _xdim = xdim(options) _height = height(options) original_current_x = current_x context.save do context.set_source_color(:black) context.fill do if barcode.two_dimensional? boolean_groups.each do |groups| groups.each do |bar,amount| current_width = _xdim * amount if bar context.rectangle(current_x, current_y, current_width, _xdim) end current_x += current_width end current_x = original_current_x current_y += _xdim end else boolean_groups.each do |bar,amount| current_width = _xdim * amount if bar context.rectangle(current_x, current_y, current_width, _height) end current_x += current_width end end end end context end #Render the barcode to a PNG image def to_png(options={}) output_to_string_io do |io| Cairo::ImageSurface.new(options[:format], full_width(options), full_height(options)) do |surface| render(surface, options) surface.write_to_png(io) end end end #Render the barcode to a PS document def to_ps(options={}) output_to_string_io do |io| Cairo::PSSurface.new(io, full_width(options), full_height(options)) do |surface| surface.eps = options[:eps] if surface.respond_to?(:eps=) render(surface, options) end end end #Render the barcode to an EPS document def to_eps(options={}) to_ps(options.merge(:eps => true)) end #Render the barcode to a PDF document def to_pdf(options={}) output_to_string_io do |io| Cairo::PDFSurface.new(io, full_width(options), full_height(options)) do |surface| render(surface, options) end end end #Render the barcode to an SVG document def to_svg(options={}) output_to_string_io do |io| Cairo::SVGSurface.new(io, full_width(options), full_height(options)) do |surface| render(surface, options) end end end def x(options={}) @x || options[:x] end def y(options={}) @y || options[:y] end def width(options={}) (barcode.two_dimensional? ? encoding.first.length : encoding.length) * xdim(options) end def height(options={}) if barcode.two_dimensional? encoding.size * xdim(options) else @height || options[:height] || 50 end end def full_width(options={}) width(options) + (margin(options) * 2) end def full_height(options={}) height(options) + (margin(options) * 2) end def xdim(options={}) @xdim || options[:xdim] || 1 end def margin(options={}) @margin || options[:margin] || 10 end private def output_to_string_io io = StringIO.new yield(io) io.rewind io.read end def render(surface, options) context = Cairo::Context.new(surface) yield(context) if block_given? context.set_source_color(options[:background] || :white) context.paint render_to_cairo_context(context, options) context end end end
toretore/barby
e86ff7edde404f43cfb20f710f4d5efc5c9e7f91
:warning: instance variable @title, @xdim, @ydim, @height, @rmargin, @lmargin, @tmargin, @bmargin, @xmargin, @ymargin, @margin not initialized
diff --git a/lib/barby/outputter/svg_outputter.rb b/lib/barby/outputter/svg_outputter.rb index 44d7b16..fd440a7 100644 --- a/lib/barby/outputter/svg_outputter.rb +++ b/lib/barby/outputter/svg_outputter.rb @@ -1,225 +1,230 @@ require 'barby/outputter' module Barby #Renders the barcode to a simple SVG image using pure ruby # #Registers the to_svg, bars_to_path, and bars_to_rects method # #Bars can be rendered as a stroked path or as filled rectangles. Path #generally yields smaller files, but this doesn't render cleanly in Firefox #3 for odd xdims. My guess is that the renderer tries to put half a pixel #on one side of the path and half on the other, leading to fuzzy dithering #instead of sharp, clean b&w. # #Therefore, default behavior is to use a path for even xdims, and #rectangles for odd. This can be overridden by calling with explicit #:use => 'rects' or :use => 'path' options. class SvgOutputter < Outputter register :to_svg, :bars_to_rects, :bars_to_path attr_writer :title, :xdim, :ydim, :height, :rmargin, :lmargin, :tmargin, :bmargin, :xmargin, :ymargin, :margin + def initialize(*) + super + @title, @xdim, @ydim, @height, @rmargin, @lmargin, @tmargin, @bmargin, @xmargin, @ymargin, @margin = nil + end + def to_svg(opts={}) with_options opts do case opts[:use] when 'rects' then bars = bars_to_rects when 'path' then bars = bars_to_path else xdim_odd = (xdim % 2 == 1) bars = xdim_odd ? bars_to_rects : bars_to_path end <<-"EOT" <?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="#{svg_width(opts)}px" height="#{svg_height(opts)}px" viewBox="0 0 #{svg_width(opts)} #{svg_height(opts)}" version="1.1"> <title>#{escape title}</title> <g id="canvas" #{transform(opts)}> <rect x="0" y="0" width="#{full_width}px" height="#{full_height}px" fill="white" /> <g id="barcode" fill="black"> #{bars} </g></g> </svg> EOT end end def bars_to_rects(opts={}) rects = '' with_options opts do x, y = lmargin, tmargin if barcode.two_dimensional? boolean_groups.each do |line| line.each do |bar, amount| bar_width = xdim * amount if bar rects << %Q|<rect x="#{x}" y="#{y}" width="#{bar_width}px" height="#{ydim}px" />\n| end x += bar_width end y += ydim x = lmargin end else boolean_groups.each do |bar, amount| bar_width = xdim * amount if bar rects << %Q|<rect x="#{x}" y="#{y}" width="#{bar_width}px" height="#{height}px" />\n| end x += bar_width end end end # with_options rects end def bars_to_path(opts={}) with_options opts do %Q|<path stroke="black" stroke-width="#{xdim}" d="#{bars_to_path_data(opts)}" />| end end def bars_to_path_data(opts={}) path_data = '' with_options opts do x, y = lmargin+(xdim/2), tmargin if barcode.two_dimensional? booleans.each do |line| line.each do |bar| if bar path_data << "M#{x} #{y}V #{y+ydim}" end x += xdim end y += ydim x = lmargin+(xdim/2) end else booleans.each do |bar| if bar path_data << "M#{x} #{y}V#{y+height}" end x += xdim end end end # with_options path_data end def title @title || barcode.to_s end def width length * xdim end def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end def full_width width + lmargin + rmargin end def full_height height + tmargin + bmargin end def xdim @xdim || 1 end def ydim @ydim || xdim end def lmargin @lmargin || _xmargin end def rmargin @rmargin || _xmargin end def tmargin @tmargin || _ymargin end def bmargin @bmargin || _ymargin end def xmargin return nil if @lmargin || @rmargin _margin end def ymargin return nil if @tmargin || @bmargin _margin end def margin return nil if @ymargin || @xmargin || @tmargin || @bmargin || @lmargin || @rmargin _margin end def length barcode.two_dimensional? ? encoding.first.length : encoding.length end def svg_width(opts={}) opts[:rot] ? full_height : full_width end def svg_height(opts={}) opts[:rot] ? full_width : full_height end def transform(opts={}) opts[:rot] ? %Q|transform="rotate(-90) translate(-#{full_width}, 0)"| : nil end private def _xmargin @xmargin || _margin end def _ymargin @ymargin || _margin end def _margin @margin || 10 end #Escape XML special characters <, & and > def escape(str) str.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;') end end end
toretore/barby
9916b04a5b5700922af1a14fa0a8e1895aad3279
:warning: instance variable @height, @xdim, @ydim, @margin not initialized
diff --git a/lib/barby/outputter/rmagick_outputter.rb b/lib/barby/outputter/rmagick_outputter.rb index fdb79f1..6e5d7a1 100644 --- a/lib/barby/outputter/rmagick_outputter.rb +++ b/lib/barby/outputter/rmagick_outputter.rb @@ -1,135 +1,140 @@ require 'barby/outputter' require 'RMagick' module Barby #Renders images from barcodes using RMagick # #Registers the to_png, to_gif, to_jpg and to_image methods class RmagickOutputter < Outputter register :to_png, :to_gif, :to_jpg, :to_image attr_writer :height, :xdim, :ydim, :margin + def initialize(*) + super + @height, @xdim, @ydim, @margin = nil + end + #Returns a string containing a PNG image def to_png(*a) to_blob('png', *a) end #Returns a string containint a GIF image def to_gif(*a) to_blob('gif', *a) end #Returns a string containing a JPEG image def to_jpg(*a) to_blob('jpg', *a) end def to_blob(format, *a) img = to_image(*a) blob = img.to_blob{|i| i.format = format } #Release the memory used by RMagick explicitly. Ruby's GC #isn't aware of it and can't clean it up automatically img.destroy! if img.respond_to?(:destroy!) blob end #Returns an instance of Magick::Image def to_image(opts={}) with_options opts do canvas = Magick::Image.new(full_width, full_height) bars = Magick::Draw.new x1 = margin y1 = margin if barcode.two_dimensional? encoding.each do |line| line.split(//).map{|c| c == '1' }.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(ydim-1) # For single pixels use point if x1 == x2 && y1 == y2 bars.point(x1,y1) else bars.rectangle(x1, y1, x2, y2) end end x1 += xdim end x1 = margin y1 += ydim end else booleans.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(height-1) bars.rectangle(x1, y1, x2, y2) end x1 += xdim end end bars.draw(canvas) canvas end end #The height of the barcode in px #For 2D barcodes this is the number of "lines" * ydim def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end #The width of the barcode in px def width length * xdim end #Number of modules (xdims) on the x axis def length barcode.two_dimensional? ? encoding.first.length : encoding.length end #X dimension. 1X == 1px def xdim @xdim || 1 end #Y dimension. Only for 2D codes def ydim @ydim || xdim end #The margin of each edge surrounding the barcode in pixels def margin @margin || 10 end #The full width of the image. This is the width of the #barcode + the left and right margin def full_width width + (margin * 2) end #The height of the image. This is the height of the #barcode + the top and bottom margin def full_height height + (margin * 2) end end end
toretore/barby
c2a922e78e25e0548f571602f9bb8ae6f29ed751
:warning: method redefined; discarding old height, xdim, ydim, margin
diff --git a/lib/barby/outputter/rmagick_outputter.rb b/lib/barby/outputter/rmagick_outputter.rb index 24d1d26..fdb79f1 100644 --- a/lib/barby/outputter/rmagick_outputter.rb +++ b/lib/barby/outputter/rmagick_outputter.rb @@ -1,135 +1,135 @@ require 'barby/outputter' require 'RMagick' module Barby #Renders images from barcodes using RMagick # #Registers the to_png, to_gif, to_jpg and to_image methods class RmagickOutputter < Outputter register :to_png, :to_gif, :to_jpg, :to_image - attr_accessor :height, :xdim, :ydim, :margin + attr_writer :height, :xdim, :ydim, :margin #Returns a string containing a PNG image def to_png(*a) to_blob('png', *a) end #Returns a string containint a GIF image def to_gif(*a) to_blob('gif', *a) end #Returns a string containing a JPEG image def to_jpg(*a) to_blob('jpg', *a) end def to_blob(format, *a) img = to_image(*a) blob = img.to_blob{|i| i.format = format } #Release the memory used by RMagick explicitly. Ruby's GC #isn't aware of it and can't clean it up automatically img.destroy! if img.respond_to?(:destroy!) blob end #Returns an instance of Magick::Image def to_image(opts={}) with_options opts do canvas = Magick::Image.new(full_width, full_height) bars = Magick::Draw.new x1 = margin y1 = margin if barcode.two_dimensional? encoding.each do |line| line.split(//).map{|c| c == '1' }.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(ydim-1) # For single pixels use point if x1 == x2 && y1 == y2 bars.point(x1,y1) else bars.rectangle(x1, y1, x2, y2) end end x1 += xdim end x1 = margin y1 += ydim end else booleans.each do |bar| if bar x2 = x1+(xdim-1) y2 = y1+(height-1) bars.rectangle(x1, y1, x2, y2) end x1 += xdim end end bars.draw(canvas) canvas end end #The height of the barcode in px #For 2D barcodes this is the number of "lines" * ydim def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end #The width of the barcode in px def width length * xdim end #Number of modules (xdims) on the x axis def length barcode.two_dimensional? ? encoding.first.length : encoding.length end #X dimension. 1X == 1px def xdim @xdim || 1 end #Y dimension. Only for 2D codes def ydim @ydim || xdim end #The margin of each edge surrounding the barcode in pixels def margin @margin || 10 end #The full width of the image. This is the width of the #barcode + the left and right margin def full_width width + (margin * 2) end #The height of the image. This is the height of the #barcode + the top and bottom margin def full_height height + (margin * 2) end end end
toretore/barby
634925e89975ec09c0d6ab03ef0aa1f39a58ba0d
:warning: method redefined; discarding old xdim, ydim, width, height, margin
diff --git a/lib/barby/outputter/png_outputter.rb b/lib/barby/outputter/png_outputter.rb index 2d4d10d..5d263a1 100644 --- a/lib/barby/outputter/png_outputter.rb +++ b/lib/barby/outputter/png_outputter.rb @@ -1,111 +1,111 @@ require 'barby/outputter' require 'chunky_png' module Barby #Renders the barcode to a PNG image using chunky_png (gem install chunky_png) # #Registers the to_png, to_datastream and to_canvas methods class PngOutputter < Outputter register :to_png, :to_image, :to_datastream - attr_accessor :xdim, :ydim, :width, :height, :margin + attr_writer :xdim, :ydim, :width, :height, :margin def initialize(*) super @xdim, @height, @margin = nil end #Creates a PNG::Canvas object and renders the barcode on it def to_image(opts={}) with_options opts do canvas = ChunkyPNG::Image.new(full_width, full_height, ChunkyPNG::Color::WHITE) if barcode.two_dimensional? x, y = margin, margin booleans.each do |line| line.each do |bar| if bar x.upto(x+(xdim-1)) do |xx| y.upto y+(ydim-1) do |yy| canvas[xx,yy] = ChunkyPNG::Color::BLACK end end end x += xdim end y += ydim x = margin end else x, y = margin, margin booleans.each do |bar| if bar x.upto(x+(xdim-1)) do |xx| y.upto y+(height-1) do |yy| canvas[xx,yy] = ChunkyPNG::Color::BLACK end end end x += xdim end end canvas end end #Create a ChunkyPNG::Datastream containing the barcode image # # :constraints - Value is passed on to ChunkyPNG::Image#to_datastream # E.g. to_datastream(:constraints => {:color_mode => ChunkyPNG::COLOR_GRAYSCALE}) def to_datastream(*a) constraints = a.first && a.first[:constraints] ? [a.first[:constraints]] : [] to_image(*a).to_datastream(*constraints) end #Renders the barcode to a PNG image def to_png(*a) to_datastream(*a).to_s end def width length * xdim end def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end def full_width width + (margin * 2) end def full_height height + (margin * 2) end def xdim @xdim || 1 end def ydim @ydim || xdim end def margin @margin || 10 end def length barcode.two_dimensional? ? encoding.first.length : encoding.length end end end
toretore/barby
e34b38ab518475c1a1cadf28a3635fc401490e39
:warning: instance variable @xdim, @height, @margin not initialized
diff --git a/lib/barby/outputter/png_outputter.rb b/lib/barby/outputter/png_outputter.rb index dfbb12c..2d4d10d 100644 --- a/lib/barby/outputter/png_outputter.rb +++ b/lib/barby/outputter/png_outputter.rb @@ -1,107 +1,111 @@ require 'barby/outputter' require 'chunky_png' module Barby #Renders the barcode to a PNG image using chunky_png (gem install chunky_png) # #Registers the to_png, to_datastream and to_canvas methods class PngOutputter < Outputter register :to_png, :to_image, :to_datastream attr_accessor :xdim, :ydim, :width, :height, :margin + def initialize(*) + super + @xdim, @height, @margin = nil + end #Creates a PNG::Canvas object and renders the barcode on it def to_image(opts={}) with_options opts do canvas = ChunkyPNG::Image.new(full_width, full_height, ChunkyPNG::Color::WHITE) if barcode.two_dimensional? x, y = margin, margin booleans.each do |line| line.each do |bar| if bar x.upto(x+(xdim-1)) do |xx| y.upto y+(ydim-1) do |yy| canvas[xx,yy] = ChunkyPNG::Color::BLACK end end end x += xdim end y += ydim x = margin end else x, y = margin, margin booleans.each do |bar| if bar x.upto(x+(xdim-1)) do |xx| y.upto y+(height-1) do |yy| canvas[xx,yy] = ChunkyPNG::Color::BLACK end end end x += xdim end end canvas end end #Create a ChunkyPNG::Datastream containing the barcode image # # :constraints - Value is passed on to ChunkyPNG::Image#to_datastream # E.g. to_datastream(:constraints => {:color_mode => ChunkyPNG::COLOR_GRAYSCALE}) def to_datastream(*a) constraints = a.first && a.first[:constraints] ? [a.first[:constraints]] : [] to_image(*a).to_datastream(*constraints) end #Renders the barcode to a PNG image def to_png(*a) to_datastream(*a).to_s end def width length * xdim end def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end def full_width width + (margin * 2) end def full_height height + (margin * 2) end def xdim @xdim || 1 end def ydim @ydim || xdim end def margin @margin || 10 end def length barcode.two_dimensional? ? encoding.first.length : encoding.length end end end
toretore/barby
4f5b031ae902e226c68ac7f5edcc06854da2b137
:warning: instance variable @xdim, @ydim, @x, @y, @height, @margin, @unbleed not initialized
diff --git a/lib/barby/outputter/prawn_outputter.rb b/lib/barby/outputter/prawn_outputter.rb index 9015929..00ce804 100644 --- a/lib/barby/outputter/prawn_outputter.rb +++ b/lib/barby/outputter/prawn_outputter.rb @@ -1,121 +1,126 @@ require 'barby/outputter' require 'prawn' module Barby class PrawnOutputter < Outputter register :to_pdf, :annotate_pdf attr_writer :xdim, :ydim, :x, :y, :height, :margin, :unbleed + def initialize(*) + super + @xdim, @ydim, @x, @y, @height, @margin, @unbleed = nil + end + def to_pdf(opts={}) doc_opts = opts.delete(:document) || {} doc_opts[:page_size] ||= 'A4' annotate_pdf(Prawn::Document.new(doc_opts), opts).render end def annotate_pdf(pdf, opts={}) with_options opts do xpos, ypos = x, y orig_xpos = xpos if barcode.two_dimensional? boolean_groups.reverse_each do |groups| groups.each do |bar,amount| if bar pdf.move_to(xpos+unbleed, ypos+unbleed) pdf.line_to(xpos+unbleed, ypos+ydim-unbleed) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos+ydim-unbleed) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos+unbleed) pdf.line_to(xpos+unbleed, ypos+unbleed) pdf.fill end xpos += (xdim*amount) end xpos = orig_xpos ypos += ydim end else boolean_groups.each do |bar,amount| if bar pdf.move_to(xpos+unbleed, ypos) pdf.line_to(xpos+unbleed, ypos+height) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos+height) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos) pdf.line_to(xpos+unbleed, ypos) pdf.fill end xpos += (xdim*amount) end end end pdf end def length two_dimensional? ? encoding.first.length : encoding.length end def width length * xdim end def height two_dimensional? ? (ydim * encoding.length) : (@height || 50) end def full_width width + (margin * 2) end def full_height height + (margin * 2) end #Margin is used for x and y if not given explicitly, effectively placing the barcode #<margin> points from the [left,bottom] of the page. #If you define x and y, there will be no margin. And if you don't define margin, it's 0. def margin @margin || 0 end def x @x || margin end def y @y || margin end def xdim @xdim || 1 end def ydim @ydim || xdim end #Defines an amount to reduce black bars/squares by to account for "ink bleed" #If xdim = 3, unbleed = 0.2, a single/width black bar will be 2.6 wide #For 2D, both x and y dimensions are reduced. def unbleed @unbleed || 0 end private def page_size(xdim, height, margin) [width(xdim,margin), height(height,margin)] end end end
toretore/barby
1438ca94bb7c24458f71b087c27a47bf7264f893
:warning: method redefined; discarding old xdim, ydim, x, y, height, margin, unbleed
diff --git a/lib/barby/outputter/prawn_outputter.rb b/lib/barby/outputter/prawn_outputter.rb index 9e422c3..9015929 100644 --- a/lib/barby/outputter/prawn_outputter.rb +++ b/lib/barby/outputter/prawn_outputter.rb @@ -1,121 +1,121 @@ require 'barby/outputter' require 'prawn' module Barby class PrawnOutputter < Outputter register :to_pdf, :annotate_pdf - attr_accessor :xdim, :ydim, :x, :y, :height, :margin, :unbleed + attr_writer :xdim, :ydim, :x, :y, :height, :margin, :unbleed def to_pdf(opts={}) doc_opts = opts.delete(:document) || {} doc_opts[:page_size] ||= 'A4' annotate_pdf(Prawn::Document.new(doc_opts), opts).render end def annotate_pdf(pdf, opts={}) with_options opts do xpos, ypos = x, y orig_xpos = xpos if barcode.two_dimensional? boolean_groups.reverse_each do |groups| groups.each do |bar,amount| if bar pdf.move_to(xpos+unbleed, ypos+unbleed) pdf.line_to(xpos+unbleed, ypos+ydim-unbleed) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos+ydim-unbleed) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos+unbleed) pdf.line_to(xpos+unbleed, ypos+unbleed) pdf.fill end xpos += (xdim*amount) end xpos = orig_xpos ypos += ydim end else boolean_groups.each do |bar,amount| if bar pdf.move_to(xpos+unbleed, ypos) pdf.line_to(xpos+unbleed, ypos+height) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos+height) pdf.line_to(xpos+(xdim*amount)-unbleed, ypos) pdf.line_to(xpos+unbleed, ypos) pdf.fill end xpos += (xdim*amount) end end end pdf end def length two_dimensional? ? encoding.first.length : encoding.length end def width length * xdim end def height two_dimensional? ? (ydim * encoding.length) : (@height || 50) end def full_width width + (margin * 2) end def full_height height + (margin * 2) end #Margin is used for x and y if not given explicitly, effectively placing the barcode #<margin> points from the [left,bottom] of the page. #If you define x and y, there will be no margin. And if you don't define margin, it's 0. def margin @margin || 0 end def x @x || margin end def y @y || margin end def xdim @xdim || 1 end def ydim @ydim || xdim end #Defines an amount to reduce black bars/squares by to account for "ink bleed" #If xdim = 3, unbleed = 0.2, a single/width black bar will be 2.6 wide #For 2D, both x and y dimensions are reduced. def unbleed @unbleed || 0 end private def page_size(xdim, height, margin) [width(xdim,margin), height(height,margin)] end end end
toretore/barby
dd84559079fae43ee4f3fa31ee08eec59d6de770
:warning: instance variable @extra not initialized
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index cfe6c25..838c4b7 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,570 +1,570 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") class Code128 < Barcode1D FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" SHIFT = "\xc8" STARTA = "\xc9" STARTB = "\xca" STARTC = "\xcb" STOP = '11000111010' TERMINATE = '11' ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => CODEB, 101 => FNC4, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type def initialize(data, type=nil) if type self.type = type self.data = "#{data}" else self.type, self.data = self.class.determine_best_type_for_data("#{data}") end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type.upcase! raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra - @extra + @extra ||= nil end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_character case type when 'A' then STARTA when 'B' then STARTB when 'C' then STARTC end end def start_num values[start_character] end def start_encoding encodings[start_num] end CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ LOWR_RE = /[a-z]/ DGTS_RE = /\d{4,}/ class << self def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Insert code shift and switch characters where appropriate to get the #shortest encoding possible def apply_shortest_encoding_for_data(data) extract_codec(data).map do |block| if possible_codec_segment?(block) "#{CODEC}#{block}" else if control_before_lowercase?(block) handle_code_a(block) else handle_code_b(block) end end end.join end def determine_best_type_for_data(data) data = apply_shortest_encoding_for_data(data) type = case data.slice!(0) when CODEA then 'A' when CODEB then 'B' when CODEC then 'C' end [type, data] end private #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. # # # C A or B C A or B # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] def extract_codec(data) segments = data.split(/(\d{4,})/).reject(&:empty?) segments.each_with_index do |s,i| if possible_codec_segment?(s) && s.size.odd? if i == 0 if segments[1] segments[1].insert(0, s.slice!(-1)) else segments[1] = s.slice!(-1) end else segments[i-1].insert(-1, s.slice!(0)) if segments[i-1] end end end segments end def possible_codec_segment?(data) data =~ /\A\d{4,}\Z/ end def control_character?(char) char =~ CTRL_RE end def lowercase_character?(char) char =~ LOWR_RE end #Handle a Code A segment which may contain Code B parts, but may not #contain any Code C parts. def handle_code_a(data) indata = data.dup outdata = CODEA.dup #We know it'll be A while char = indata.slice!(0) if lowercase_character?(char) #Found a lower case character (Code B) if control_before_lowercase?(indata) outdata << SHIFT << char #Control character appears before a new lowercase, use shift else outdata << handle_code_b(char+indata) #Switch to Code B break end else outdata << char end end#while outdata end #Handle a Code B segment which may contain Code A parts, but may not #contain any Code C parts. def handle_code_b(data) indata = data.dup outdata = CODEB.dup #We know this is going to start with Code B while char = indata.slice!(0) if control_character?(char) #Found a control character (Code A) if control_before_lowercase?(indata) #There is another control character before any lowercase, so outdata << handle_code_a(char+indata) #switch over to Code A. break else outdata << SHIFT << char #Can use a shift to only encode this char as Code A end else outdata << char end end#while outdata end #Test str to see if a control character (Code A) appears #before a lower case character (Code B). # #Returns true only if it contains a control character and a lower case #character doesn't appear before it. def control_before_lowercase?(str) ctrl = str =~ CTRL_RE char = str =~ LOWR_RE ctrl && (!char || ctrl < char) end end#class << self end#class Code128 class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end
toretore/barby
54ee57ff449ad368b40f5d7d6180969d00414e38
:warning: method redefined; discarding old data=
diff --git a/lib/barby/barcode/data_matrix.rb b/lib/barby/barcode/data_matrix.rb index 9bf9576..f872a8c 100644 --- a/lib/barby/barcode/data_matrix.rb +++ b/lib/barby/barcode/data_matrix.rb @@ -1,46 +1,46 @@ require 'semacode' #Ruby 1.8: gem install semacode - Ruby 1.9: gem install semacode-ruby19 require 'barby/barcode' module Barby #Uses the semacode library (gem install semacode) to encode DataMatrix barcodes class DataMatrix < Barcode2D - attr_accessor :data + attr_reader :data def initialize(data) self.data = data end def data=(data) @data = data @encoder = nil end def encoder @encoder ||= ::DataMatrix::Encoder.new(data) end def encoding encoder.data.map{|a| a.map{|b| b ? '1' : '0' }.join } end def semacode? #TODO: Not sure if this is right data =~ /^http:\/\// end def to_s data end end end
toretore/barby
e718f328fc94133ab4c1d7b05695bf83216341d8
:warning: method redefined; discarding old spacing, narrow_width, wide_width
diff --git a/lib/barby/barcode/code_39.rb b/lib/barby/barcode/code_39.rb index 23e6a8b..1eea290 100644 --- a/lib/barby/barcode/code_39.rb +++ b/lib/barby/barcode/code_39.rb @@ -1,235 +1,236 @@ #encoding: ASCII require 'barby/barcode' module Barby class Code39 < Barcode1D WIDE = W = true NARROW = N = false ENCODINGS = { ' ' => [N,W,W,N,N,N,W,N,N], '$' => [N,W,N,W,N,W,N,N,N], '%' => [N,N,N,W,N,W,N,W,N], '+' => [N,W,N,N,N,W,N,W,N], '-' => [N,W,N,N,N,N,W,N,W], '.' => [W,W,N,N,N,N,W,N,N], '/' => [N,W,N,W,N,N,N,W,N], '0' => [N,N,N,W,W,N,W,N,N], '1' => [W,N,N,W,N,N,N,N,W], '2' => [N,N,W,W,N,N,N,N,W], '3' => [W,N,W,W,N,N,N,N,N], '4' => [N,N,N,W,W,N,N,N,W], '5' => [W,N,N,W,W,N,N,N,N], '6' => [N,N,W,W,W,N,N,N,N], '7' => [N,N,N,W,N,N,W,N,W], '8' => [W,N,N,W,N,N,W,N,N], '9' => [N,N,W,W,N,N,W,N,N], 'A' => [W,N,N,N,N,W,N,N,W], 'B' => [N,N,W,N,N,W,N,N,W], 'C' => [W,N,W,N,N,W,N,N,N], 'D' => [N,N,N,N,W,W,N,N,W], 'E' => [W,N,N,N,W,W,N,N,N], 'F' => [N,N,W,N,W,W,N,N,N], 'G' => [N,N,N,N,N,W,W,N,W], 'H' => [W,N,N,N,N,W,W,N,N], 'I' => [N,N,W,N,N,W,W,N,N], 'J' => [N,N,N,N,W,W,W,N,N], 'K' => [W,N,N,N,N,N,N,W,W], 'L' => [N,N,W,N,N,N,N,W,W], 'M' => [W,N,W,N,N,N,N,W,N], 'N' => [N,N,N,N,W,N,N,W,W], 'O' => [W,N,N,N,W,N,N,W,N], 'P' => [N,N,W,N,W,N,N,W,N], 'Q' => [N,N,N,N,N,N,W,W,W], 'R' => [W,N,N,N,N,N,W,W,N], 'S' => [N,N,W,N,N,N,W,W,N], 'T' => [N,N,N,N,W,N,W,W,N], 'U' => [W,W,N,N,N,N,N,N,W], 'V' => [N,W,W,N,N,N,N,N,W], 'W' => [W,W,W,N,N,N,N,N,N], 'X' => [N,W,N,N,W,N,N,N,W], 'Y' => [W,W,N,N,W,N,N,N,N], 'Z' => [N,W,W,N,W,N,N,N,N] } #In extended mode, each character is replaced with two characters from the "normal" encoding EXTENDED_ENCODINGS = { "\000" => '%U', " " => " ", "@" => "%V", "`" => "%W", "\001" => '$A', "!" => "/A", "A" => "A", "a" => "+A", "\002" => '$B', '"' => "/B", "B" => "B", "b" => "+B", "\003" => '$C', "#" => "/C", "C" => "C", "c" => "+C", "\004" => '$D', "$" => "/D", "D" => "D", "d" => "+D", "\005" => '$E', "%" => "/E", "E" => "E", "e" => "+E", "\006" => '$F', "&" => "/F", "F" => "F", "f" => "+F", "\007" => '$G', "'" => "/G", "G" => "G", "g" => "+G", "\010" => '$H', "(" => "/H", "H" => "H", "h" => "+H", "\011" => '$I', ")" => "/I", "I" => "I", "i" => "+I", "\012" => '$J', "*" => "/J", "J" => "J", "j" => "+J", "\013" => '$K', "+" => "/K", "K" => "K", "k" => "+K", "\014" => '$L', "," => "/L", "L" => "L", "l" => "+L", "\015" => '$M', "-" => "-", "M" => "M", "m" => "+M", "\016" => '$N', "." => ".", "N" => "N", "n" => "+N", "\017" => '$O', "/" => "/O", "O" => "O", "o" => "+O", "\020" => '$P', "0" => "0", "P" => "P", "p" => "+P", "\021" => '$Q', "1" => "1", "Q" => "Q", "q" => "+Q", "\022" => '$R', "2" => "2", "R" => "R", "r" => "+R", "\023" => '$S', "3" => "3", "S" => "S", "s" => "+S", "\024" => '$T', "4" => "4", "T" => "T", "t" => "+T", "\025" => '$U', "5" => "5", "U" => "U", "u" => "+U", "\026" => '$V', "6" => "6", "V" => "V", "v" => "+V", "\027" => '$W', "7" => "7", "W" => "W", "w" => "+W", "\030" => '$X', "8" => "8", "X" => "X", "x" => "+X", "\031" => '$Y', "9" => "9", "Y" => "Y", "y" => "+Y", "\032" => '$Z', ":" => "/Z", "Z" => "Z", "z" => "+Z", "\033" => '%A', ";" => "%F", "[" => "%K", "{" => "%P", "\034" => '%B', "<" => "%G", "\\" => "%L", "|" => "%Q", "\035" => '%C', "=" => "%H", "]" => "%M", "}" => "%R", "\036" => '%D', ">" => "%I", "^" => "%N", "~" => "%S", "\037" => '%E', "?" => "%J", "_" => "%O", "\177" => "%T" } CHECKSUM_VALUES = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'I' => 18, 'J' => 19, 'K' => 20, 'L' => 21, 'N' => 23, 'M' => 22, 'O' => 24, 'P' => 25, 'Q' => 26, 'R' => 27, 'S' => 28, 'T' => 29, 'U' => 30, 'V' => 31, 'W' => 32, 'X' => 33, 'Y' => 34, 'Z' => 35, '-' => 36, '.' => 37, ' ' => 38, '$' => 39, '/' => 40, '+' => 41, '%' => 42 } START_ENCODING = [N,W,N,N,W,N,W,N,N] # * STOP_ENCODING = [N,W,N,N,W,N,W,N,N] # * - attr_accessor :data, :spacing, :narrow_width, :wide_width, :extended, :include_checksum + attr_accessor :data, :extended, :include_checksum + attr_writer :spacing, :narrow_width, :wide_width # Do not surround "data" with the mandatory "*" as is this is done automically for you. # So instead of passing "*123456*" as "data", just pass "123456". def initialize(data, extended=false) self.data = data self.extended = extended raise(ArgumentError, "data is not valid (extended=#{extended?})") unless valid? yield self if block_given? end #Returns the characters that were passed in, no matter it they're part of #the extended charset or if they're already encodable, "normal" characters def raw_characters data.split(//) end #Returns the encodable characters. If extended mode is enabled, each character will #first be replaced by two characters from the encodable charset def characters chars = raw_characters extended ? chars.map{|c| EXTENDED_ENCODINGS[c].split(//) }.flatten : chars end def characters_with_checksum characters + [checksum_character] end def encoded_characters characters.map{|c| encoding_for(c) } end def encoded_characters_with_checksum encoded_characters + [checksum_encoding] end #The data part of the encoding (no start+stop characters) def data_encoding encoded_characters.join(spacing_encoding) end def data_encoding_with_checksum encoded_characters_with_checksum.join(spacing_encoding) end def encoding return encoding_with_checksum if include_checksum? start_encoding+spacing_encoding+data_encoding+spacing_encoding+stop_encoding end def encoding_with_checksum start_encoding+spacing_encoding+data_encoding_with_checksum+spacing_encoding+stop_encoding end #Checksum is optional def checksum characters.inject(0) do |sum,char| sum + CHECKSUM_VALUES[char] end % 43 end def checksum_character CHECKSUM_VALUES.invert[checksum] end def checksum_encoding encoding_for(checksum_character) end #Set include_checksum to true to make +encoding+ include the checksum def include_checksum? include_checksum end #Takes an array of WIDE/NARROW values and returns the string representation for #those bars and spaces, using wide_width and narrow_width def encoding_for_bars(*bars_and_spaces) bar = false bars_and_spaces.flatten.map do |width| bar = !bar (bar ? '1' : '0') * (width == WIDE ? wide_width : narrow_width) end.join end #Returns the string representation for a single character def encoding_for(character) encoding_for_bars(ENCODINGS[character]) end #Spacing between the characters in xdims. Spacing will be inserted #between each character in the encoding def spacing @spacing ||= 1 end def spacing_encoding '0' * spacing end def narrow_width @narrow_width ||= 1 end def wide_width @wide_width ||= 2 end def extended? extended end def start_encoding encoding_for_bars(START_ENCODING) end def stop_encoding encoding_for_bars(STOP_ENCODING) end def valid? if extended? raw_characters.all?{|c| EXTENDED_ENCODINGS.include?(c) } else raw_characters.all?{|c| ENCODINGS.include?(c) } end end def to_s data end end end
toretore/barby
760e6da74810e11a8acae07f686eeca754a98edb
:warning: instance variable @level, @size not initialized
diff --git a/lib/barby/barcode/qr_code.rb b/lib/barby/barcode/qr_code.rb index 064d1c8..82ae0f6 100644 --- a/lib/barby/barcode/qr_code.rb +++ b/lib/barby/barcode/qr_code.rb @@ -1,101 +1,102 @@ require 'rqrcode' require 'barby/barcode' module Barby #QrCode is a thin wrapper around the RQRCode library class QrCode < Barcode2D #Maximum sizes for each correction level for binary data #It's an array SIZES = { #L M Q H 1 => [17, 14, 11, 7], 2 => [32, 26, 20, 14], 3 => [53, 42, 32, 24], 4 => [78, 62, 46, 34], 5 => [106, 84, 60, 44], 6 => [134, 106, 74, 58], 7 => [154, 122, 86, 64], 8 => [192, 152, 108, 84], 9 => [230, 180, 130, 98], 10 => [271, 213, 151, 119], 11 => [321, 251, 177, 137], 12 => [367, 287, 203, 155], 13 => [425, 331, 241, 177], 14 => [458, 362, 258, 194], 15 => [520, 412, 292, 220], 16 => [586, 450, 322, 250], 17 => [644, 504, 364, 280], 18 => [718, 560, 394, 310], 19 => [792, 624, 442, 338], 20 => [858, 666, 482, 382], 21 => [929, 711, 509, 403], 22 => [1003, 779, 565, 439], 23 => [1091, 857, 611, 461], 24 => [1171, 911, 661, 511], 25 => [1273, 997, 715, 535], 26 => [1367, 1059, 751, 593], 27 => [1465, 1125, 805, 625], 28 => [1528, 1190, 868, 658], 29 => [1628, 1264, 908, 698], 30 => [1732, 1370, 982, 742], 31 => [1840, 1452, 1030, 790], 32 => [1952, 1538, 1112, 842], 33 => [2068, 1628, 1168, 898], 34 => [2188, 1722, 1228, 958], 35 => [2303, 1809, 1283, 983], 36 => [2431, 1911, 1351, 1051], 37 => [2563, 1989, 1423, 1093], 38 => [2699, 2099, 1499, 1139], 39 => [2809, 2213, 1579, 1219], 40 => [2953, 2331, 1663, 1273] }.sort LEVELS = { :l => 0, :m => 1, :q => 2, :h => 3 } attr_reader :data attr_writer :level, :size def initialize(data, options={}) self.data = data + @level, @size = nil options.each{|k,v| send("#{k}=", v) } raise(ArgumentError, "data too large") unless size end def data=(data) @data = data end def encoding rqrcode.modules.map{|r| r.inject(''){|s,m| s << (m ? '1' : '0') } } end #Error correction level #Can be one of [:l, :m, :q, :h] (7%, 15%, 25%, 30%) def level @level || :l end def size #@size is only used for manual override, if it's not set #manually the size is always dynamic, calculated from the #length of the data return @size if @size level_index = LEVELS[level] length = data.length found_size = nil SIZES.each do |size,max_values| if max_values[level_index] >= length found_size = size break end end found_size end def to_s data[0,20] end private #Generate an RQRCode object with the available values def rqrcode RQRCode::QRCode.new(data, :level => level, :size => size) end end end
toretore/barby
da8b0e781e31592c8f29a6828cefd95f4882f8a8
:warning: shadowing outer local variable - d
diff --git a/lib/barby/barcode/code_25_interleaved.rb b/lib/barby/barcode/code_25_interleaved.rb index b608bda..de0f15b 100644 --- a/lib/barby/barcode/code_25_interleaved.rb +++ b/lib/barby/barcode/code_25_interleaved.rb @@ -1,73 +1,73 @@ require 'barby/barcode/code_25' module Barby #Code 2 of 5 interleaved. Same as standard 2 of 5, but spaces are used #for encoding as well as the bars. Each pair of numbers get interleaved, #that is, the first is encoded in the bars and the second is encoded #in the spaced. This means an interleaved 2/5 barcode must have an even #number of digits. class Code25Interleaved < Code25 START_ENCODING = [N,N,N,N] STOP_ENCODING = [W,N,N] def digit_pairs(d=nil) - (d || digits).inject [] do |ary,d| + (d || digits).inject [] do |ary,i| ary << [] if !ary.last || ary.last.size == 2 - ary.last << d + ary.last << i ary end end def digit_pairs_with_checksum digit_pairs(digits_with_checksum) end def digit_encodings raise_invalid unless valid? digit_pairs.map{|p| encoding_for_pair(p) } end def digit_encodings_with_checksum digit_pairs_with_checksum.map{|p| encoding_for_pair(p) } end def encoding_for_pair(pair) bars, spaces = ENCODINGS[pair.first], ENCODINGS[pair.last] encoding_for_interleaved(bars.zip(spaces)) end #Encodes an array of interleaved W or N bars and spaces #ex: [W,N,W,W,N,N] => "111011100010" def encoding_for_interleaved(*bars_and_spaces) bar = false#starts with bar bars_and_spaces.flatten.inject '' do |enc,bar_or_space| bar = !bar enc << (bar ? '1' : '0') * (bar_or_space == WIDE ? wide_width : narrow_width) end end def start_encoding encoding_for_interleaved(START_ENCODING) end def stop_encoding encoding_for_interleaved(STOP_ENCODING) end def valid? # When checksum is included, it's included when determining "evenness" super && digits.size % 2 == (include_checksum? ? 1 : 0) end end end
toretore/barby
8ba0d48628f25041a5b80c5b1e57be11e3e6ad46
:warning: instance variable @narrow_width, @wide_width, @space_width not initialized
diff --git a/lib/barby/barcode/code_25.rb b/lib/barby/barcode/code_25.rb index 2951183..7470357 100644 --- a/lib/barby/barcode/code_25.rb +++ b/lib/barby/barcode/code_25.rb @@ -1,195 +1,196 @@ require 'barby/barcode' module Barby #Standard/Industrial 2 of 5, non-interleaved # #Checksum not included by default, to include it, #set include_checksum = true class Code25 < Barcode1D WIDE = W = true NARROW = N = false START_ENCODING = [W,W,N] STOP_ENCODING = [W,N,W] ENCODINGS = { 0 => [N,N,W,W,N], 1 => [W,N,N,N,W], 2 => [N,W,N,N,W], 3 => [W,W,N,N,N], 4 => [N,N,W,N,W], 5 => [W,N,W,N,N], 6 => [N,W,W,N,N], 7 => [N,N,N,W,W], 8 => [W,N,N,W,N], 9 => [N,W,N,W,N] } attr_accessor :include_checksum attr_writer :narrow_width, :wide_width, :space_width attr_reader :data def initialize(data) self.data = data + @narrow_width, @wide_width, @space_width = nil end def data_encoding digit_encodings.join end def data_encoding_with_checksum digit_encodings_with_checksum.join end def encoding start_encoding+(include_checksum? ? data_encoding_with_checksum : data_encoding)+stop_encoding end def characters data.split(//) end def characters_with_checksum characters.push(checksum.to_s) end def digits characters.map{|c| c.to_i } end def digits_with_checksum digits.push(checksum) end def even_and_odd_digits alternater = false digits.reverse.partition{ alternater = !alternater } end def digit_encodings raise_invalid unless valid? digits.map{|d| encoding_for(d) } end alias character_encodings digit_encodings def digit_encodings_with_checksum raise_invalid unless valid? digits_with_checksum.map{|d| encoding_for(d) } end alias character_encodings_with_checksum digit_encodings_with_checksum #Returns the encoding for a single digit def encoding_for(digit) encoding_for_bars(ENCODINGS[digit]) end #Generate encoding for an array of W,N def encoding_for_bars(*bars) wide, narrow, space = wide_encoding, narrow_encoding, space_encoding bars.flatten.inject '' do |enc,bar| enc + (bar == WIDE ? wide : narrow) + space end end def encoding_for_bars_without_end_space(*a) encoding_for_bars(*a).gsub(/0+$/, '') end #Mod10 def checksum evens, odds = even_and_odd_digits sum = odds.inject(0){|s,d| s + d } + evens.inject(0){|s,d| s + (d*3) } sum %= 10 sum.zero? ? 0 : 10-sum end def checksum_encoding encoding_for(checksum) end #The width of a narrow bar in xdims def narrow_width @narrow_width || 1 end #The width of a wide bar in xdims #By default three times as wide as a narrow bar def wide_width @wide_width || narrow_width*3 end #The width of the space between the bars in xdims #By default the same width as a narrow bar # #A space serves only as a separator for the bars, #there is no encoded meaning in them def space_width @space_width || narrow_width end #2 of 5 doesn't require a checksum, but you can include a Mod10 checksum #by setting +include_checksum+ to true def include_checksum? include_checksum end def data=(data) @data = "#{data}" end def start_encoding encoding_for_bars(START_ENCODING) end def stop_encoding encoding_for_bars_without_end_space(STOP_ENCODING) end def narrow_encoding '1' * narrow_width end def wide_encoding '1' * wide_width end def space_encoding '0' * space_width end def valid? data =~ /^[0-9]*$/ end def to_s (include_checksum? ? characters_with_checksum : characters).join end private def raise_invalid raise ArgumentError, "data not valid" end end end
toretore/barby
ac5e7c08e48dd0efca2d8b59cc545ef0d8880378
:warning: method redefined; discarding old data=
diff --git a/lib/barby/barcode/code_25.rb b/lib/barby/barcode/code_25.rb index bf72957..2951183 100644 --- a/lib/barby/barcode/code_25.rb +++ b/lib/barby/barcode/code_25.rb @@ -1,194 +1,195 @@ require 'barby/barcode' module Barby #Standard/Industrial 2 of 5, non-interleaved # #Checksum not included by default, to include it, #set include_checksum = true class Code25 < Barcode1D WIDE = W = true NARROW = N = false START_ENCODING = [W,W,N] STOP_ENCODING = [W,N,W] ENCODINGS = { 0 => [N,N,W,W,N], 1 => [W,N,N,N,W], 2 => [N,W,N,N,W], 3 => [W,W,N,N,N], 4 => [N,N,W,N,W], 5 => [W,N,W,N,N], 6 => [N,W,W,N,N], 7 => [N,N,N,W,W], 8 => [W,N,N,W,N], 9 => [N,W,N,W,N] } - attr_accessor :data, :include_checksum + attr_accessor :include_checksum attr_writer :narrow_width, :wide_width, :space_width + attr_reader :data def initialize(data) self.data = data end def data_encoding digit_encodings.join end def data_encoding_with_checksum digit_encodings_with_checksum.join end def encoding start_encoding+(include_checksum? ? data_encoding_with_checksum : data_encoding)+stop_encoding end def characters data.split(//) end def characters_with_checksum characters.push(checksum.to_s) end def digits characters.map{|c| c.to_i } end def digits_with_checksum digits.push(checksum) end def even_and_odd_digits alternater = false digits.reverse.partition{ alternater = !alternater } end def digit_encodings raise_invalid unless valid? digits.map{|d| encoding_for(d) } end alias character_encodings digit_encodings def digit_encodings_with_checksum raise_invalid unless valid? digits_with_checksum.map{|d| encoding_for(d) } end alias character_encodings_with_checksum digit_encodings_with_checksum #Returns the encoding for a single digit def encoding_for(digit) encoding_for_bars(ENCODINGS[digit]) end #Generate encoding for an array of W,N def encoding_for_bars(*bars) wide, narrow, space = wide_encoding, narrow_encoding, space_encoding bars.flatten.inject '' do |enc,bar| enc + (bar == WIDE ? wide : narrow) + space end end def encoding_for_bars_without_end_space(*a) encoding_for_bars(*a).gsub(/0+$/, '') end #Mod10 def checksum evens, odds = even_and_odd_digits sum = odds.inject(0){|s,d| s + d } + evens.inject(0){|s,d| s + (d*3) } sum %= 10 sum.zero? ? 0 : 10-sum end def checksum_encoding encoding_for(checksum) end #The width of a narrow bar in xdims def narrow_width @narrow_width || 1 end #The width of a wide bar in xdims #By default three times as wide as a narrow bar def wide_width @wide_width || narrow_width*3 end #The width of the space between the bars in xdims #By default the same width as a narrow bar # #A space serves only as a separator for the bars, #there is no encoded meaning in them def space_width @space_width || narrow_width end #2 of 5 doesn't require a checksum, but you can include a Mod10 checksum #by setting +include_checksum+ to true def include_checksum? include_checksum end def data=(data) @data = "#{data}" end def start_encoding encoding_for_bars(START_ENCODING) end def stop_encoding encoding_for_bars_without_end_space(STOP_ENCODING) end def narrow_encoding '1' * narrow_width end def wide_encoding '1' * wide_width end def space_encoding '0' * space_width end def valid? data =~ /^[0-9]*$/ end def to_s (include_checksum? ? characters_with_checksum : characters).join end private def raise_invalid raise ArgumentError, "data not valid" end end end
toretore/barby
790268ea4b3b1d45590df3c8fa97fe2ff5fefba1
:warning: method redefined; discarding old narrow_width, wide_width, space_width
diff --git a/lib/barby/barcode/code_25.rb b/lib/barby/barcode/code_25.rb index 630ba0d..bf72957 100644 --- a/lib/barby/barcode/code_25.rb +++ b/lib/barby/barcode/code_25.rb @@ -1,193 +1,194 @@ require 'barby/barcode' module Barby #Standard/Industrial 2 of 5, non-interleaved # #Checksum not included by default, to include it, #set include_checksum = true class Code25 < Barcode1D WIDE = W = true NARROW = N = false START_ENCODING = [W,W,N] STOP_ENCODING = [W,N,W] ENCODINGS = { 0 => [N,N,W,W,N], 1 => [W,N,N,N,W], 2 => [N,W,N,N,W], 3 => [W,W,N,N,N], 4 => [N,N,W,N,W], 5 => [W,N,W,N,N], 6 => [N,W,W,N,N], 7 => [N,N,N,W,W], 8 => [W,N,N,W,N], 9 => [N,W,N,W,N] } - attr_accessor :data, :narrow_width, :wide_width, :space_width, :include_checksum + attr_accessor :data, :include_checksum + attr_writer :narrow_width, :wide_width, :space_width def initialize(data) self.data = data end def data_encoding digit_encodings.join end def data_encoding_with_checksum digit_encodings_with_checksum.join end def encoding start_encoding+(include_checksum? ? data_encoding_with_checksum : data_encoding)+stop_encoding end def characters data.split(//) end def characters_with_checksum characters.push(checksum.to_s) end def digits characters.map{|c| c.to_i } end def digits_with_checksum digits.push(checksum) end def even_and_odd_digits alternater = false digits.reverse.partition{ alternater = !alternater } end def digit_encodings raise_invalid unless valid? digits.map{|d| encoding_for(d) } end alias character_encodings digit_encodings def digit_encodings_with_checksum raise_invalid unless valid? digits_with_checksum.map{|d| encoding_for(d) } end alias character_encodings_with_checksum digit_encodings_with_checksum #Returns the encoding for a single digit def encoding_for(digit) encoding_for_bars(ENCODINGS[digit]) end #Generate encoding for an array of W,N def encoding_for_bars(*bars) wide, narrow, space = wide_encoding, narrow_encoding, space_encoding bars.flatten.inject '' do |enc,bar| enc + (bar == WIDE ? wide : narrow) + space end end def encoding_for_bars_without_end_space(*a) encoding_for_bars(*a).gsub(/0+$/, '') end #Mod10 def checksum evens, odds = even_and_odd_digits sum = odds.inject(0){|s,d| s + d } + evens.inject(0){|s,d| s + (d*3) } sum %= 10 sum.zero? ? 0 : 10-sum end def checksum_encoding encoding_for(checksum) end #The width of a narrow bar in xdims def narrow_width @narrow_width || 1 end #The width of a wide bar in xdims #By default three times as wide as a narrow bar def wide_width @wide_width || narrow_width*3 end #The width of the space between the bars in xdims #By default the same width as a narrow bar # #A space serves only as a separator for the bars, #there is no encoded meaning in them def space_width @space_width || narrow_width end #2 of 5 doesn't require a checksum, but you can include a Mod10 checksum #by setting +include_checksum+ to true def include_checksum? include_checksum end def data=(data) @data = "#{data}" end def start_encoding encoding_for_bars(START_ENCODING) end def stop_encoding encoding_for_bars_without_end_space(STOP_ENCODING) end def narrow_encoding '1' * narrow_width end def wide_encoding '1' * wide_width end def space_encoding '0' * space_width end def valid? data =~ /^[0-9]*$/ end def to_s (include_checksum? ? characters_with_checksum : characters).join end private def raise_invalid raise ArgumentError, "data not valid" end end end
toretore/barby
9b1dceb04991740e8cde7d4e0210b4848b041650
:warning: shadowing outer local variable - sum
diff --git a/lib/barby/barcode/code_25.rb b/lib/barby/barcode/code_25.rb index 56185fe..630ba0d 100644 --- a/lib/barby/barcode/code_25.rb +++ b/lib/barby/barcode/code_25.rb @@ -1,193 +1,193 @@ require 'barby/barcode' module Barby #Standard/Industrial 2 of 5, non-interleaved # #Checksum not included by default, to include it, #set include_checksum = true class Code25 < Barcode1D WIDE = W = true NARROW = N = false START_ENCODING = [W,W,N] STOP_ENCODING = [W,N,W] ENCODINGS = { 0 => [N,N,W,W,N], 1 => [W,N,N,N,W], 2 => [N,W,N,N,W], 3 => [W,W,N,N,N], 4 => [N,N,W,N,W], 5 => [W,N,W,N,N], 6 => [N,W,W,N,N], 7 => [N,N,N,W,W], 8 => [W,N,N,W,N], 9 => [N,W,N,W,N] } attr_accessor :data, :narrow_width, :wide_width, :space_width, :include_checksum def initialize(data) self.data = data end def data_encoding digit_encodings.join end def data_encoding_with_checksum digit_encodings_with_checksum.join end def encoding start_encoding+(include_checksum? ? data_encoding_with_checksum : data_encoding)+stop_encoding end def characters data.split(//) end def characters_with_checksum characters.push(checksum.to_s) end def digits characters.map{|c| c.to_i } end def digits_with_checksum digits.push(checksum) end def even_and_odd_digits alternater = false digits.reverse.partition{ alternater = !alternater } end def digit_encodings raise_invalid unless valid? digits.map{|d| encoding_for(d) } end alias character_encodings digit_encodings def digit_encodings_with_checksum raise_invalid unless valid? digits_with_checksum.map{|d| encoding_for(d) } end alias character_encodings_with_checksum digit_encodings_with_checksum #Returns the encoding for a single digit def encoding_for(digit) encoding_for_bars(ENCODINGS[digit]) end #Generate encoding for an array of W,N def encoding_for_bars(*bars) wide, narrow, space = wide_encoding, narrow_encoding, space_encoding bars.flatten.inject '' do |enc,bar| enc + (bar == WIDE ? wide : narrow) + space end end def encoding_for_bars_without_end_space(*a) encoding_for_bars(*a).gsub(/0+$/, '') end #Mod10 def checksum evens, odds = even_and_odd_digits - sum = odds.inject(0){|sum,d| sum + d } + evens.inject(0){|sum,d| sum + (d*3) } + sum = odds.inject(0){|s,d| s + d } + evens.inject(0){|s,d| s + (d*3) } sum %= 10 sum.zero? ? 0 : 10-sum end def checksum_encoding encoding_for(checksum) end #The width of a narrow bar in xdims def narrow_width @narrow_width || 1 end #The width of a wide bar in xdims #By default three times as wide as a narrow bar def wide_width @wide_width || narrow_width*3 end #The width of the space between the bars in xdims #By default the same width as a narrow bar # #A space serves only as a separator for the bars, #there is no encoded meaning in them def space_width @space_width || narrow_width end #2 of 5 doesn't require a checksum, but you can include a Mod10 checksum #by setting +include_checksum+ to true def include_checksum? include_checksum end def data=(data) @data = "#{data}" end def start_encoding encoding_for_bars(START_ENCODING) end def stop_encoding encoding_for_bars_without_end_space(STOP_ENCODING) end def narrow_encoding '1' * narrow_width end def wide_encoding '1' * wide_width end def space_encoding '0' * space_width end def valid? data =~ /^[0-9]*$/ end def to_s (include_checksum? ? characters_with_checksum : characters).join end private def raise_invalid raise ArgumentError, "data not valid" end end end
toretore/barby
45d534e1cc8d758672aee14c7577df8bff727212
:warning: assigned but unused variable - klass
diff --git a/lib/barby/barcode/bookland.rb b/lib/barby/barcode/bookland.rb index 6d34bec..8263777 100644 --- a/lib/barby/barcode/bookland.rb +++ b/lib/barby/barcode/bookland.rb @@ -1,146 +1,146 @@ #encoding: ASCII require 'barby/barcode/ean_13' module Barby # Bookland barcodes are EAN-13 barcodes with number system # 978/979 (hence "Bookland"). The data they encode is an ISBN # with its check digit removed. This is a convenience class # that takes an ISBN number instead of "pure" EAN-13 data. # # #These are all the same: # barcode = Bookland.new('978-0-306-40615-7') # barcode = Bookland.new('978-0-306-40615') # barcode = Bookland.new('0-306-40615-7') # barcode = Bookland.new('0-306-40615') # # If a prefix is not given, a default of 978 is used. class Bookland < EAN13 # isbn should be an ISBN number string, with or without an EAN prefix and an ISBN checksum # non-number formatting like hyphens or spaces are ignored # # If a prefix is not given, a default of 978 is used. def initialize(isbn) self.isbn = isbn raise ArgumentError, 'data not valid' unless valid? end def data isbn.isbn end def isbn=(isbn) @isbn = ISBN.new(isbn) end #An instance of ISBN def isbn @isbn end # Encapsulates an ISBN number # # isbn = ISBN.new('978-0-306-40615') class ISBN DEFAULT_PREFIX = '978' PATTERN = /\A(?<prefix>\d\d\d)?(?<number>\d{9})(?<checksum>\d)?\Z/ attr_reader :number # Takes one argument, which is the ISBN string with or without prefix and/or check digit. # Non-digit characters like hyphens and spaces are ignored. # # Prefix is 978 if not given. def initialize(isbn) self.isbn = isbn end def isbn=(isbn) if match = PATTERN.match(isbn.gsub(/\D/, '')) @number = match[:number] @prefix = match[:prefix] else raise ArgumentError, "Not a valid ISBN: #{isbn}" end end def isbn "#{prefix}#{number}" end def isbn_with_checksum "#{isbn}#{checksum}" end def isbn_10 number end def isbn_10_with_checksum "#{number}#{checksum}" end def formatted_isbn "#{prefix}-#{number}-#{checksum}" end def formatted_isbn_10 "#{number}-#{checksum}" end def prefix @prefix || DEFAULT_PREFIX end def digits (prefix+number).split('').map(&:to_i) end def isbn_10_digits number.split('').map(&:to_i) end # Calculates the ISBN 13-digit checksum following the algorithm from: # http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-13_check_digit_calculation def checksum (10 - (digits.each_with_index.inject(0) do |sum, (digit, index)| sum + (digit * (index.even? ? 1 : 3)) end % 10)) % 10 end ISBN_10_CHECKSUM_MULTIPLIERS = [10,9,8,7,6,5,4,3,2] # Calculates the ISBN 10-digit checksum following the algorithm from: # http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digit_calculation def isbn_10_checksum isbn_10_digits.zip(ISBN_10_CHECKSUM_MULTIPLIERS).inject(0) do |sum, (digit, multiplier)| sum + (digit * multiplier) end end def to_s isbn_with_checksum end def inspect klass = (self.class.ancestors + [self.class.name]).join(':') - "#<#{self.class}:0x#{'%014x' % object_id} #{formatted_isbn}>" + "#<#{klass}:0x#{'%014x' % object_id} #{formatted_isbn}>" end end#class ISBN end#class Bookland end#module Barby
toretore/barby
8d74dadba525624559c4a2d958a182d7384b185d
:warning: assigned but unused variable - sum
diff --git a/lib/barby/barcode/ean_13.rb b/lib/barby/barcode/ean_13.rb index f889926..d845cd8 100644 --- a/lib/barby/barcode/ean_13.rb +++ b/lib/barby/barcode/ean_13.rb @@ -1,186 +1,186 @@ require 'barby/barcode' module Barby #EAN-13, aka UPC-A, barcodes are the ones you can see at your local #supermarket, in your house and, well, everywhere.. # #To use this for a UPC barcode, just add a 0 to the front class EAN13 < Barcode1D LEFT_ENCODINGS_ODD = { 0 => '0001101', 1 => '0011001', 2 => '0010011', 3 => '0111101', 4 => '0100011', 5 => '0110001', 6 => '0101111', 7 => '0111011', 8 => '0110111', 9 => '0001011' } LEFT_ENCODINGS_EVEN = { 0 => '0100111', 1 => '0110011', 2 => '0011011', 3 => '0100001', 4 => '0011101', 5 => '0111001', 6 => '0000101', 7 => '0010001', 8 => '0001001', 9 => '0010111' } RIGHT_ENCODINGS = { 0 => '1110010', 1 => '1100110', 2 => '1101100', 3 => '1000010', 4 => '1011100', 5 => '1001110', 6 => '1010000', 7 => '1000100', 8 => '1001000', 9 => '1110100' } #Describes whether the left-hand encoding should use #LEFT_ENCODINGS_ODD or LEFT_ENCODINGS_EVEN, based on the #first digit in the number system (and the barcode as a whole) LEFT_PARITY_MAPS = { 0 => [:odd, :odd, :odd, :odd, :odd, :odd], #UPC-A 1 => [:odd, :odd, :even, :odd, :even, :even], 2 => [:odd, :odd, :even, :even, :odd, :even], 3 => [:odd, :odd, :even, :even, :even, :odd], 4 => [:odd, :even, :odd, :odd, :even, :even], 5 => [:odd, :even, :even, :odd, :odd, :even], 6 => [:odd, :even, :even, :even, :odd, :odd], 7 => [:odd, :even, :odd, :even, :odd, :even], 8 => [:odd, :even, :odd, :even, :even, :odd], 9 => [:odd, :even, :even, :odd, :even, :odd] } #These are the lines that "stick down" in the graphical representation START = '101' CENTER = '01010' STOP = '101' #EAN-13 barcodes have 12 digits + check digit FORMAT = /^\d{12}$/ attr_accessor :data def initialize(data) self.data = data raise ArgumentError, 'data not valid' unless valid? end def characters data.split(//) end def numbers characters.map{|s| s.to_i } end def odd_and_even_numbers alternater = false numbers.reverse.partition{ alternater = !alternater } end #Numbers that are encoded to the left of the center #The first digit is not included def left_numbers numbers[1,6] end #Numbers that are encoded to the right of the center #The checksum is included here def right_numbers numbers_with_checksum[7,6] end def numbers_with_checksum numbers + [checksum] end def data_with_checksum data + checksum.to_s end def left_encodings left_parity_map.zip(left_numbers).map do |parity,number| parity == :odd ? LEFT_ENCODINGS_ODD[number] : LEFT_ENCODINGS_EVEN[number] end end def right_encodings right_numbers.map{|n| RIGHT_ENCODINGS[n] } end def left_encoding left_encodings.join end def right_encoding right_encodings.join end def encoding start_encoding+left_encoding+center_encoding+right_encoding+stop_encoding end #The parities to use for encoding left-hand numbers def left_parity_map LEFT_PARITY_MAPS[numbers.first] end def weighted_sum odds, evens = odd_and_even_numbers odds.map!{|n| n * 3 } - sum = (odds+evens).inject(0){|s,n| s+n } + (odds+evens).inject(0){|s,n| s+n } end #Mod10 def checksum mod = weighted_sum % 10 mod.zero? ? 0 : 10-mod end def checksum_encoding RIGHT_ENCODINGS[checksum] end def valid? data =~ FORMAT end def to_s data_with_checksum end #Is this a UPC-A barcode? #UPC barcodes are EAN codes that start with 0 def upc? numbers.first.zero? end def start_encoding START end def center_encoding CENTER end def stop_encoding STOP end end class UPCA < EAN13 def data '0' + super end end end
toretore/barby
e9b294fb78e2d29f2315e7fb7685b57bdc08cb11
Add hidden support to Code 39 extended and mention to 128A, B, and C
diff --git a/README.md b/README.md index e237402..2a17429 100644 --- a/README.md +++ b/README.md @@ -1,106 +1,107 @@ # Barby Barby is a Ruby library that generates barcodes in a variety of symbologies. Its functionality is split into _barcode_ and "_outputter_" objects: * [`Barby::Barcode` objects] [symbologies] turn data into a binary representation for a given symbology. * [`Barby::Outputter`] [outputters] then takes this representation and turns it into images, PDF, etc. You can easily add a symbology without having to worry about graphical representation. If it can be represented as the usual 1D or 2D matrix of lines or squares, outputters will do that for you. Likewise, you can easily add an outputter for a format that doesn't have one yet, and it will work with all existing symbologies. For more information, check out [the Barby wiki] [wiki]. ### New require policy Barcode symbologies are no longer required automatically, so you'll have to require the ones you need. If you need EAN-13, `require 'barby/barcode/ean_13'`. Full list of symbologies and filenames below. ## Example ```ruby require 'barby' require 'barby/barcode/code_128' require 'barby/outputter/ascii_outputter' barcode = Barby::Code128B.new('BARBY') puts barcode.to_ascii #Implicitly uses the AsciiOutputter ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## B A R B Y ``` ## Supported symbologies ```ruby require 'barby/barcode/<filename>' ``` | Name | Filename | Dependencies | | ----------------------------------- | --------------------- | ------------- | | Code 25 | `code_25` | ─ | | ├─ Interleaved | `code_25_interleaved` | ─ | | └─ IATA | `code_25_iata` | ─ | | Code 39 | `code_39` | ─ | +| └─ Extended | `code_39` | ─ | | Code 93 | `code_93` | ─ | -| Code 128 | `code_128` | ─ | +| Code 128 (A, B, and C) | `code_128` | ─ | | └─ GS1 128 | `gs1_128` | ─ | | EAN-13 | `ean_13` | ─ | | ├─ Bookland | `bookland` | ─ | | └─ UPC-A | `ean_13` | ─ | | EAN-8 | `ean_8` | ─ | | UPC/EAN supplemental, 2 & 5 digits | `upc_supplemental` | ─ | | QR Code | `qr_code` | `rqrcode` | | DataMatrix (Semacode) | `data_matrix` | `semacode` | | PDF417 | `pdf_417` | JRuby | ## Outputters ```ruby require 'barby/outputter/<filename>_outputter' ``` | filename | dependencies | | ----------- | ------------- | | `ascii` | ─ | | `cairo` | cairo | | `html` | ─ | | `pdfwriter` | ─ | | `png` | chunky_png | | `prawn` | prawn | | `rmagick` | RMagick | | `svg` | ─ | ### Formats supported by outputters * Text (mostly for testing) * PNG, JPEG, GIF * PS, EPS * SVG * PDF * HTML --- For more information, check out [the Barby wiki] [wiki]. [wiki]: https://github.com/toretore/barby/wiki [symbologies]: https://github.com/toretore/barby/wiki/Symbologies [outputters]: https://github.com/toretore/barby/wiki/Outputters
toretore/barby
4ec4b9a8e532dd85a13b17b332fbdcc37a0c2d1b
Make the readme information easier to consume
diff --git a/README b/README deleted file mode 100644 index 0008165..0000000 --- a/README +++ /dev/null @@ -1,93 +0,0 @@ -*** NEW REQUIRE POLICY *** - -Barcode symbologies are no longer requires automatically, so you'll have to -require the ones you need. If you need EAN-13, require 'barby/barcode/ean_13'. -Full list of symbologies and filenames below. - -*** - -For more information, check out the Barby wiki at https://github.com/toretore/barby/wiki - -Barby is a Ruby library that generates barcodes in a variety of symbologies. -Its functionality is split into barcode and "outputter" objects. Barcode -objects turn data into a binary representation for a given symbology. -Outputters then take this representation and turns it into images, PDF, etc. - -You can easily add a symbology without having to worry about graphical -representation. If it can be represented as the usual 1D or 2D matrix of -lines or squares, outputters will do that for you. - -Likewise, you can easily add an outputter for a format that doesn't have one -yet, and it will work with all existing symbologies. - -See Barby::Barcode and Barby::Outputter for more information. - - require 'barby' - require 'barby/barcode/code_128' - require 'barby/outputter/ascii_outputter' - - barcode = Barby::Code128B.new('BARBY') - - puts barcode.to_ascii #Implicitly uses the AsciiOutputter - - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## - B A R B Y - - -Supported symbologies: - -Name - filename - dependencies - -require 'barby/barcode/<filename>' - -* Code 25 - code_25 - * Interleaved - code_25_interleaved - * IATA - code_25_iata -* Code 39 - code_39 -* Code 93 - code_93 -* Code 128 - code_128 - * GS1 128 - gs1_128 -* EAN-13 - ean_13 - * Bookland - bookland - * UPC-A - ean_13 -* EAN-8 - ean_8 -* UPC/EAN supplemental, 2 & 5 digits - upc_supplemental - -* QR Code - qr_code - rqrcode -* DataMatrix (Semacode) - data_matrix - semacode -* PDF417 - pdf_417 - java (JRuby) - - -Formats supported by outputters: - -* Text (mostly for testing) -* PNG, JPEG, GIF -* PS, EPS -* SVG -* PDF -* HTML - - -Outputters: - -filename (dependencies) - -require 'barby/outputter/<filename>_outputter' - -* ascii -* cairo (cairo) -* html -* pdfwriter -* png (chunky_png) -* prawn (prawn) -* rmagick (RMagick) -* svg diff --git a/README.md b/README.md new file mode 100644 index 0000000..e237402 --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# Barby +Barby is a Ruby library that generates barcodes in a variety of symbologies. + +Its functionality is split into _barcode_ and "_outputter_" objects: + * [`Barby::Barcode` objects] [symbologies] turn data into a binary representation for a given symbology. + * [`Barby::Outputter`] [outputters] then takes this representation and turns it into images, PDF, etc. + +You can easily add a symbology without having to worry about graphical +representation. If it can be represented as the usual 1D or 2D matrix of +lines or squares, outputters will do that for you. + +Likewise, you can easily add an outputter for a format that doesn't have one +yet, and it will work with all existing symbologies. + +For more information, check out [the Barby wiki] [wiki]. + +### New require policy + +Barcode symbologies are no longer required automatically, so you'll have to +require the ones you need. + +If you need EAN-13, `require 'barby/barcode/ean_13'`. Full list of symbologies and filenames below. + +## Example + +```ruby +require 'barby' +require 'barby/barcode/code_128' +require 'barby/outputter/ascii_outputter' + +barcode = Barby::Code128B.new('BARBY') + +puts barcode.to_ascii #Implicitly uses the AsciiOutputter + +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## +## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## + B A R B Y +``` + +## Supported symbologies + +```ruby +require 'barby/barcode/<filename>' +``` + +| Name | Filename | Dependencies | +| ----------------------------------- | --------------------- | ------------- | +| Code 25 | `code_25` | ─ | +| ├─ Interleaved | `code_25_interleaved` | ─ | +| └─ IATA | `code_25_iata` | ─ | +| Code 39 | `code_39` | ─ | +| Code 93 | `code_93` | ─ | +| Code 128 | `code_128` | ─ | +| └─ GS1 128 | `gs1_128` | ─ | +| EAN-13 | `ean_13` | ─ | +| ├─ Bookland | `bookland` | ─ | +| └─ UPC-A | `ean_13` | ─ | +| EAN-8 | `ean_8` | ─ | +| UPC/EAN supplemental, 2 & 5 digits | `upc_supplemental` | ─ | +| QR Code | `qr_code` | `rqrcode` | +| DataMatrix (Semacode) | `data_matrix` | `semacode` | +| PDF417 | `pdf_417` | JRuby | + + +## Outputters + +```ruby +require 'barby/outputter/<filename>_outputter' +``` + +| filename | dependencies | +| ----------- | ------------- | +| `ascii` | ─ | +| `cairo` | cairo | +| `html` | ─ | +| `pdfwriter` | ─ | +| `png` | chunky_png | +| `prawn` | prawn | +| `rmagick` | RMagick | +| `svg` | ─ | + +### Formats supported by outputters + +* Text (mostly for testing) +* PNG, JPEG, GIF +* PS, EPS +* SVG +* PDF +* HTML + +--- + +For more information, check out [the Barby wiki] [wiki]. + + + [wiki]: https://github.com/toretore/barby/wiki + [symbologies]: https://github.com/toretore/barby/wiki/Symbologies + [outputters]: https://github.com/toretore/barby/wiki/Outputters
toretore/barby
e06bf06da6f7edafd0af10854085d66436ab7e3a
Allow setting prefix for Bookland
diff --git a/lib/barby/barcode/bookland.rb b/lib/barby/barcode/bookland.rb index 4362ce2..6d34bec 100644 --- a/lib/barby/barcode/bookland.rb +++ b/lib/barby/barcode/bookland.rb @@ -1,38 +1,146 @@ #encoding: ASCII require 'barby/barcode/ean_13' module Barby - #Bookland barcodes are EAN-13 barcodes with number system - #978 (hence "Bookland"). The data they encode is an ISBN - #with its check digit removed. This is a convenience class - #that takes an ISBN no instead of "pure" EAN-13 data. + # Bookland barcodes are EAN-13 barcodes with number system + # 978/979 (hence "Bookland"). The data they encode is an ISBN + # with its check digit removed. This is a convenience class + # that takes an ISBN number instead of "pure" EAN-13 data. + # + # #These are all the same: + # barcode = Bookland.new('978-0-306-40615-7') + # barcode = Bookland.new('978-0-306-40615') + # barcode = Bookland.new('0-306-40615-7') + # barcode = Bookland.new('0-306-40615') + # + # If a prefix is not given, a default of 978 is used. class Bookland < EAN13 - BOOKLAND_NUMBER_SYSTEM = '978' - - attr_accessor :isbn - + # isbn should be an ISBN number string, with or without an EAN prefix and an ISBN checksum + # non-number formatting like hyphens or spaces are ignored + # + # If a prefix is not given, a default of 978 is used. def initialize(isbn) self.isbn = isbn raise ArgumentError, 'data not valid' unless valid? end def data - BOOKLAND_NUMBER_SYSTEM+isbn_only + isbn.isbn end - #Removes any non-digit characters, number system and check digit - #from ISBN, so "978-82-92526-14-9" would result in "829252614" - def isbn_only - s = isbn.gsub(/[^0-9]/, '') - if s.size > 10#Includes number system - s[3,9] - else#No number system, may include check digit - s[0,9] - end + def isbn=(isbn) + @isbn = ISBN.new(isbn) end - end + #An instance of ISBN + def isbn + @isbn + end + + + # Encapsulates an ISBN number + # + # isbn = ISBN.new('978-0-306-40615') + class ISBN + + DEFAULT_PREFIX = '978' + PATTERN = /\A(?<prefix>\d\d\d)?(?<number>\d{9})(?<checksum>\d)?\Z/ + + attr_reader :number + + + # Takes one argument, which is the ISBN string with or without prefix and/or check digit. + # Non-digit characters like hyphens and spaces are ignored. + # + # Prefix is 978 if not given. + def initialize(isbn) + self.isbn = isbn + end + + + def isbn=(isbn) + if match = PATTERN.match(isbn.gsub(/\D/, '')) + @number = match[:number] + @prefix = match[:prefix] + else + raise ArgumentError, "Not a valid ISBN: #{isbn}" + end + end + + def isbn + "#{prefix}#{number}" + end + + def isbn_with_checksum + "#{isbn}#{checksum}" + end + + def isbn_10 + number + end + + def isbn_10_with_checksum + "#{number}#{checksum}" + end + + def formatted_isbn + "#{prefix}-#{number}-#{checksum}" + end + + def formatted_isbn_10 + "#{number}-#{checksum}" + end + + + def prefix + @prefix || DEFAULT_PREFIX + end + + def digits + (prefix+number).split('').map(&:to_i) + end + + def isbn_10_digits + number.split('').map(&:to_i) + end + + + # Calculates the ISBN 13-digit checksum following the algorithm from: + # http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-13_check_digit_calculation + def checksum + (10 - (digits.each_with_index.inject(0) do |sum, (digit, index)| + sum + (digit * (index.even? ? 1 : 3)) + end % 10)) % 10 + end + + + ISBN_10_CHECKSUM_MULTIPLIERS = [10,9,8,7,6,5,4,3,2] + + # Calculates the ISBN 10-digit checksum following the algorithm from: + # http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digit_calculation + def isbn_10_checksum + isbn_10_digits.zip(ISBN_10_CHECKSUM_MULTIPLIERS).inject(0) do |sum, (digit, multiplier)| + sum + (digit * multiplier) + end + end + + + def to_s + isbn_with_checksum + end + + def inspect + klass = (self.class.ancestors + [self.class.name]).join(':') + "#<#{self.class}:0x#{'%014x' % object_id} #{formatted_isbn}>" + end + + + end#class ISBN + + + end#class Bookland + -end +end#module Barby diff --git a/test/bookland_test.rb b/test/bookland_test.rb index 5e9b82d..e88766a 100644 --- a/test/bookland_test.rb +++ b/test/bookland_test.rb @@ -1,58 +1,54 @@ require 'test_helper' require 'barby/barcode/bookland' class BooklandTest < Barby::TestCase - + before do - @isbn = '968-26-1240-3' + # Gr Publ Tit Checksum + @isbn = '96-8261-240-3' @code = Bookland.new(@isbn) end - it "should not touch the ISBN" do - @code.isbn.must_equal @isbn - end - - it "should have an isbn_only" do - @code.isbn_only.must_equal '968261240' - end - it "should have the expected data" do @code.data.must_equal '978968261240' end it "should have the expected numbers" do @code.numbers.must_equal [9,7,8,9,6,8,2,6,1,2,4,0] end it "should have the expected checksum" do @code.checksum.must_equal 4 end it "should raise an error when data not valid" do lambda{ Bookland.new('1234') }.must_raise ArgumentError end - + describe 'ISBN conversion' do it "should accept ISBN with number system and check digit" do code = Bookland.new('978-82-92526-14-9') assert code.valid? code.data.must_equal '978829252614' + code = Bookland.new('979-82-92526-14-9') + assert code.valid? + code.data.must_equal '979829252614' end it "should accept ISBN without number system but with check digit" do code = Bookland.new('82-92526-14-9') assert code.valid? - code.data.must_equal '978829252614' + code.data.must_equal '978829252614' #978 is the default prefix end it "should accept ISBN without number system or check digit" do code = Bookland.new('82-92526-14') assert code.valid? code.data.must_equal '978829252614' end end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 28169e2..588b71e 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,23 +1,23 @@ require 'rubygems' require 'barby' -require 'minitest/spec' require 'minitest/autorun' +require 'minitest/spec' module Barby class TestCase < MiniTest::Spec - + include Barby - + private - + # So we can register outputter during an full test suite run. def load_outputter(outputter) - @loaded_outputter ||= load "barby/outputter/#{outputter}_outputter.rb" + @loaded_outputter ||= load "barby/outputter/#{outputter}_outputter.rb" end - + def ruby_19_or_greater? RUBY_VERSION >= '1.9' end - + end end
toretore/barby
b87a021b7c39a2ba008bc853ef541a6c75ada155
Fixes support for 2d barcodes with RmagickOutputter
diff --git a/lib/barby/outputter/rmagick_outputter.rb b/lib/barby/outputter/rmagick_outputter.rb index d402bad..24d1d26 100644 --- a/lib/barby/outputter/rmagick_outputter.rb +++ b/lib/barby/outputter/rmagick_outputter.rb @@ -1,126 +1,135 @@ require 'barby/outputter' require 'RMagick' module Barby #Renders images from barcodes using RMagick # #Registers the to_png, to_gif, to_jpg and to_image methods class RmagickOutputter < Outputter register :to_png, :to_gif, :to_jpg, :to_image attr_accessor :height, :xdim, :ydim, :margin #Returns a string containing a PNG image def to_png(*a) to_blob('png', *a) end #Returns a string containint a GIF image def to_gif(*a) to_blob('gif', *a) end #Returns a string containing a JPEG image def to_jpg(*a) to_blob('jpg', *a) end def to_blob(format, *a) img = to_image(*a) blob = img.to_blob{|i| i.format = format } #Release the memory used by RMagick explicitly. Ruby's GC #isn't aware of it and can't clean it up automatically img.destroy! if img.respond_to?(:destroy!) blob end #Returns an instance of Magick::Image def to_image(opts={}) with_options opts do canvas = Magick::Image.new(full_width, full_height) bars = Magick::Draw.new - x = margin - y = margin + x1 = margin + y1 = margin if barcode.two_dimensional? encoding.each do |line| line.split(//).map{|c| c == '1' }.each do |bar| if bar - bars.rectangle(x, y, x+(xdim-1), y+(ydim-1)) + x2 = x1+(xdim-1) + y2 = y1+(ydim-1) + # For single pixels use point + if x1 == x2 && y1 == y2 + bars.point(x1,y1) + else + bars.rectangle(x1, y1, x2, y2) + end end - x += xdim + x1 += xdim end - x = margin - y += ydim + x1 = margin + y1 += ydim end else booleans.each do |bar| if bar - bars.rectangle(x, y, x+(xdim-1), y+(height-1)) + x2 = x1+(xdim-1) + y2 = y1+(height-1) + bars.rectangle(x1, y1, x2, y2) end - x += xdim + x1 += xdim end end bars.draw(canvas) canvas end end #The height of the barcode in px #For 2D barcodes this is the number of "lines" * ydim def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end #The width of the barcode in px def width length * xdim end #Number of modules (xdims) on the x axis def length barcode.two_dimensional? ? encoding.first.length : encoding.length end #X dimension. 1X == 1px def xdim @xdim || 1 end #Y dimension. Only for 2D codes def ydim @ydim || xdim end #The margin of each edge surrounding the barcode in pixels def margin @margin || 10 end #The full width of the image. This is the width of the #barcode + the left and right margin def full_width width + (margin * 2) end #The height of the image. This is the height of the #barcode + the top and bottom margin def full_height height + (margin * 2) end end end
toretore/barby
8d48bc6f33011e0e1cf820c7194a7e8b3e422338
Fix HTMLOutputter test
diff --git a/test/outputter/html_outputter_test.rb b/test/outputter/html_outputter_test.rb index f15c41e..65c3bb9 100644 --- a/test/outputter/html_outputter_test.rb +++ b/test/outputter/html_outputter_test.rb @@ -1,68 +1,68 @@ require 'test_helper' require 'barby/barcode/code_128' #require 'barby/outputter/html_outputter' class HtmlOutputterTest < Barby::TestCase class MockCode attr_reader :encoding def initialize(e) @encoding = e end def two_dimensional? encoding.is_a? Array end end before do load_outputter('html') @barcode = Barby::Code128B.new('BARBY') @outputter = HtmlOutputter.new(@barcode) end it "should register to_html" do Barcode.outputters.must_include(:to_html) end it 'should have the expected start HTML' do assert_equal '<table class="barby-barcode"><tbody>', @outputter.start end it 'should be able to set additional class name' do @outputter.class_name = 'humbaba' assert_equal '<table class="barby-barcode humbaba"><tbody>', @outputter.start end it 'should have the expected stop HTML' do assert_equal '</tbody></table>', @outputter.stop end it 'should build the expected cells' do assert_equal ['<td class="barby-cell on"></td>', '<td class="barby-cell off"></td>', '<td class="barby-cell off"></td>', '<td class="barby-cell on"></td>'], @outputter.cells_for([true, false, false, true]) end it 'should build the expected rows' do assert_equal( [ - @outputter.cells_for([true, false]).map{|c| "<tr class=\"barby-row\">#{c}</tr>" }.join, - @outputter.cells_for([false, true]).map{|c| "<tr class=\"barby-row\">#{c}</tr>" }.join + "<tr class=\"barby-row\">#{@outputter.cells_for([true, false]).join}</tr>", + "<tr class=\"barby-row\">#{@outputter.cells_for([false, true]).join}</tr>", ], @outputter.rows_for([[true, false],[false, true]]) ) end it 'should have the expected rows' do barcode = MockCode.new('101100') outputter = HtmlOutputter.new(barcode) assert_equal outputter.rows_for([[true, false, true, true, false, false]]), outputter.rows barcode = MockCode.new(['101', '010']) outputter = HtmlOutputter.new(barcode) assert_equal outputter.rows_for([[true, false, true], [false, true, false]]), outputter.rows end it 'should have the expected html' do assert_equal @outputter.start + @outputter.rows.join + @outputter.stop, @outputter.to_html end end
toretore/barby
c44a5658c1fc4cf1d22ec99c61e77606dd10a76e
Automatic charset for Code 128
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index 7e47d5f..cfe6c25 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,413 +1,570 @@ #encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") class Code128 < Barcode1D + FNC1 = "\xc1" + FNC2 = "\xc2" + FNC3 = "\xc3" + FNC4 = "\xc4" + CODEA = "\xc5" + CODEB = "\xc6" + CODEC = "\xc7" + SHIFT = "\xc8" + STARTA = "\xc9" + STARTB = "\xca" + STARTC = "\xcb" + + STOP = '11000111010' + TERMINATE = '11' + ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", - 96 => "\303", 97 => "\302", 98 => "SHIFT", - 99 => "\307", 100 => "\306", 101 => "\304", - 102 => "\301", 103 => "STARTA", 104 => "STARTB", - 105 => "STARTC" + 96 => FNC3, 97 => FNC2, 98 => SHIFT, + 99 => CODEC, 100 => CODEB, 101 => FNC4, + 102 => FNC1, 103 => STARTA, 104 => STARTB, + 105 => STARTC }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", - 96 => "\303", 97 => "\302", 98 => "SHIFT", 99 => "\307", 100 => "\304", - 101 => "\305", 102 => "\301", 103 => "STARTA", 104 => "STARTB", - 105 => "STARTC", + 96 => FNC3, 97 => FNC2, 98 => SHIFT, 99 => CODEC, 100 => FNC4, + 101 => CODEA, 102 => FNC1, 103 => STARTA, 104 => STARTB, + 105 => STARTC, }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", - 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => "\306", 101 => "\305", - 102 => "\301", 103 => "STARTA", 104 => "STARTB", 105 => "STARTC" + 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => CODEB, 101 => CODEA, + 102 => FNC1, 103 => STARTA, 104 => STARTB, 105 => STARTC }.invert } - FNC1 = "\xc1" - FNC2 = "\xc2" - FNC3 = "\xc3" - FNC4 = "\xc4" - CODEA = "\xc5" - CODEB = "\xc6" - CODEC = "\xc7" - - STOP = '11000111010' - TERMINATE = '11' + CONTROL_CHARACTERS = VALUES['A'].invert.values_at(*(64..95).to_a) attr_reader :type - - def initialize(data, type) - self.type = type - self.data = "#{data}" + + def initialize(data, type=nil) + if type + self.type = type + self.data = "#{data}" + else + self.type, self.data = self.class.determine_best_type_for_data("#{data}") + end raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type.upcase! raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra @extra end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) - case character - when 'A' then Code128A - when 'B' then Code128B - when 'C' then Code128C - when CODEA then Code128A - when CODEB then Code128B - when CODEC then Code128C - end + self.class.class_for(character) end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end + def start_character + case type + when 'A' then STARTA + when 'B' then STARTB + when 'C' then STARTC + end + end + def start_num - values["START#{type}"] + values[start_character] end def start_encoding encodings[start_num] end - end + + CTRL_RE = /#{CONTROL_CHARACTERS.join('|')}/ + LOWR_RE = /[a-z]/ + DGTS_RE = /\d{4,}/ + + class << self + + + def class_for(character) + case character + when 'A' then Code128A + when 'B' then Code128B + when 'C' then Code128C + when CODEA then Code128A + when CODEB then Code128B + when CODEC then Code128C + end + end + + + #Insert code shift and switch characters where appropriate to get the + #shortest encoding possible + def apply_shortest_encoding_for_data(data) + extract_codec(data).map do |block| + if possible_codec_segment?(block) + "#{CODEC}#{block}" + else + if control_before_lowercase?(block) + handle_code_a(block) + else + handle_code_b(block) + end + end + end.join + end + + def determine_best_type_for_data(data) + data = apply_shortest_encoding_for_data(data) + type = case data.slice!(0) + when CODEA then 'A' + when CODEB then 'B' + when CODEC then 'C' + end + [type, data] + end + + + private + + #Extract all CODEC segments from the data. 4 or more evenly numbered contiguous digits. + # + # # C A or B C A or B + # extract_codec("12345abc678910DEF11") => ["1234", "5abc", "678910", "DEF11"] + def extract_codec(data) + segments = data.split(/(\d{4,})/).reject(&:empty?) + segments.each_with_index do |s,i| + if possible_codec_segment?(s) && s.size.odd? + if i == 0 + if segments[1] + segments[1].insert(0, s.slice!(-1)) + else + segments[1] = s.slice!(-1) + end + else + segments[i-1].insert(-1, s.slice!(0)) if segments[i-1] + end + end + end + segments + end + + def possible_codec_segment?(data) + data =~ /\A\d{4,}\Z/ + end + + def control_character?(char) + char =~ CTRL_RE + end + + def lowercase_character?(char) + char =~ LOWR_RE + end + + + #Handle a Code A segment which may contain Code B parts, but may not + #contain any Code C parts. + def handle_code_a(data) + indata = data.dup + outdata = CODEA.dup #We know it'll be A + while char = indata.slice!(0) + if lowercase_character?(char) #Found a lower case character (Code B) + if control_before_lowercase?(indata) + outdata << SHIFT << char #Control character appears before a new lowercase, use shift + else + outdata << handle_code_b(char+indata) #Switch to Code B + break + end + else + outdata << char + end + end#while + + outdata + end + + + #Handle a Code B segment which may contain Code A parts, but may not + #contain any Code C parts. + def handle_code_b(data) + indata = data.dup + outdata = CODEB.dup #We know this is going to start with Code B + while char = indata.slice!(0) + if control_character?(char) #Found a control character (Code A) + if control_before_lowercase?(indata) #There is another control character before any lowercase, so + outdata << handle_code_a(char+indata) #switch over to Code A. + break + else + outdata << SHIFT << char #Can use a shift to only encode this char as Code A + end + else + outdata << char + end + end#while + + outdata + end + + + #Test str to see if a control character (Code A) appears + #before a lower case character (Code B). + # + #Returns true only if it contains a control character and a lower case + #character doesn't appear before it. + def control_before_lowercase?(str) + ctrl = str =~ CTRL_RE + char = str =~ LOWR_RE + + ctrl && (!char || ctrl < char) + end + + + + end#class << self + + + + end#class Code128 class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end diff --git a/test/code_128_test.rb b/test/code_128_test.rb index 802a760..29c6203 100644 --- a/test/code_128_test.rb +++ b/test/code_128_test.rb @@ -1,359 +1,406 @@ # encoding: UTF-8 require 'test_helper' require 'barby/barcode/code_128' class Code128Test < Barby::TestCase + %w[CODEA CODEB CODEC FNC1 FNC2 FNC3 FNC4 SHIFT].each do |const| + const_set const, Code128.const_get(const) + end + before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do @code.send(:stop_encoding).must_equal '1100011101011' end it "should find the right class for a character A, B or C" do @code.send(:class_for, 'A').must_equal Code128A @code.send(:class_for, 'B').must_equal Code128B @code.send(:class_for, 'C').must_equal Code128C end it "should find the right change code for a class" do @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC end it "should not allow empty data" do lambda{ Code128B.new("") }.must_raise(ArgumentError) end - + describe "single encoding" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do @code.data.must_equal @data end it "should be able to change its data" do @code.data = '123ABC' @code.data.must_equal '123ABC' @code.data.wont_equal @data end it "should not have an extra" do assert @code.extra.nil? end it "should have empty extra encoding" do @code.extra_encoding.must_equal '' end it "should have the correct checksum" do @code.checksum.must_equal 66 end it "should return all data for to_s" do @code.to_s.must_equal @data end end describe "multiple encodings" do before do @data = binary_encode("ABC123\306def\3074567") @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do @code.full_data.must_equal "ABC123def4567" end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do @code.full_data_with_change_codes.must_equal @data end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = binary_encode("\3071234") code.full_data.must_equal "ABC1234" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234") code.extra.extra = binary_encode("\306abc") code.full_data.must_equal "ABC1234abc" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc") code.extra.extra.data = binary_encode("abc\305DEF") code.full_data.must_equal "ABC1234abcDEF" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc\305DEF") code.extra.extra.full_data.must_equal "abcDEF" code.extra.extra.full_data_with_change_codes.must_equal binary_encode("abc\305DEF") code.extra.full_data.must_equal "1234abcDEF" code.extra.full_data_with_change_codes.must_equal binary_encode("1234\306abc\305DEF") end it "should have a Code B extra" do @code.extra.must_be_instance_of(Code128B) end it "should have a valid extra" do assert @code.extra.valid? end it "the extra should also have an extra of type C" do @code.extra.extra.must_be_instance_of(Code128C) end it "the extra's extra should be valid" do assert @code.extra.extra.valid? end it "should not have more than two extras" do assert @code.extra.extra.extra.nil? end it "should split extra data from string on data assignment" do @code.data = binary_encode("123\306abc") @code.data.must_equal '123' @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal 'abc' end it "should be be able to change its extra" do @code.extra = binary_encode("\3071234") @code.extra.must_be_instance_of(Code128C) @code.extra.data.must_equal '1234' end it "should split extra data from string on extra assignment" do @code.extra = binary_encode("\306123\3074567") @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal '123' @code.extra.extra.must_be_instance_of(Code128C) @code.extra.extra.data.must_equal '4567' end it "should not fail on newlines in extras" do code = Code128B.new(binary_encode("ABC\305\n")) code.data.must_equal "ABC" code.extra.must_be_instance_of(Code128A) code.extra.data.must_equal "\n" code.extra.extra = binary_encode("\305\n\n\n\n\n\nVALID") code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" end it "should raise an exception when extra string doesn't start with the special code character" do lambda{ @code.extra = '123' }.must_raise ArgumentError end it "should have the correct checksum" do @code.checksum.must_equal 84 end it "should have the expected encoding" do #STARTA A B C 1 2 3 @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ #CODEB d e f '10111101110100001001101011001000010110000100'+ #CODEC 45 67 '101110111101011101100010000101100'+ #CHECK=84 STOP '100111101001100011101011' end it "should return all data including extras, except change codes for to_s" do @code.to_s.must_equal "ABC123def4567" end end - + describe "128A" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = 'abc123' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(A B C 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010000100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10010000110' end end describe "128B" do before do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = binary_encode("abc£123") refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(a b c 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010010000' end it "should have the expected data encoding" do @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '11011101110' end end describe "128C" do before do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = '123' refute @code.valid? @code.data = 'abc' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(12 34 56) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010011100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101100111001000101100011100010110' end it "should have the expected encoding" do @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10001101110' end end describe "Function characters" do it "should retain the special symbols in the data accessor" do Code128A.new(binary_encode("\301ABC\301DEF")).data.must_equal binary_encode("\301ABC\301DEF") Code128B.new(binary_encode("\301ABC\302DEF")).data.must_equal binary_encode("\301ABC\302DEF") Code128C.new(binary_encode("\301123456")).data.must_equal binary_encode("\301123456") Code128C.new(binary_encode("12\30134\30156")).data.must_equal binary_encode("12\30134\30156") end it "should keep the special symbols as characters" do Code128A.new(binary_encode("\301ABC\301DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \301 D E F)) Code128B.new(binary_encode("\301ABC\302DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \302 D E F)) Code128C.new(binary_encode("\301123456")).characters.must_equal binary_encode_array(%W(\301 12 34 56)) Code128C.new(binary_encode("12\30134\30156")).characters.must_equal binary_encode_array(%W(12 \301 34 \301 56)) end it "should not allow FNC > 1 for Code C" do lambda{ Code128C.new("12\302") }.must_raise ArgumentError lambda{ Code128C.new("\30312") }.must_raise ArgumentError lambda{ Code128C.new("12\304") }.must_raise ArgumentError end it "should be included in the encoding" do a = Code128A.new(binary_encode("\301AB")) a.data_encoding.must_equal '111101011101010001100010001011000' a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' end end describe "Code128 with type" do - it "should raise an exception when not given a type" do - lambda{ Code128.new('abc') }.must_raise(ArgumentError) - end + #it "should raise an exception when not given a type" do + # lambda{ Code128.new('abc') }.must_raise(ArgumentError) + #end it "should raise an exception when given a non-existent type" do lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) end it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end end + + describe "Code128 automatic charset" do + + it "should know how to extract CODEC segments properly from a data string" do + Code128.send(:extract_codec, "1234abcd5678\r\n\r\n").must_equal ["1234", "abcd", "5678", "\r\n\r\n"] + Code128.send(:extract_codec, "12345abc6").must_equal ["1234", "5abc6"] + Code128.send(:extract_codec, "abcdef").must_equal ["abcdef"] + Code128.send(:extract_codec, "123abcdef45678").must_equal ["123abcdef4", "5678"] + Code128.send(:extract_codec, "abcd12345").must_equal ["abcd1", "2345"] + Code128.send(:extract_codec, "abcd12345efg").must_equal ["abcd1", "2345", "efg"] + Code128.send(:extract_codec, "12345").must_equal ["1234", "5"] + Code128.send(:extract_codec, "12345abc").must_equal ["1234", "5abc"] + Code128.send(:extract_codec, "abcdef1234567").must_equal ["abcdef1", "234567"] + end + + it "should know how to most efficiently apply different encodings to a data string" do + Code128.apply_shortest_encoding_for_data("123456").must_equal "#{CODEC}123456" + Code128.apply_shortest_encoding_for_data("abcdef").must_equal "#{CODEB}abcdef" + Code128.apply_shortest_encoding_for_data("ABCDEF").must_equal "#{CODEB}ABCDEF" + Code128.apply_shortest_encoding_for_data("\n\t\r").must_equal "#{CODEA}\n\t\r" + Code128.apply_shortest_encoding_for_data("123456abcdef").must_equal "#{CODEC}123456#{CODEB}abcdef" + Code128.apply_shortest_encoding_for_data("abcdef123456").must_equal "#{CODEB}abcdef#{CODEC}123456" + Code128.apply_shortest_encoding_for_data("1234567").must_equal "#{CODEC}123456#{CODEB}7" + Code128.apply_shortest_encoding_for_data("123b456").must_equal "#{CODEB}123b456" + Code128.apply_shortest_encoding_for_data("abc123def45678gh").must_equal "#{CODEB}abc123def4#{CODEC}5678#{CODEB}gh" + Code128.apply_shortest_encoding_for_data("12345AB\nEEasdgr12EE\r\n").must_equal "#{CODEC}1234#{CODEA}5AB\nEE#{CODEB}asdgr12EE#{CODEA}\r\n" + Code128.apply_shortest_encoding_for_data("123456QWERTY\r\n\tAAbbcc12XX34567").must_equal "#{CODEC}123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" + + Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl" + Code128.apply_shortest_encoding_for_data("ABC\rb\nDEF12gHI3456").must_equal "#{CODEA}ABC\r#{SHIFT}b\nDEF12#{CODEB}gHI#{CODEC}3456" + Code128.apply_shortest_encoding_for_data("ABCdef\rGHIjkl\tMNop\nqRs").must_equal "#{CODEB}ABCdef#{SHIFT}\rGHIjkl#{SHIFT}\tMNop#{SHIFT}\nqRs" + end + + it "should apply automatic charset when no charset is given" do + b = Code128.new("123456QWERTY\r\n\tAAbbcc12XX34567") + b.type.must_equal 'C' + b.full_data_with_change_codes.must_equal "123456#{CODEA}QWERTY\r\n\tAA#{CODEB}bbcc12XX3#{CODEC}4567" + end + + end + + + private - + def binary_encode_array(datas) datas.each { |data| binary_encode(data) } end - + def binary_encode(data) ruby_19_or_greater? ? data.force_encoding('BINARY') : data end - + end
toretore/barby
b4b37fb6536ea5de1052cb2fafdd359afcde010d
Fix some encoding issues
diff --git a/lib/barby/barcode/bookland.rb b/lib/barby/barcode/bookland.rb index af461d8..4362ce2 100644 --- a/lib/barby/barcode/bookland.rb +++ b/lib/barby/barcode/bookland.rb @@ -1,37 +1,38 @@ +#encoding: ASCII require 'barby/barcode/ean_13' module Barby #Bookland barcodes are EAN-13 barcodes with number system #978 (hence "Bookland"). The data they encode is an ISBN #with its check digit removed. This is a convenience class #that takes an ISBN no instead of "pure" EAN-13 data. class Bookland < EAN13 BOOKLAND_NUMBER_SYSTEM = '978' attr_accessor :isbn def initialize(isbn) self.isbn = isbn raise ArgumentError, 'data not valid' unless valid? end def data BOOKLAND_NUMBER_SYSTEM+isbn_only end #Removes any non-digit characters, number system and check digit #from ISBN, so "978-82-92526-14-9" would result in "829252614" def isbn_only s = isbn.gsub(/[^0-9]/, '') if s.size > 10#Includes number system s[3,9] else#No number system, may include check digit s[0,9] end end end end diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index 75d23fd..7e47d5f 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,412 +1,413 @@ +#encoding: ASCII require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") class Code128 < Barcode1D ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => "\303", 97 => "\302", 98 => "SHIFT", 99 => "\307", 100 => "\306", 101 => "\304", 102 => "\301", 103 => "STARTA", 104 => "STARTB", 105 => "STARTC" }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => "\303", 97 => "\302", 98 => "SHIFT", 99 => "\307", 100 => "\304", 101 => "\305", 102 => "\301", 103 => "STARTA", 104 => "STARTB", 105 => "STARTC", }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => "\306", 101 => "\305", 102 => "\301", 103 => "STARTA", 104 => "STARTB", 105 => "STARTC" }.invert } FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" STOP = '11000111010' TERMINATE = '11' attr_reader :type def initialize(data, type) self.type = type self.data = "#{data}" raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type.upcase! raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra @extra end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_num values["START#{type}"] end def start_encoding encodings[start_num] end end class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end diff --git a/lib/barby/barcode/code_39.rb b/lib/barby/barcode/code_39.rb index 5758533..23e6a8b 100644 --- a/lib/barby/barcode/code_39.rb +++ b/lib/barby/barcode/code_39.rb @@ -1,234 +1,235 @@ +#encoding: ASCII require 'barby/barcode' module Barby class Code39 < Barcode1D WIDE = W = true NARROW = N = false ENCODINGS = { ' ' => [N,W,W,N,N,N,W,N,N], '$' => [N,W,N,W,N,W,N,N,N], '%' => [N,N,N,W,N,W,N,W,N], '+' => [N,W,N,N,N,W,N,W,N], '-' => [N,W,N,N,N,N,W,N,W], '.' => [W,W,N,N,N,N,W,N,N], '/' => [N,W,N,W,N,N,N,W,N], '0' => [N,N,N,W,W,N,W,N,N], '1' => [W,N,N,W,N,N,N,N,W], '2' => [N,N,W,W,N,N,N,N,W], '3' => [W,N,W,W,N,N,N,N,N], '4' => [N,N,N,W,W,N,N,N,W], '5' => [W,N,N,W,W,N,N,N,N], '6' => [N,N,W,W,W,N,N,N,N], '7' => [N,N,N,W,N,N,W,N,W], '8' => [W,N,N,W,N,N,W,N,N], '9' => [N,N,W,W,N,N,W,N,N], 'A' => [W,N,N,N,N,W,N,N,W], 'B' => [N,N,W,N,N,W,N,N,W], 'C' => [W,N,W,N,N,W,N,N,N], 'D' => [N,N,N,N,W,W,N,N,W], 'E' => [W,N,N,N,W,W,N,N,N], 'F' => [N,N,W,N,W,W,N,N,N], 'G' => [N,N,N,N,N,W,W,N,W], 'H' => [W,N,N,N,N,W,W,N,N], 'I' => [N,N,W,N,N,W,W,N,N], 'J' => [N,N,N,N,W,W,W,N,N], 'K' => [W,N,N,N,N,N,N,W,W], 'L' => [N,N,W,N,N,N,N,W,W], 'M' => [W,N,W,N,N,N,N,W,N], 'N' => [N,N,N,N,W,N,N,W,W], 'O' => [W,N,N,N,W,N,N,W,N], 'P' => [N,N,W,N,W,N,N,W,N], 'Q' => [N,N,N,N,N,N,W,W,W], 'R' => [W,N,N,N,N,N,W,W,N], 'S' => [N,N,W,N,N,N,W,W,N], 'T' => [N,N,N,N,W,N,W,W,N], 'U' => [W,W,N,N,N,N,N,N,W], 'V' => [N,W,W,N,N,N,N,N,W], 'W' => [W,W,W,N,N,N,N,N,N], 'X' => [N,W,N,N,W,N,N,N,W], 'Y' => [W,W,N,N,W,N,N,N,N], 'Z' => [N,W,W,N,W,N,N,N,N] } #In extended mode, each character is replaced with two characters from the "normal" encoding EXTENDED_ENCODINGS = { "\000" => '%U', " " => " ", "@" => "%V", "`" => "%W", "\001" => '$A', "!" => "/A", "A" => "A", "a" => "+A", "\002" => '$B', '"' => "/B", "B" => "B", "b" => "+B", "\003" => '$C', "#" => "/C", "C" => "C", "c" => "+C", "\004" => '$D', "$" => "/D", "D" => "D", "d" => "+D", "\005" => '$E', "%" => "/E", "E" => "E", "e" => "+E", "\006" => '$F', "&" => "/F", "F" => "F", "f" => "+F", "\007" => '$G', "'" => "/G", "G" => "G", "g" => "+G", "\010" => '$H', "(" => "/H", "H" => "H", "h" => "+H", "\011" => '$I', ")" => "/I", "I" => "I", "i" => "+I", "\012" => '$J', "*" => "/J", "J" => "J", "j" => "+J", "\013" => '$K', "+" => "/K", "K" => "K", "k" => "+K", "\014" => '$L', "," => "/L", "L" => "L", "l" => "+L", "\015" => '$M', "-" => "-", "M" => "M", "m" => "+M", "\016" => '$N', "." => ".", "N" => "N", "n" => "+N", "\017" => '$O', "/" => "/O", "O" => "O", "o" => "+O", "\020" => '$P', "0" => "0", "P" => "P", "p" => "+P", "\021" => '$Q', "1" => "1", "Q" => "Q", "q" => "+Q", "\022" => '$R', "2" => "2", "R" => "R", "r" => "+R", "\023" => '$S', "3" => "3", "S" => "S", "s" => "+S", "\024" => '$T', "4" => "4", "T" => "T", "t" => "+T", "\025" => '$U', "5" => "5", "U" => "U", "u" => "+U", "\026" => '$V', "6" => "6", "V" => "V", "v" => "+V", "\027" => '$W', "7" => "7", "W" => "W", "w" => "+W", "\030" => '$X', "8" => "8", "X" => "X", "x" => "+X", "\031" => '$Y', "9" => "9", "Y" => "Y", "y" => "+Y", "\032" => '$Z', ":" => "/Z", "Z" => "Z", "z" => "+Z", "\033" => '%A', ";" => "%F", "[" => "%K", "{" => "%P", "\034" => '%B', "<" => "%G", "\\" => "%L", "|" => "%Q", "\035" => '%C', "=" => "%H", "]" => "%M", "}" => "%R", "\036" => '%D', ">" => "%I", "^" => "%N", "~" => "%S", "\037" => '%E', "?" => "%J", "_" => "%O", "\177" => "%T" } CHECKSUM_VALUES = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'I' => 18, 'J' => 19, 'K' => 20, 'L' => 21, 'N' => 23, 'M' => 22, 'O' => 24, 'P' => 25, 'Q' => 26, 'R' => 27, 'S' => 28, 'T' => 29, 'U' => 30, 'V' => 31, 'W' => 32, 'X' => 33, 'Y' => 34, 'Z' => 35, '-' => 36, '.' => 37, ' ' => 38, '$' => 39, '/' => 40, '+' => 41, '%' => 42 } START_ENCODING = [N,W,N,N,W,N,W,N,N] # * STOP_ENCODING = [N,W,N,N,W,N,W,N,N] # * attr_accessor :data, :spacing, :narrow_width, :wide_width, :extended, :include_checksum # Do not surround "data" with the mandatory "*" as is this is done automically for you. # So instead of passing "*123456*" as "data", just pass "123456". def initialize(data, extended=false) self.data = data self.extended = extended raise(ArgumentError, "data is not valid (extended=#{extended?})") unless valid? yield self if block_given? end #Returns the characters that were passed in, no matter it they're part of #the extended charset or if they're already encodable, "normal" characters def raw_characters data.split(//) end #Returns the encodable characters. If extended mode is enabled, each character will #first be replaced by two characters from the encodable charset def characters chars = raw_characters extended ? chars.map{|c| EXTENDED_ENCODINGS[c].split(//) }.flatten : chars end def characters_with_checksum characters + [checksum_character] end def encoded_characters characters.map{|c| encoding_for(c) } end def encoded_characters_with_checksum encoded_characters + [checksum_encoding] end #The data part of the encoding (no start+stop characters) def data_encoding encoded_characters.join(spacing_encoding) end def data_encoding_with_checksum encoded_characters_with_checksum.join(spacing_encoding) end def encoding return encoding_with_checksum if include_checksum? start_encoding+spacing_encoding+data_encoding+spacing_encoding+stop_encoding end def encoding_with_checksum start_encoding+spacing_encoding+data_encoding_with_checksum+spacing_encoding+stop_encoding end #Checksum is optional def checksum characters.inject(0) do |sum,char| sum + CHECKSUM_VALUES[char] end % 43 end def checksum_character CHECKSUM_VALUES.invert[checksum] end def checksum_encoding encoding_for(checksum_character) end #Set include_checksum to true to make +encoding+ include the checksum def include_checksum? include_checksum end #Takes an array of WIDE/NARROW values and returns the string representation for #those bars and spaces, using wide_width and narrow_width def encoding_for_bars(*bars_and_spaces) bar = false bars_and_spaces.flatten.map do |width| bar = !bar (bar ? '1' : '0') * (width == WIDE ? wide_width : narrow_width) end.join end #Returns the string representation for a single character def encoding_for(character) encoding_for_bars(ENCODINGS[character]) end #Spacing between the characters in xdims. Spacing will be inserted #between each character in the encoding def spacing @spacing ||= 1 end def spacing_encoding '0' * spacing end def narrow_width @narrow_width ||= 1 end def wide_width @wide_width ||= 2 end def extended? extended end def start_encoding encoding_for_bars(START_ENCODING) end def stop_encoding encoding_for_bars(STOP_ENCODING) end def valid? if extended? raw_characters.all?{|c| EXTENDED_ENCODINGS.include?(c) } else raw_characters.all?{|c| ENCODINGS.include?(c) } end end def to_s data end end end diff --git a/lib/barby/barcode/code_93.rb b/lib/barby/barcode/code_93.rb index 9571c12..0c7d917 100644 --- a/lib/barby/barcode/code_93.rb +++ b/lib/barby/barcode/code_93.rb @@ -1,230 +1,231 @@ +#encoding: ASCII require 'barby/barcode' module Barby class Code93 < Barcode1D SHIFT_DOLLAR = "\301" # ($) SHIFT_PERCENT = "\302" # (%) SHIFT_SLASH = "\303" # (/) SHIFT_PLUS = "\304" # (+) SHIFT_CHARACTERS = [SHIFT_DOLLAR, SHIFT_PERCENT, SHIFT_SLASH, SHIFT_PLUS] ENCODINGS = { "0" => "100010100", "1" => "101001000", "2" => "101000100", "3" => "101000010", "4" => "100101000", "5" => "100100100", "6" => "100100010", "7" => "101010000", "8" => "100010010", "9" => "100001010", "A" => "110101000", "B" => "110100100", "C" => "110100010", "D" => "110010100", "E" => "110010010", "F" => "110001010", "G" => "101101000", "H" => "101100100", "I" => "101100010", "J" => "100110100", "K" => "100011010", "L" => "101011000", "M" => "101001100", "N" => "101000110", "O" => "100101100", "P" => "100010110", "Q" => "110110100", "R" => "110110010", "S" => "110101100", "T" => "110100110", "U" => "110010110", "V" => "110011010", "W" => "101101100", "X" => "101100110", "Y" => "100110110", "Z" => "100111010", "-" => "100101110", "." => "111010100", " " => "111010010", "$" => "111001010", "/" => "101101110", "+" => "101110110", "%" => "110101110", SHIFT_DOLLAR => "100100110", SHIFT_PERCENT => "111011010", SHIFT_SLASH => "111010110", SHIFT_PLUS => "100110010" } EXTENDED_MAPPING = { "\000" => "\302U", " " => " ", "@" => "\302V", "`" => "\302W", "\001" => "\301A", "!" => "\303A", "A" => "A", "a" => "\304A", "\002" => "\301B", '"' => "\303B", "B" => "B", "b" => "\304B", "\003" => "\301C", "#" => "\303C", "C" => "C", "c" => "\304C", "\004" => "\301D", "$" => "\303D", "D" => "D", "d" => "\304D", "\005" => "\301E", "%" => "\303E", "E" => "E", "e" => "\304E", "\006" => "\301F", "&" => "\303F", "F" => "F", "f" => "\304F", "\007" => "\301G", "'" => "\303G", "G" => "G", "g" => "\304G", "\010" => "\301H", "(" => "\303H", "H" => "H", "h" => "\304H", "\011" => "\301I", ")" => "\303I", "I" => "I", "i" => "\304I", "\012" => "\301J", "*" => "\303J", "J" => "J", "j" => "\304J", "\013" => "\301K", "/" => "\303K", "K" => "K", "k" => "\304K", "\014" => "\301L", "," => "\303L", "L" => "L", "l" => "\304L", "\015" => "\301M", "-" => "-", "M" => "M", "m" => "\304M", "\016" => "\301N", "." => ".", "N" => "N", "n" => "\304N", "\017" => "\301O", "+" => "\303O", "O" => "O", "o" => "\304O", "\020" => "\301P", "0" => "0", "P" => "P", "p" => "\304P", "\021" => "\301Q", "1" => "1", "Q" => "Q", "q" => "\304Q", "\022" => "\301R", "2" => "2", "R" => "R", "r" => "\304R", "\023" => "\301S", "3" => "3", "S" => "S", "s" => "\304S", "\024" => "\301T", "4" => "4", "T" => "T", "t" => "\304T", "\025" => "\301U", "5" => "5", "U" => "U", "u" => "\304U", "\026" => "\301V", "6" => "6", "V" => "V", "v" => "\304V", "\027" => "\301W", "7" => "7", "W" => "W", "w" => "\304W", "\030" => "\301X", "8" => "8", "X" => "X", "x" => "\304X", "\031" => "\301Y", "9" => "9", "Y" => "Y", "y" => "\304Y", "\032" => "\301Z", ":" => "\303Z", "Z" => "Z", "z" => "\304Z", "\033" => "\302A", ";" => "\302F", "[" => "\302K", "{" => "\302P", "\034" => "\302B", "<" => "\302G", "\\" => "\302L", "|" => "\302Q", "\035" => "\302C", "=" => "\302H", "]" => "\302M", "}" => "\302R", "\036" => "\302D", ">" => "\302I", "^" => "\302N", "~" => "\302S", "\037" => "\302E", "?" => "\302J", "_" => "\302O", "\177" => "\302T" } EXTENDED_CHARACTERS = EXTENDED_MAPPING.keys - ENCODINGS.keys CHARACTERS = { 0 => "0", 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8 => "8", 9 => "9", 10 => "A", 11 => "B", 12 => "C", 13 => "D", 14 => "E", 15 => "F", 16 => "G", 17 => "H", 18 => "I", 19 => "J", 20 => "K", 21 => "L", 22 => "M", 23 => "N", 24 => "O", 25 => "P", 26 => "Q", 27 => "R", 28 => "S", 29 => "T", 30 => "U", 31 => "V", 32 => "W", 33 => "X", 34 => "Y", 35 => "Z", 36 => "-", 37 => ".", 38 => " ", 39 => "$", 40 => "/", 41 => "+", 42 => "%", 43 => SHIFT_DOLLAR, 44 => SHIFT_PERCENT, 45 => SHIFT_SLASH, 46 => SHIFT_PLUS } VALUES = CHARACTERS.invert START_ENCODING = '101011110' # * STOP_ENCODING = '101011110' TERMINATE_ENCODING = '1' attr_accessor :data def initialize(data) self.data = data end def extended? raw_characters.any?{|c| EXTENDED_CHARACTERS.include?(c) } end def raw_characters data.split(//) end def characters raw_characters.map{|c| EXTENDED_MAPPING[c].split(//) }.flatten end def encoded_characters characters.map{|c| ENCODINGS[c] } end alias character_encodings encoded_characters def start_encoding START_ENCODING end #The stop encoding includes the termination bar def stop_encoding STOP_ENCODING+TERMINATE_ENCODING end def encoding start_encoding+data_encoding_with_checksums+stop_encoding end def data_encoding character_encodings.join end def data_encoding_with_checksums (character_encodings + checksum_encodings).join end def checksum_encodings checksum_characters.map{|c| ENCODINGS[c] } end def checksum_encoding checksum_encodings.join end def checksums [c_checksum, k_checksum] end def checksum_characters checksums.map{|s| CHARACTERS[s] } end #Returns the values used for computing the C checksum #in the "right" order (i.e. reversed) def checksum_values characters.map{|c| VALUES[c] }.reverse end #Returns the normal checksum plus the c_checksum #This is used for calculating the k_checksum def checksum_values_with_c_checksum [c_checksum] + checksum_values end #Calculates the C checksum based on checksum_values def c_checksum sum = 0 checksum_values.each_with_index do |value, index| sum += ((index % 20) + 1) * value end sum % 47 end def c_checksum_character CHARACTERS[c_checksum] end def c_checksum_encoding ENCODINGS[c_checksum_character] end #Calculates the K checksum based on checksum_values_with_c_checksum def k_checksum sum = 0 checksum_values_with_c_checksum.each_with_index do |value, index| sum += ((index % 15) + 1) * value end sum % 47 end def k_checksum_character CHARACTERS[k_checksum] end def k_checksum_encoding ENCODINGS[k_checksum_character] end def valid? characters.all?{|c| ENCODINGS.include?(c) } end def to_s data end end end diff --git a/lib/barby/barcode/data_matrix.rb b/lib/barby/barcode/data_matrix.rb index 5005895..9bf9576 100644 --- a/lib/barby/barcode/data_matrix.rb +++ b/lib/barby/barcode/data_matrix.rb @@ -1,46 +1,46 @@ -require 'semacode' +require 'semacode' #Ruby 1.8: gem install semacode - Ruby 1.9: gem install semacode-ruby19 require 'barby/barcode' module Barby #Uses the semacode library (gem install semacode) to encode DataMatrix barcodes class DataMatrix < Barcode2D attr_accessor :data def initialize(data) self.data = data end def data=(data) @data = data @encoder = nil end def encoder @encoder ||= ::DataMatrix::Encoder.new(data) end def encoding encoder.data.map{|a| a.map{|b| b ? '1' : '0' }.join } end def semacode? #TODO: Not sure if this is right data =~ /^http:\/\// end def to_s data end end end diff --git a/test/barcodes.rb b/test/barcodes.rb new file mode 100644 index 0000000..61b8ae2 --- /dev/null +++ b/test/barcodes.rb @@ -0,0 +1,19 @@ +require 'code_128_test' +require 'gs1_128_test' + +require 'code_25_test' +require 'code_25_interleaved_test' +require 'code_25_iata_test' + +require 'code_39_test' +require 'code_93_test' + +require 'ean13_test' +require 'ean8_test' +require 'bookland_test' +require 'upc_supplemental_test' + +require 'data_matrix_test' +require 'qr_code_test' + +#require 'pdf_417_test' diff --git a/test/code_39_test.rb b/test/code_39_test.rb index 2fff220..7d60de9 100644 --- a/test/code_39_test.rb +++ b/test/code_39_test.rb @@ -1,209 +1,210 @@ +#encoding: ASCII require 'test_helper' require 'barby/barcode/code_39' class Code39Test < Barby::TestCase before do @data = 'TEST8052' @code = Code39.new(@data) @code.spacing = 3 end it "should yield self on initialize" do c1 = nil c2 = Code39.new('TEST'){|c| c1 = c } c1.must_equal c2 end it "should have the expected data" do @code.data.must_equal @data end it "should have the expected characters" do @code.characters.must_equal @data.split(//) end it "should have the expected start_encoding" do @code.start_encoding.must_equal '100101101101' end it "should have the expected stop_encoding" do @code.stop_encoding.must_equal '100101101101' end it "should have the expected spacing_encoding" do @code.spacing_encoding.must_equal '000' end it "should have the expected encoded characters" do @code.encoded_characters.must_equal %w(101011011001 110101100101 101101011001 101011011001 110100101101 101001101101 110100110101 101100101011) end it "should have the expected data_encoding" do @code.data_encoding.must_equal '101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011' end it "should have the expected encoding" do @code.encoding.must_equal '100101101101000101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011000100101101101' end it "should be valid" do assert @code.valid? end it "should not be valid" do @code.data = "123\200456" refute @code.valid? end it "should raise an exception when data is not valid on initialization" do lambda{ Code39.new('abc') }.must_raise(ArgumentError) end it "should return all characters in sequence without checksum on to_s" do @code.to_s.must_equal @data end describe "Checksumming" do before do @code = Code39.new('CODE39') end it "should have the expected checksum" do @code.checksum.must_equal 32 end it "should have the expected checksum_character" do @code.checksum_character.must_equal 'W' end it "should have the expected checksum_encoding" do @code.checksum_encoding.must_equal '110011010101' end it "should have the expected characters_with_checksum" do @code.characters_with_checksum.must_equal %w(C O D E 3 9 W) end it "should have the expected encoded_characters_with_checksum" do @code.encoded_characters_with_checksum.must_equal %w(110110100101 110101101001 101011001011 110101100101 110110010101 101100101101 110011010101) end it "should have the expected data_encoding_with_checksum" do @code.data_encoding_with_checksum.must_equal "110110100101011010110100101010110010110110101100101011011001010101011001011010110011010101" end it "should have the expected encoding_with_checksum" do @code.encoding_with_checksum.must_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" end it "should return the encoding with checksum when include_checksum == true" do @code.include_checksum = true @code.encoding.must_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" end end describe "Normal encoding" do before do @data = 'ABC$%' @code = Code39.new(@data) end it "should have the expected characters" do @code.characters.must_equal %w(A B C $ %) end it "should have the expected encoded_characters" do @code.encoded_characters.must_equal %w(110101001011 101101001011 110110100101 100100100101 101001001001) end it "should have the expected data_encoding" do @code.data_encoding.must_equal '1101010010110101101001011011011010010101001001001010101001001001' end it "should not be valid" do @code.data = 'abc' refute @code.valid? end end describe "Extended encoding" do before do @data = '<abc>' @code = Code39.new(@data, true) end it "should return true on extended?" do assert @code.extended? end it "should have the expected characters" do @code.characters.must_equal %w(% G + A + B + C % I) end it "should have the expected encoded_characters" do @code.encoded_characters.must_equal %w(101001001001 101010011011 100101001001 110101001011 100101001001 101101001011 100101001001 110110100101 101001001001 101101001101) end it "should have the expected data_encoding" do @code.data_encoding.must_equal '101001001001010101001101101001010010010110101001011010010100100101011010010110100101001001011011010010101010010010010101101001101' end it "should have the expected encoding" do @code.encoding.must_equal '10010110110101010010010010101010011011010010100100101101010010110100101001001'+ '010110100101101001010010010110110100101010100100100101011010011010100101101101' end it "should take a second parameter on initialize indicating it is extended" do assert Code39.new('abc', true).extended? refute Code39.new('ABC', false).extended? refute Code39.new('ABC').extended? end it "should be valid" do assert @code.valid? end it "should not be valid" do @code.data = "abc\200123" refute @code.valid? end it "should return all characters in sequence without checksum on to_s" do @code.to_s.must_equal @data end end describe "Variable widths" do before do @data = 'ABC$%' @code = Code39.new(@data) @code.narrow_width = 2 @code.wide_width = 5 end it "should have the expected encoded_characters" do @code.encoded_characters.must_equal %w(111110011001100000110011111 110011111001100000110011111 111110011111001100000110011 110000011000001100000110011 110011000001100000110000011) end it "should have the expected data_encoding" do # A SB SC S$ S% @code.data_encoding.must_equal '1111100110011000001100111110110011111001100000110011111011111001111100110000011001101100000110000011000001100110110011000001100000110000011' @code.spacing = 3 # A S B S C S $ S % @code.data_encoding.must_equal '111110011001100000110011111000110011111001100000110011111000111110011111001100000110011000110000011000001100000110011000110011000001100000110000011' end end end diff --git a/test/code_93_test.rb b/test/code_93_test.rb index 749b39b..5a9615b 100644 --- a/test/code_93_test.rb +++ b/test/code_93_test.rb @@ -1,143 +1,144 @@ +#encoding: ASCII require 'test_helper' require 'barby/barcode/code_93' class Code93Test < Barby::TestCase before do @data = 'TEST93' @code = Code93.new(@data) end it "should return the same data we put in" do @code.data.must_equal @data end it "should have the expected characters" do @code.characters.must_equal @data.split(//) end it "should have the expected start_encoding" do @code.start_encoding.must_equal '101011110' end it "should have the expected stop_encoding" do # STOP TERM @code.stop_encoding.must_equal '1010111101' end it "should have the expected encoded characters" do # T E S T 9 3 @code.encoded_characters.must_equal %w(110100110 110010010 110101100 110100110 100001010 101000010) end it "should have the expected data_encoding" do # T E S T 9 3 @code.data_encoding.must_equal "110100110110010010110101100110100110100001010101000010" end it "should have the expected data_encoding_with_checksums" do # T E S T 9 3 + (C) 6 (K) @code.data_encoding_with_checksums.must_equal "110100110110010010110101100110100110100001010101000010101110110100100010" end it "should have the expected encoding" do # START T E S T 9 3 + (C) 6 (K) STOP TERM @code.encoding.must_equal "1010111101101001101100100101101011001101001101000010101010000101011101101001000101010111101" end it "should have the expected checksum_values" do @code.checksum_values.must_equal [29, 14, 28, 29, 9, 3].reverse #! end it "should have the expected c_checksum" do @code.c_checksum.must_equal 41 #calculate this first! end it "should have the expected c_checksum_character" do @code.c_checksum_character.must_equal '+' end it "should have the expected c_checksum_encoding" do @code.c_checksum_encoding.must_equal '101110110' end it "should have the expected checksum_values_with_c_checksum" do @code.checksum_values_with_c_checksum.must_equal [29, 14, 28, 29, 9, 3, 41].reverse #! end it "should have the expected k_checksum" do @code.k_checksum.must_equal 6 #calculate this first! end it "should have the expected k_checksum_character" do @code.k_checksum_character.must_equal '6' end it "should have the expected k_checksum_encoding" do @code.k_checksum_encoding.must_equal '100100010' end it "should have the expected checksums" do @code.checksums.must_equal [41, 6] end it "should have the expected checksum_characters" do @code.checksum_characters.must_equal ['+', '6'] end it "should have the expected checksum_encodings" do @code.checksum_encodings.must_equal %w(101110110 100100010) end it "should have the expected checksum_encoding" do @code.checksum_encoding.must_equal '101110110100100010' end it "should be valid" do assert @code.valid? end it "should not be valid when not in extended mode" do @code.data = 'not extended' end it "should return data with no checksums on to_s" do @code.to_s.must_equal 'TEST93' end describe "Extended mode" do before do @data = "Extended!" @code = Code93.new(@data) end it "should be extended" do assert @code.extended? end it "should convert extended characters to special shift characters" do @code.characters.must_equal ["E", "\304", "X", "\304", "T", "\304", "E", "\304", "N", "\304", "D", "\304", "E", "\304", "D", "\303", "A"] end it "should have the expected data_encoding" do @code.data_encoding.must_equal '110010010100110010101100110100110010110100110100110010110010010'+ '100110010101000110100110010110010100100110010110010010100110010110010100111010110110101000' end it "should have the expected c_checksum" do @code.c_checksum.must_equal 9 end it "should have the expected k_checksum" do @code.k_checksum.must_equal 46 end it "should return the original data on to_s with no checksums" do @code.to_s.must_equal 'Extended!' end end end diff --git a/test/data_matrix_test.rb b/test/data_matrix_test.rb index e65deea..6e971b7 100644 --- a/test/data_matrix_test.rb +++ b/test/data_matrix_test.rb @@ -1,34 +1,30 @@ -unless RUBY_VERSION >= '1.9' +require 'test_helper' +require 'barby/barcode/data_matrix' - require 'test_helper' - require 'barby/barcode/data_matrix' +class DataMatrixTest < Barby::TestCase - class DataMatrixTest < Barby::TestCase - - before do - @data = "humbaba" - @code = Barby::DataMatrix.new(@data) - end - - it "should have the expected encoding" do - @code.encoding.must_equal ["1010101010101010", "1011111000011111", "1110111000010100", - "1110100100000111", "1101111010101000", "1101111011110011", - "1111111100000100", "1100101111110001", "1001000010001010", - "1101010110111011", "1000000100011110", "1001010010000011", - "1101100111011110", "1110111010000101", "1110010110001010", - "1111111111111111"] - end + before do + @data = "humbaba" + @code = Barby::DataMatrix.new(@data) + end - it "should return data on to_s" do - @code.to_s.must_equal @data - end + it "should have the expected encoding" do + @code.encoding.must_equal ["1010101010101010", "1011111000011111", "1110111000010100", + "1110100100000111", "1101111010101000", "1101111011110011", + "1111111100000100", "1100101111110001", "1001000010001010", + "1101010110111011", "1000000100011110", "1001010010000011", + "1101100111011110", "1110111010000101", "1110010110001010", + "1111111111111111"] + end - it "should be able to change its data" do - prev_encoding = @code.encoding - @code.data = "after eight" - @code.encoding.wont_equal prev_encoding - end + it "should return data on to_s" do + @code.to_s.must_equal @data + end + it "should be able to change its data" do + prev_encoding = @code.encoding + @code.data = "after eight" + @code.encoding.wont_equal prev_encoding end end diff --git a/test/gs1_128_test.rb b/test/gs1_128_test.rb index bf3575e..e66e2ee 100644 --- a/test/gs1_128_test.rb +++ b/test/gs1_128_test.rb @@ -1,67 +1,68 @@ +#encoding: ASCII require 'test_helper' require 'barby/barcode/gs1_128' class GS1128Test < Barby::TestCase before do @code = GS1128.new('071230', 'C', '11') end it "should inherit Code128" do GS1128.superclass.must_equal Code128 end it "should have an application_identifier attribute" do @code.must_respond_to(:application_identifier) @code.must_respond_to(:application_identifier=) end it "should have the given application identifier" do @code.application_identifier.must_equal '11' end it "should have an application_identifier_encoding" do @code.must_respond_to(:application_identifier_encoding) end it "should have the expected application_identifier_number" do @code.application_identifier_number.must_equal 11 end it "should have the expected application identifier encoding" do @code.application_identifier_encoding.must_equal '11000100100'#Code C number 11 end it "should have data with FNC1 and AI" do @code.data.must_equal "\30111071230" end it "should have partial_data without FNC1 or AI" do @code.partial_data.must_equal '071230' end it "should have characters that include FNC1 and AI" do @code.characters.must_equal %W(\301 11 07 12 30) end it "should have data_encoding that includes FNC1 and the AI" do @code.data_encoding.must_equal '1111010111011000100100100110001001011001110011011011000' end it "should have the expected checksum" do @code.checksum.must_equal 36 end it "should have the expected checksum encoding" do @code.checksum_encoding == '10110001000' end it "should have the expected encoding" do @code.encoding.must_equal '110100111001111010111011000100100100110001001011001110011011011000101100010001100011101011' end it "should return full data excluding change codes, including AI on to_s" do @code.to_s.must_equal '(11) 071230' end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 39e45f7..28169e2 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,25 +1,23 @@ require 'rubygems' -require 'bundler' -Bundler.setup require 'barby' require 'minitest/spec' require 'minitest/autorun' module Barby class TestCase < MiniTest::Spec include Barby private # So we can register outputter during an full test suite run. def load_outputter(outputter) @loaded_outputter ||= load "barby/outputter/#{outputter}_outputter.rb" end def ruby_19_or_greater? RUBY_VERSION >= '1.9' end end end
toretore/barby
1634331ea0d523608cc0667133da40512384ae44
Fix HtmlOutputter.
diff --git a/lib/barby/outputter/html_outputter.rb b/lib/barby/outputter/html_outputter.rb index 7098050..62fb46e 100644 --- a/lib/barby/outputter/html_outputter.rb +++ b/lib/barby/outputter/html_outputter.rb @@ -1,93 +1,93 @@ require 'barby/outputter' module Barby # Outputs an HTML <table> containing cells for each module in the barcode. # # This does NOT include any styling, you're expected to add the relevant # CSS yourself. The markup is simple: One <table> with class 'barby-barcode', # one or more <tr class="barby-row"> inside a <tbody> each containing # <td class="barby-cell"> for each module with the additional class "on" or "off". # # Example, let's say the barcode.encoding == ['101', '010'] : # # <table class="barby-barcode"> # <tbody> # <tr class="barby-row"> # <td class="barby-cell on"></td> # <td class="barby-cell off"></td> # <td class="barby-cell on"></td> # </tr> # <tr class="barby-row"> # <td class="barby-cell off"></td> # <td class="barby-cell on"></td> # <td class="barby-cell off"></td> # </tr> # </tbody> # </table> # # You could then style this with: # # table.barby-barcode { border-spacing: 0; } # tr.barby-row {} # td.barby-cell { width: 3px; height: 3px; } # td.barby-cell.on { background: #000; } # # Options: # # :class_name - A class name that will be added to the <table> in addition to barby-barcode class HtmlOutputter < Outputter register :to_html attr_accessor :class_name def to_html(options = {}) with_options options do start + rows.join + stop end end def rows if barcode.two_dimensional? rows_for(booleans) else rows_for([booleans]) end end def rows_for(boolean_groups) boolean_groups.map{|g| row_for(cells_for(g)) } end def cells_for(booleans) booleans.map{|b| b ? on_cell : off_cell } end def row_for(cells) - cells.map{|c| "<tr class=\"barby-row\">#{c}</tr>" }.join + "<tr class=\"barby-row\">#{cells.join}</tr>" end def on_cell '<td class="barby-cell on"></td>' end def off_cell '<td class="barby-cell off"></td>' end def start '<table class="barby-barcode'+(class_name ? " #{class_name}" : '')+'"><tbody>' end def stop '</tbody></table>' end end end
toretore/barby
3225004f29b9e250953d12f43ba4c8565a9a1c3e
Clean up Rakefile
diff --git a/Rakefile b/Rakefile index d17dc85..efa7cb0 100644 --- a/Rakefile +++ b/Rakefile @@ -1,27 +1,15 @@ require 'rake' -require 'rake/gempackagetask' require 'rake/testtask' -require 'fileutils' - -include FileUtils - -spec = eval(File.read('barby.gemspec')) - -Rake::GemPackageTask.new(spec) do |pkg| - pkg.need_tar = false -end - -task :default => "pkg/#{spec.name}-#{spec.version}.gem" do - puts "generated latest version" -end +require 'rdoc/task' Rake::TestTask.new do |t| t.libs = ['lib','test'] t.test_files = Dir.glob("test/**/*_test.rb").sort t.verbose = true end -desc "Build RDoc" -task :doc do - system "rm -rf site/rdoc; rdoc -tBarby -xvendor -osite/rdoc -mREADME lib/**/* README" +RDoc::Task.new do |rdoc| + rdoc.main = "README" + rdoc.rdoc_files.include("README", "lib") + rdoc.rdoc_dir = 'doc' end
toretore/barby
268a077e893c57257711ab67f0d88e1d131d37a1
Rewrite HtmlOutputter
diff --git a/CHANGELOG b/CHANGELOG index faaafa8..62ae7c0 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,58 +1,66 @@ +* master + +* Rewrite HtmlOutputter. Not entirely backwards compatible with the previous version. + +* 0.5.0 + +* Require requirement of barcode symbologies in the same way outputters must be required before being used + * 0.4.4 * Use Gemfile for dependency management [Ken Collins] * Move to MiniTest [Ken Collins] * HTML outputter [Ken Collins] * Various 1.9 fixes [Ken Collins, Dominique Ribaut] * 0.4.3 * 2- and 5-digit UPC supplements * Use ChunkyPNG for PngOutputter * 0.4.2 * ChunkyPngOutputter now renders 2D barcodes not upside down [Thanks Scient] * 0.4.1 * ChunkyPngOutputter - ChunkyPNG is a pure-Ruby PNG library * 0.4.0 * Can you tell I'm just making up version numbers as I go along? * DataMatrix (not required automatically, requires the 'semacode' gem) * Refactored PrawnOutputter a little. No more stupid options hashes + unbleed attribute * 0.3.2 * Fix bug where Code128 extras choke on newlines [Wayne Conrad] * Don't allow Code128 with empty data strings [Wayne Conrad] * Allow custom :size for QrCodes * 0.3.1 * Add support for PDF417, using Pdf417lib (JRuby only) [Aslak Hellesøy] * 0.3.0 * Make compatible with Ruby 1.9 [Chris Mowforth] * Add SvgOutputter for outputting SVGs without dependencies [Peter H. Li] * 0.2.1 * Allow QR Codes with sizes up to 40 * 0.2.0 * Added support for 2D barcodes * Updated all outputters to support 2D barcodes * Added support for QR Code * 0.1.2 * Added CairoOutputter [Kouhei Sutou] * 0.1.1 * Added PngOutputter that uses "png" gem diff --git a/lib/barby/outputter/html_outputter.rb b/lib/barby/outputter/html_outputter.rb index 1c8e200..7098050 100644 --- a/lib/barby/outputter/html_outputter.rb +++ b/lib/barby/outputter/html_outputter.rb @@ -1,88 +1,93 @@ require 'barby/outputter' module Barby - # Outputs an HTML representation of the barcode. - # - # Registers to_html - # - # Allowed options include. - # :width - Applied to parent element's style attribute. Default 100. - # :height - Applied to parent element's style attribute. Default 100. - # :css - Include Barby::HtmlOutputter.css in output's style tag. If you pass false - # you can include the output of Barby::HtmlOutputter.css in single place like - # your own stylesheet on once on the page. Default true. - # :parent_style - Include inline style for things like width and height on parent element. - # Useful if you want to style these attributes elsewhere globally. Default true. + # Outputs an HTML <table> containing cells for each module in the barcode. + # + # This does NOT include any styling, you're expected to add the relevant + # CSS yourself. The markup is simple: One <table> with class 'barby-barcode', + # one or more <tr class="barby-row"> inside a <tbody> each containing + # <td class="barby-cell"> for each module with the additional class "on" or "off". + # + # Example, let's say the barcode.encoding == ['101', '010'] : + # + # <table class="barby-barcode"> + # <tbody> + # <tr class="barby-row"> + # <td class="barby-cell on"></td> + # <td class="barby-cell off"></td> + # <td class="barby-cell on"></td> + # </tr> + # <tr class="barby-row"> + # <td class="barby-cell off"></td> + # <td class="barby-cell on"></td> + # <td class="barby-cell off"></td> + # </tr> + # </tbody> + # </table> + # + # You could then style this with: + # + # table.barby-barcode { border-spacing: 0; } + # tr.barby-row {} + # td.barby-cell { width: 3px; height: 3px; } + # td.barby-cell.on { background: #000; } + # + # Options: + # + # :class_name - A class name that will be added to the <table> in addition to barby-barcode class HtmlOutputter < Outputter register :to_html - - def self.css - <<-CSS - table.barby_code { - border: 0 none transparent !important; - border-collapse: collapse !important; - } - table.barby_code tr.barby_row { - border: 0 none transparent !important; - border-collapse: collapse !important; - margin: 0 !important; - padding: 0 !important; - } - table.barby_code tr.barby_row td { border: 0 none transparent !important; } - table.barby_code tr.barby_row td.barby_black { background-color: black !important; } - table.barby_code tr.barby_row td.barby_white { background-color: white !important; } - CSS + + attr_accessor :class_name + + + def to_html(options = {}) + with_options options do + start + rows.join + stop + end end - - def to_html(options={}) - default_options = {:width => 100, :height => 100, :css => true, :parent_style => :true} - options = default_options.merge(options) - elements = if barcode.two_dimensional? - booleans.map do |bools| - line_to_elements_row(bools, options) - end.join("\n") - else - line_to_elements_row(booleans, options) - end - html = %|<#{parent_element} class="barby_code" #{parent_style_attribute(options)}>\n#{elements}\n</#{parent_element}>| - options[:css] ? "<style>#{self.class.css}</style>\n#{html}" : html + + + def rows + if barcode.two_dimensional? + rows_for(booleans) + else + rows_for([booleans]) + end end - private + def rows_for(boolean_groups) + boolean_groups.map{|g| row_for(cells_for(g)) } + end - def line_to_elements_row(bools, options) - elements = bools.map{ |b| b ? black_tag : white_tag }.join - Array(%|<#{row_element} class="barby_row">#{elements}</#{row_element}>|) + def cells_for(booleans) + booleans.map{|b| b ? on_cell : off_cell } end - - def black_tag - '<td class="barby_black"></td>' + + def row_for(cells) + cells.map{|c| "<tr class=\"barby-row\">#{c}</tr>" }.join end - - def white_tag - '<td class="barby_white"></td>' + + def on_cell + '<td class="barby-cell on"></td>' end - - def row_element - 'tr' + + def off_cell + '<td class="barby-cell off"></td>' end - - def parent_element - 'table' + + def start + '<table class="barby-barcode'+(class_name ? " #{class_name}" : '')+'"><tbody>' end - - def parent_style_attribute(options) - return unless options[:parent_style] - s = '' - s << "width: #{options[:width]}px; " if options[:width] - s << "height: #{options[:height]}px; " if options[:height] - s.strip! - s.empty? ? nil : %|style="#{s}"| + + def stop + '</tbody></table>' end + end end diff --git a/test/outputter/html_outputter_test.rb b/test/outputter/html_outputter_test.rb index 66826ca..f15c41e 100644 --- a/test/outputter/html_outputter_test.rb +++ b/test/outputter/html_outputter_test.rb @@ -1,25 +1,68 @@ require 'test_helper' +require 'barby/barcode/code_128' +#require 'barby/outputter/html_outputter' class HtmlOutputterTest < Barby::TestCase + class MockCode + attr_reader :encoding + def initialize(e) + @encoding = e + end + def two_dimensional? + encoding.is_a? Array + end + end + before do load_outputter('html') @barcode = Barby::Code128B.new('BARBY') @outputter = HtmlOutputter.new(@barcode) end - + it "should register to_html" do Barcode.outputters.must_include(:to_html) end - - it "should include css style tag by default with option to leave out" do - @barcode.to_html.must_include "<style>#{Barby::HtmlOutputter.css}</style>" - @barcode.to_html(:css => false).wont_include "<style>#{Barby::HtmlOutputter.css}</style>" + + it 'should have the expected start HTML' do + assert_equal '<table class="barby-barcode"><tbody>', @outputter.start + end + + it 'should be able to set additional class name' do + @outputter.class_name = 'humbaba' + assert_equal '<table class="barby-barcode humbaba"><tbody>', @outputter.start + end + + it 'should have the expected stop HTML' do + assert_equal '</tbody></table>', @outputter.stop end - - it "should include inline parent style for width and height with option to disable" do - @barcode.to_html.must_include '<table class="barby_code" style="width: 100px; height: 100px;">' - @barcode.to_html(:parent_style => false).must_include '<table class="barby_code" >' + + it 'should build the expected cells' do + assert_equal ['<td class="barby-cell on"></td>', '<td class="barby-cell off"></td>', '<td class="barby-cell off"></td>', '<td class="barby-cell on"></td>'], + @outputter.cells_for([true, false, false, true]) + end + + it 'should build the expected rows' do + assert_equal( + [ + @outputter.cells_for([true, false]).map{|c| "<tr class=\"barby-row\">#{c}</tr>" }.join, + @outputter.cells_for([false, true]).map{|c| "<tr class=\"barby-row\">#{c}</tr>" }.join + ], + @outputter.rows_for([[true, false],[false, true]]) + ) + end + + it 'should have the expected rows' do + barcode = MockCode.new('101100') + outputter = HtmlOutputter.new(barcode) + assert_equal outputter.rows_for([[true, false, true, true, false, false]]), outputter.rows + barcode = MockCode.new(['101', '010']) + outputter = HtmlOutputter.new(barcode) + assert_equal outputter.rows_for([[true, false, true], [false, true, false]]), outputter.rows + end + + it 'should have the expected html' do + assert_equal @outputter.start + @outputter.rows.join + @outputter.stop, @outputter.to_html end end
toretore/barby
0b9eb1b8f605503a0bc98983e5ed8b2dd4637aa5
Un-privatize some methods on Outputter
diff --git a/lib/barby/outputter.rb b/lib/barby/outputter.rb index 096588a..ae1a6ea 100644 --- a/lib/barby/outputter.rb +++ b/lib/barby/outputter.rb @@ -1,135 +1,135 @@ require 'barby/barcode' module Barby #An Outputter creates something from a barcode. That something can be #anything, but is most likely a graphical representation of the barcode. #Outputters can register methods on barcodes that will be associated with #them. # #The basic structure of an outputter class: # # class FooOutputter < Barby::Outputter # register :to_foo # def to_too # do_something_with(barcode.encoding) # end # end # #Barcode#to_foo will now be available to all barcodes class Outputter attr_accessor :barcode #An outputter instance will have access to a Barcode def initialize(barcode) self.barcode = barcode end #Register one or more handler methods with this outputter #Barcodes will then be able to use these methods to get the output #from the outputter. For example, if you have an ImageOutputter, #you could do: # #register :to_png, :to_gif # #You could then do aBarcode.to_png and get the result of that method. #The class which registers the method will receive the barcode as the only #argument, and the default implementation of initialize puts that into #the +barcode+ accessor. # #You can also have different method names on the barcode and the outputter #by providing a hash: # #register :to_png => :create_png, :to_gif => :create_gif def self.register(*method_names) if method_names.first.is_a? Hash method_names.first.each do |name, method_name| Barcode.register_outputter(name, self, method_name) end else method_names.each do |name| Barcode.register_outputter(name, self, name) end end end - private - def two_dimensional? barcode.respond_to?(:two_dimensional?) && barcode.two_dimensional? end #Converts the barcode's encoding (a string containing 1s and 0s) #to true and false values (1 == true == "black bar") # #If the barcode is 2D, each line will be converted to an array #in the same way def booleans(reload=false)#:doc: if two_dimensional? encoding(reload).map{|l| l.split(//).map{|c| c == '1' } } else encoding(reload).split(//).map{|c| c == '1' } end end #Returns the barcode's encoding. The encoding #is cached and can be reloaded by passing true def encoding(reload=false)#:doc: @encoding = barcode.encoding if reload @encoding ||= barcode.encoding end #Collects continuous groups of bars and spaces (1 and 0) #into arrays where the first item is true or false (1 or 0) #and the second is the size of the group # #For example, "1100111000" becomes [[true,2],[false,2],[true,3],[false,3]] def boolean_groups(reload=false) if two_dimensional? encoding(reload).map do |line| line.scan(/1+|0+/).map do |group| [group[0,1] == '1', group.size] end end else encoding(reload).scan(/1+|0+/).map do |group| [group[0,1] == '1', group.size] end end end + private + #Takes a hash and temporarily sets properties on self (the outputter object) #corresponding with the keys to their values. When the block exits, the #properties are reset to their original values. Returns whatever the block returns. def with_options(options={}) original_options = options.inject({}) do |origs,pair| if respond_to?(pair.first) && respond_to?("#{pair.first}=") origs[pair.first] = send(pair.first) send("#{pair.first}=", pair.last) end origs end rv = yield original_options.each do |attribute,value| send("#{attribute}=", value) end rv end end end
toretore/barby
9ad696be4da66a5598be187aada14b1ec7574199
Add explanation of char skip for Code128C
diff --git a/lib/barby/barcode/code_128.rb b/lib/barby/barcode/code_128.rb index d8860ef..75d23fd 100644 --- a/lib/barby/barcode/code_128.rb +++ b/lib/barby/barcode/code_128.rb @@ -1,410 +1,412 @@ require 'barby/barcode' module Barby #Code 128 barcodes # #Note that you must provide a type for each object, either by passing a string #as a second parameter to Code128.new or by instantiating one of the child classes. # #You can switch type by using the CODEA, CODEB and CODEC characters: # # "\305" => A # "\306" => B # "\307" => C # #As an example, here's one that starts out as type A and then switches to B and then C: # # Code128A.new("ABC123\306def\3074567") class Code128 < Barcode1D ENCODINGS = { 0 => "11011001100", 1 => "11001101100", 2 => "11001100110", 3 => "10010011000", 4 => "10010001100", 5 => "10001001100", 6 => "10011001000", 7 => "10011000100", 8 => "10001100100", 9 => "11001001000", 10 => "11001000100", 11 => "11000100100", 12 => "10110011100", 13 => "10011011100", 14 => "10011001110", 15 => "10111001100", 16 => "10011101100", 17 => "10011100110", 18 => "11001110010", 19 => "11001011100", 20 => "11001001110", 21 => "11011100100", 22 => "11001110100", 23 => "11101101110", 24 => "11101001100", 25 => "11100101100", 26 => "11100100110", 27 => "11101100100", 28 => "11100110100", 29 => "11100110010", 30 => "11011011000", 31 => "11011000110", 32 => "11000110110", 33 => "10100011000", 34 => "10001011000", 35 => "10001000110", 36 => "10110001000", 37 => "10001101000", 38 => "10001100010", 39 => "11010001000", 40 => "11000101000", 41 => "11000100010", 42 => "10110111000", 43 => "10110001110", 44 => "10001101110", 45 => "10111011000", 46 => "10111000110", 47 => "10001110110", 48 => "11101110110", 49 => "11010001110", 50 => "11000101110", 51 => "11011101000", 52 => "11011100010", 53 => "11011101110", 54 => "11101011000", 55 => "11101000110", 56 => "11100010110", 57 => "11101101000", 58 => "11101100010", 59 => "11100011010", 60 => "11101111010", 61 => "11001000010", 62 => "11110001010", 63 => "10100110000", 64 => "10100001100", 65 => "10010110000", 66 => "10010000110", 67 => "10000101100", 68 => "10000100110", 69 => "10110010000", 70 => "10110000100", 71 => "10011010000", 72 => "10011000010", 73 => "10000110100", 74 => "10000110010", 75 => "11000010010", 76 => "11001010000", 77 => "11110111010", 78 => "11000010100", 79 => "10001111010", 80 => "10100111100", 81 => "10010111100", 82 => "10010011110", 83 => "10111100100", 84 => "10011110100", 85 => "10011110010", 86 => "11110100100", 87 => "11110010100", 88 => "11110010010", 89 => "11011011110", 90 => "11011110110", 91 => "11110110110", 92 => "10101111000", 93 => "10100011110", 94 => "10001011110", 95 => "10111101000", 96 => "10111100010", 97 => "11110101000", 98 => "11110100010", 99 => "10111011110", 100 => "10111101110", 101 => "11101011110", 102 => "11110101110", 103 => "11010000100", 104 => "11010010000", 105 => "11010011100" } VALUES = { 'A' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "\000", 65 => "\001", 66 => "\002", 67 => "\003", 68 => "\004", 69 => "\005", 70 => "\006", 71 => "\a", 72 => "\b", 73 => "\t", 74 => "\n", 75 => "\v", 76 => "\f", 77 => "\r", 78 => "\016", 79 => "\017", 80 => "\020", 81 => "\021", 82 => "\022", 83 => "\023", 84 => "\024", 85 => "\025", 86 => "\026", 87 => "\027", 88 => "\030", 89 => "\031", 90 => "\032", 91 => "\e", 92 => "\034", 93 => "\035", 94 => "\036", 95 => "\037", 96 => "\303", 97 => "\302", 98 => "SHIFT", 99 => "\307", 100 => "\306", 101 => "\304", 102 => "\301", 103 => "STARTA", 104 => "STARTB", 105 => "STARTC" }.invert, 'B' => { 0 => " ", 1 => "!", 2 => "\"", 3 => "#", 4 => "$", 5 => "%", 6 => "&", 7 => "'", 8 => "(", 9 => ")", 10 => "*", 11 => "+", 12 => ",", 13 => "-", 14 => ".", 15 => "/", 16 => "0", 17 => "1", 18 => "2", 19 => "3", 20 => "4", 21 => "5", 22 => "6", 23 => "7", 24 => "8", 25 => "9", 26 => ":", 27 => ";", 28 => "<", 29 => "=", 30 => ">", 31 => "?", 32 => "@", 33 => "A", 34 => "B", 35 => "C", 36 => "D", 37 => "E", 38 => "F", 39 => "G", 40 => "H", 41 => "I", 42 => "J", 43 => "K", 44 => "L", 45 => "M", 46 => "N", 47 => "O", 48 => "P", 49 => "Q", 50 => "R", 51 => "S", 52 => "T", 53 => "U", 54 => "V", 55 => "W", 56 => "X", 57 => "Y", 58 => "Z", 59 => "[", 60 => "\\", 61 => "]", 62 => "^", 63 => "_", 64 => "`", 65 => "a", 66 => "b", 67 => "c", 68 => "d", 69 => "e", 70 => "f", 71 => "g", 72 => "h", 73 => "i", 74 => "j", 75 => "k", 76 => "l", 77 => "m", 78 => "n", 79 => "o", 80 => "p", 81 => "q", 82 => "r", 83 => "s", 84 => "t", 85 => "u", 86 => "v", 87 => "w", 88 => "x", 89 => "y", 90 => "z", 91 => "{", 92 => "|", 93 => "}", 94 => "~", 95 => "\177", 96 => "\303", 97 => "\302", 98 => "SHIFT", 99 => "\307", 100 => "\304", 101 => "\305", 102 => "\301", 103 => "STARTA", 104 => "STARTB", 105 => "STARTC", }.invert, 'C' => { 0 => "00", 1 => "01", 2 => "02", 3 => "03", 4 => "04", 5 => "05", 6 => "06", 7 => "07", 8 => "08", 9 => "09", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", 16 => "16", 17 => "17", 18 => "18", 19 => "19", 20 => "20", 21 => "21", 22 => "22", 23 => "23", 24 => "24", 25 => "25", 26 => "26", 27 => "27", 28 => "28", 29 => "29", 30 => "30", 31 => "31", 32 => "32", 33 => "33", 34 => "34", 35 => "35", 36 => "36", 37 => "37", 38 => "38", 39 => "39", 40 => "40", 41 => "41", 42 => "42", 43 => "43", 44 => "44", 45 => "45", 46 => "46", 47 => "47", 48 => "48", 49 => "49", 50 => "50", 51 => "51", 52 => "52", 53 => "53", 54 => "54", 55 => "55", 56 => "56", 57 => "57", 58 => "58", 59 => "59", 60 => "60", 61 => "61", 62 => "62", 63 => "63", 64 => "64", 65 => "65", 66 => "66", 67 => "67", 68 => "68", 69 => "69", 70 => "70", 71 => "71", 72 => "72", 73 => "73", 74 => "74", 75 => "75", 76 => "76", 77 => "77", 78 => "78", 79 => "79", 80 => "80", 81 => "81", 82 => "82", 83 => "83", 84 => "84", 85 => "85", 86 => "86", 87 => "87", 88 => "88", 89 => "89", 90 => "90", 91 => "91", 92 => "92", 93 => "93", 94 => "94", 95 => "95", 96 => "96", 97 => "97", 98 => "98", 99 => "99", 100 => "\306", 101 => "\305", 102 => "\301", 103 => "STARTA", 104 => "STARTB", 105 => "STARTC" }.invert } FNC1 = "\xc1" FNC2 = "\xc2" FNC3 = "\xc3" FNC4 = "\xc4" CODEA = "\xc5" CODEB = "\xc6" CODEC = "\xc7" STOP = '11000111010' TERMINATE = '11' attr_reader :type def initialize(data, type) self.type = type self.data = "#{data}" raise ArgumentError, 'Data not valid' unless valid? end def type=(type) type.upcase! raise ArgumentError, 'type must be A, B or C' unless type =~ /^[ABC]$/ @type = type end def to_s full_data end def data @data end #Returns the data for this barcode plus that for the entire extra chain, #excluding all change codes def full_data data + full_extra_data end #Returns the data for this barcode plus that for the entire extra chain, #including all change codes prefixing each extra def full_data_with_change_codes data + full_extra_data_with_change_code end #Returns the full_data for the extra or an empty string if there is no extra def full_extra_data return '' unless extra extra.full_data end #Returns the full_data for the extra with the change code for the extra #prepended. If there is no extra, an empty string is returned def full_extra_data_with_change_code return '' unless extra change_code_for(extra) + extra.full_data_with_change_codes end #Set the data for this barcode. If the barcode changes #character set, an extra will be created. def data=(data) data, *extra = data.split(/([#{CODEA+CODEB+CODEC}])/n) @data = data || '' self.extra = extra.join unless extra.empty? end #An "extra" is present if the barcode changes character set. If #a 128A barcode changes to C, the extra will be an instance of #Code128C. Extras can themselves have an extra if the barcode #changes character set again. It's like a linked list, and when #there are no more extras, the barcode ends with that object. #Most barcodes probably don't change charsets and don't have extras. def extra @extra end #Set the extra for this barcode. The argument is a string starting with the #"change character set" symbol. The string may contain several character #sets, in which case the extra will itself have an extra. def extra=(extra) raise ArgumentError, "Extra must begin with \\305, \\306 or \\307" unless extra =~ /^[#{CODEA+CODEB+CODEC}]/n type, data = extra[0,1], extra[1..-1] @extra = class_for(type).new(data) end #Get an array of the individual characters for this barcode. Special #characters like FNC1 will be present. Characters from extras are not #present. def characters chars = data.split(//n) if type == 'C' result = [] count = 0 while count < chars.size if chars[count] =~ /^\d$/ + #If encountering a digit, next char/byte *must* be second digit in pair. I.e. if chars[count] is 5, + #chars[count+1] must be /[0-9]/, otherwise it's not valid result << "#{chars[count]}#{chars[count+1]}" count += 2 else result << chars[count] count += 1 end end result else chars end end #Return the encoding of this barcode as a string of 1 and 0 def encoding start_encoding+data_encoding+extra_encoding+checksum_encoding+stop_encoding end #Returns the encoding for the data part of this barcode, without any extras def data_encoding characters.map do |char| encoding_for char end.join end #Returns the data encoding of this barcode and extras. def data_encoding_with_extra_encoding data_encoding+extra_encoding end #Returns the data encoding of this barcode's extra and its #extra until the barcode ends. def extra_encoding return '' unless extra change_code_encoding_for(extra) + extra.data_encoding + extra.extra_encoding end #Calculate the checksum for the data in this barcode. The data includes #data from extras. def checksum pos = 0 (numbers+extra_numbers).inject(start_num) do |sum,number| pos += 1 sum + (number * pos) end % 103 end #Get the encoding for the checksum def checksum_encoding encodings[checksum] end #protected #Returns the numeric values for the characters in the barcode in an array def numbers characters.map do |char| values[char] end end #Returns the numeric values for extras def extra_numbers return [] unless extra [change_code_number_for(extra)] + extra.numbers + extra.extra_numbers end def encodings ENCODINGS end #The start encoding starts the barcode def stop_encoding STOP+TERMINATE end #Find the encoding for the specified character for this barcode def encoding_for(char) encodings[values[char]] end def change_code_for_class(klass) {Code128A => CODEA, Code128B => CODEB, Code128C => CODEC}[klass] end #Find the character that changes the character set to the one #represented in +barcode+ def change_code_for(barcode) change_code_for_class(barcode.class) end #Find the numeric value for the character that changes the character #set to the one represented in +barcode+ def change_code_number_for(barcode) values[change_code_for(barcode)] end #Find the encoding to change to the character set in +barcode+ def change_code_encoding_for(barcode) encodings[change_code_number_for(barcode)] end def class_for(character) case character when 'A' then Code128A when 'B' then Code128B when 'C' then Code128C when CODEA then Code128A when CODEB then Code128B when CODEC then Code128C end end #Is the data in this barcode valid? Does a lookup of every character #and checks if it exists in the character set. An empty data string #will also be reported as invalid. def valid? characters.any? && characters.all?{|c| values.include?(c) } end def values VALUES[type] end def start_num values["START#{type}"] end def start_encoding encodings[start_num] end end class Code128A < Code128 def initialize(data) super(data, 'A') end end class Code128B < Code128 def initialize(data) super(data, 'B') end end class Code128C < Code128 def initialize(data) super(data, 'C') end end end
toretore/barby
9afbe4fbcc1fdd4bff070fa603840b7d78ad939f
Don't automatically require all symbologies
diff --git a/README b/README index d231c8f..1ed30a2 100644 --- a/README +++ b/README @@ -1,62 +1,91 @@ +*** NEW REQUIRE POLICY *** + +Barcode symbologies are no longer requires automatically, so you'll have to +require the ones you need. If you need EAN-13, require 'barby/barcode/ean_13'. +Full list of symbologies and filenames below. + +*** + Barby is a Ruby library that generates barcodes in a variety of symbologies. Its functionality is split into barcode and "outputter" objects. Barcode objects turn data into a binary representation for a given symbology. Outputters then take this representation and turns it into images, PDF, etc. You can easily add a symbology without having to worry about graphical representation. If it can be represented as the usual 1D or 2D matrix of lines or squares, outputters will do that for you. Likewise, you can easily add an outputter for a format that doesn't have one yet, and it will work with all existing symbologies. See Barby::Barcode and Barby::Outputter for more information. require 'barby' + require 'barby/barcode/code_128' require 'barby/outputter/ascii_outputter' barcode = Barby::Code128B.new('BARBY') puts barcode.to_ascii #Implicitly uses the AsciiOutputter ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## B A R B Y Supported symbologies: -* Code 25 - * Interleaved - * IATA -* Code 39 -* Code 93 -* Code 128 - * GS1 128 -* EAN-13 - * Bookland - * UPC-A -* EAN-8 -* UPC/EAN supplemental, 2 & 5 digits +Name - filename - dependencies + +require 'barby/barcode/<filename>' + +* Code 25 - code_25 + * Interleaved - code_25_interleaved + * IATA - code_25_iata +* Code 39 - code_39 +* Code 93 - code_93 +* Code 128 - code_128 + * GS1 128 - gs1_128 +* EAN-13 - ean_13 + * Bookland - bookland + * UPC-A - ean_13 +* EAN-8 - ean_8 +* UPC/EAN supplemental, 2 & 5 digits - upc_supplemental -* QR Code -* DataMatrix (Semacode) -* PDF417 (requires JRuby) +* QR Code - qr_code - rqrcode +* DataMatrix (Semacode) - data_matrix - semacode +* PDF417 - pdf_417 - java (JRuby) Formats supported by outputters: * Text (mostly for testing) * PNG, JPEG, GIF * PS, EPS * SVG * PDF * HTML + + +Outputters: + +filename (dependencies) + +require 'barby/outputter/<filename>_outputter' + +* ascii +* cairo (cairo) +* html +* pdfwriter +* png (chunky_png) +* prawn (prawn) +* rmagick (RMagick) +* svg diff --git a/lib/barby.rb b/lib/barby.rb index 634119b..06a410b 100644 --- a/lib/barby.rb +++ b/lib/barby.rb @@ -1,17 +1,4 @@ require 'barby/vendor' require 'barby/version' - require 'barby/barcode' -require 'barby/barcode/code_128' -require 'barby/barcode/gs1_128' -require 'barby/barcode/code_39' -require 'barby/barcode/code_93' -require 'barby/barcode/ean_13' -require 'barby/barcode/ean_8' -require 'barby/barcode/upc_supplemental' -require 'barby/barcode/bookland' -require 'barby/barcode/code_25' -require 'barby/barcode/code_25_interleaved' -require 'barby/barcode/code_25_iata' - require 'barby/outputter' diff --git a/test/bookland_test.rb b/test/bookland_test.rb index 312d14c..5e9b82d 100644 --- a/test/bookland_test.rb +++ b/test/bookland_test.rb @@ -1,57 +1,58 @@ require 'test_helper' +require 'barby/barcode/bookland' class BooklandTest < Barby::TestCase before do @isbn = '968-26-1240-3' @code = Bookland.new(@isbn) end it "should not touch the ISBN" do @code.isbn.must_equal @isbn end it "should have an isbn_only" do @code.isbn_only.must_equal '968261240' end it "should have the expected data" do @code.data.must_equal '978968261240' end it "should have the expected numbers" do @code.numbers.must_equal [9,7,8,9,6,8,2,6,1,2,4,0] end it "should have the expected checksum" do @code.checksum.must_equal 4 end it "should raise an error when data not valid" do lambda{ Bookland.new('1234') }.must_raise ArgumentError end describe 'ISBN conversion' do it "should accept ISBN with number system and check digit" do code = Bookland.new('978-82-92526-14-9') assert code.valid? code.data.must_equal '978829252614' end it "should accept ISBN without number system but with check digit" do code = Bookland.new('82-92526-14-9') assert code.valid? code.data.must_equal '978829252614' end it "should accept ISBN without number system or check digit" do code = Bookland.new('82-92526-14') assert code.valid? code.data.must_equal '978829252614' end end end diff --git a/test/code_128_test.rb b/test/code_128_test.rb index 8bca9ad..802a760 100644 --- a/test/code_128_test.rb +++ b/test/code_128_test.rb @@ -1,358 +1,359 @@ # encoding: UTF-8 require 'test_helper' +require 'barby/barcode/code_128' class Code128Test < Barby::TestCase before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do @code.send(:stop_encoding).must_equal '1100011101011' end it "should find the right class for a character A, B or C" do @code.send(:class_for, 'A').must_equal Code128A @code.send(:class_for, 'B').must_equal Code128B @code.send(:class_for, 'C').must_equal Code128C end it "should find the right change code for a class" do @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC end it "should not allow empty data" do lambda{ Code128B.new("") }.must_raise(ArgumentError) end describe "single encoding" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do @code.data.must_equal @data end it "should be able to change its data" do @code.data = '123ABC' @code.data.must_equal '123ABC' @code.data.wont_equal @data end it "should not have an extra" do assert @code.extra.nil? end it "should have empty extra encoding" do @code.extra_encoding.must_equal '' end it "should have the correct checksum" do @code.checksum.must_equal 66 end it "should return all data for to_s" do @code.to_s.must_equal @data end end describe "multiple encodings" do before do @data = binary_encode("ABC123\306def\3074567") @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do @code.full_data.must_equal "ABC123def4567" end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do @code.full_data_with_change_codes.must_equal @data end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = binary_encode("\3071234") code.full_data.must_equal "ABC1234" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234") code.extra.extra = binary_encode("\306abc") code.full_data.must_equal "ABC1234abc" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc") code.extra.extra.data = binary_encode("abc\305DEF") code.full_data.must_equal "ABC1234abcDEF" code.full_data_with_change_codes.must_equal binary_encode("ABC\3071234\306abc\305DEF") code.extra.extra.full_data.must_equal "abcDEF" code.extra.extra.full_data_with_change_codes.must_equal binary_encode("abc\305DEF") code.extra.full_data.must_equal "1234abcDEF" code.extra.full_data_with_change_codes.must_equal binary_encode("1234\306abc\305DEF") end it "should have a Code B extra" do @code.extra.must_be_instance_of(Code128B) end it "should have a valid extra" do assert @code.extra.valid? end it "the extra should also have an extra of type C" do @code.extra.extra.must_be_instance_of(Code128C) end it "the extra's extra should be valid" do assert @code.extra.extra.valid? end it "should not have more than two extras" do assert @code.extra.extra.extra.nil? end it "should split extra data from string on data assignment" do @code.data = binary_encode("123\306abc") @code.data.must_equal '123' @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal 'abc' end it "should be be able to change its extra" do @code.extra = binary_encode("\3071234") @code.extra.must_be_instance_of(Code128C) @code.extra.data.must_equal '1234' end it "should split extra data from string on extra assignment" do @code.extra = binary_encode("\306123\3074567") @code.extra.must_be_instance_of(Code128B) @code.extra.data.must_equal '123' @code.extra.extra.must_be_instance_of(Code128C) @code.extra.extra.data.must_equal '4567' end it "should not fail on newlines in extras" do code = Code128B.new(binary_encode("ABC\305\n")) code.data.must_equal "ABC" code.extra.must_be_instance_of(Code128A) code.extra.data.must_equal "\n" code.extra.extra = binary_encode("\305\n\n\n\n\n\nVALID") code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" end it "should raise an exception when extra string doesn't start with the special code character" do lambda{ @code.extra = '123' }.must_raise ArgumentError end it "should have the correct checksum" do @code.checksum.must_equal 84 end it "should have the expected encoding" do #STARTA A B C 1 2 3 @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ #CODEB d e f '10111101110100001001101011001000010110000100'+ #CODEC 45 67 '101110111101011101100010000101100'+ #CHECK=84 STOP '100111101001100011101011' end it "should return all data including extras, except change codes for to_s" do @code.to_s.must_equal "ABC123def4567" end end describe "128A" do before do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = 'abc123' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(A B C 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010000100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10010000110' end end describe "128B" do before do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = binary_encode("abc£123") refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(a b c 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010010000' end it "should have the expected data encoding" do @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '11011101110' end end describe "128C" do before do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do assert @code.valid? end it "should not be valid when given invalid data" do @code.data = '123' refute @code.valid? @code.data = 'abc' refute @code.valid? end it "should have the expected characters" do @code.characters.must_equal %w(12 34 56) end it "should have the expected start encoding" do @code.start_encoding.must_equal '11010011100' end it "should have the expected data encoding" do @code.data_encoding.must_equal '101100111001000101100011100010110' end it "should have the expected encoding" do @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.must_equal '10001101110' end end describe "Function characters" do it "should retain the special symbols in the data accessor" do Code128A.new(binary_encode("\301ABC\301DEF")).data.must_equal binary_encode("\301ABC\301DEF") Code128B.new(binary_encode("\301ABC\302DEF")).data.must_equal binary_encode("\301ABC\302DEF") Code128C.new(binary_encode("\301123456")).data.must_equal binary_encode("\301123456") Code128C.new(binary_encode("12\30134\30156")).data.must_equal binary_encode("12\30134\30156") end it "should keep the special symbols as characters" do Code128A.new(binary_encode("\301ABC\301DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \301 D E F)) Code128B.new(binary_encode("\301ABC\302DEF")).characters.must_equal binary_encode_array(%W(\301 A B C \302 D E F)) Code128C.new(binary_encode("\301123456")).characters.must_equal binary_encode_array(%W(\301 12 34 56)) Code128C.new(binary_encode("12\30134\30156")).characters.must_equal binary_encode_array(%W(12 \301 34 \301 56)) end it "should not allow FNC > 1 for Code C" do lambda{ Code128C.new("12\302") }.must_raise ArgumentError lambda{ Code128C.new("\30312") }.must_raise ArgumentError lambda{ Code128C.new("12\304") }.must_raise ArgumentError end it "should be included in the encoding" do a = Code128A.new(binary_encode("\301AB")) a.data_encoding.must_equal '111101011101010001100010001011000' a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' end end describe "Code128 with type" do it "should raise an exception when not given a type" do lambda{ Code128.new('abc') }.must_raise(ArgumentError) end it "should raise an exception when given a non-existent type" do lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) end it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' end end private def binary_encode_array(datas) datas.each { |data| binary_encode(data) } end def binary_encode(data) ruby_19_or_greater? ? data.force_encoding('BINARY') : data end end diff --git a/test/code_25_iata_test.rb b/test/code_25_iata_test.rb index 5f53e10..14715cb 100644 --- a/test/code_25_iata_test.rb +++ b/test/code_25_iata_test.rb @@ -1,18 +1,19 @@ require 'test_helper' +require 'barby/barcode/code_25_iata' class Code25IATATest < Barby::TestCase before do @data = '0123456789' @code = Code25IATA.new(@data) end it "should have the expected start_encoding" do @code.start_encoding.must_equal '1010' end it "should have the expected stop_encoding" do @code.stop_encoding.must_equal '11101' end end diff --git a/test/code_25_interleaved_test.rb b/test/code_25_interleaved_test.rb index c15de9b..f9bc5e6 100644 --- a/test/code_25_interleaved_test.rb +++ b/test/code_25_interleaved_test.rb @@ -1,115 +1,116 @@ require 'test_helper' +require 'barby/barcode/code_25_interleaved' class Code25InterleavedTest < Barby::TestCase before do @data = '12345670' @code = Code25Interleaved.new(@data) end it "should have the expected digit_pairs" do @code.digit_pairs.must_equal [[1,2],[3,4],[5,6],[7,0]] end it "should have the expected digit_encodings" do @code.digit_encodings.must_equal %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110) end it "should have the expected start_encoding" do @code.start_encoding.must_equal '1010' end it "should have the expected stop_encoding" do @code.stop_encoding.must_equal '11101' end it "should have the expected data_encoding" do @code.data_encoding.must_equal "111010001010111000111011101000101000111010001110001010101010001110001110" end it "should have the expected encoding" do @code.encoding.must_equal "101011101000101011100011101110100010100011101000111000101010101000111000111011101" end it "should be valid" do assert @code.valid? end it "should return the expected encoding for parameters passed to encoding_for_interleaved" do w, n = Code25Interleaved::WIDE, Code25Interleaved::NARROW # 1 2 1 2 1 2 1 2 1 2 digits 1 and 2 # B S B S B S B S B S bars and spaces @code.encoding_for_interleaved(w,n,n,w,n,n,n,n,w,w).must_equal '111010001010111000' # 3 4 3 4 3 4 3 4 3 4 digits 3 and 4 # B S B S B S B S B S bars and spaces @code.encoding_for_interleaved(w,n,w,n,n,w,n,n,n,w).must_equal '111011101000101000' end it "should return all characters in sequence for to_s" do @code.to_s.must_equal @code.characters.join end describe "with checksum" do before do @data = '1234567' @code = Code25Interleaved.new(@data) @code.include_checksum = true end it "should have the expected digit_pairs_with_checksum" do @code.digit_pairs_with_checksum.must_equal [[1,2],[3,4],[5,6],[7,0]] end it "should have the expected digit_encodings_with_checksum" do @code.digit_encodings_with_checksum.must_equal %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110) end it "should have the expected data_encoding_with_checksum" do @code.data_encoding_with_checksum.must_equal "111010001010111000111011101000101000111010001110001010101010001110001110" end it "should have the expected encoding" do @code.encoding.must_equal "101011101000101011100011101110100010100011101000111000101010101000111000111011101" end it "should be valid" do assert @code.valid? end it "should return all characters including checksum in sequence on to_s" do @code.to_s.must_equal @code.characters_with_checksum.join end end describe "with invalid number of digits" do before do @data = '1234567' @code = Code25Interleaved.new(@data) end it "should not be valid" do refute @code.valid? end it "should raise ArgumentError on all encoding methods" do lambda{ @code.encoding }.must_raise(ArgumentError) lambda{ @code.data_encoding }.must_raise(ArgumentError) lambda{ @code.digit_encodings }.must_raise(ArgumentError) end it "should not raise ArgumentError on encoding methods that include checksum" do b = Code25Interleaved.new(@data) b.include_checksum = true b.encoding @code.data_encoding_with_checksum @code.digit_encodings_with_checksum end end end diff --git a/test/code_25_test.rb b/test/code_25_test.rb index ec99f44..2264bfe 100644 --- a/test/code_25_test.rb +++ b/test/code_25_test.rb @@ -1,109 +1,110 @@ require 'test_helper' +require 'barby/barcode/code_25' class Code25Test < Barby::TestCase before do @data = "1234567" @code = Code25.new(@data) end it "should return the same data it was given" do @code.data.must_equal @data end it "should have the expected characters" do @code.characters.must_equal %w(1 2 3 4 5 6 7) end it "should have the expected characters_with_checksum" do @code.characters_with_checksum.must_equal %w(1 2 3 4 5 6 7 0) end it "should have the expected digits" do @code.digits.must_equal [1,2,3,4,5,6,7] end it "should have the expected digits_with_checksum" do @code.digits_with_checksum.must_equal [1,2,3,4,5,6,7,0] end it "should have the expected even_and_odd_digits" do @code.even_and_odd_digits.must_equal [[7,5,3,1], [6,4,2]] end it "should have the expected start_encoding" do @code.start_encoding.must_equal '1110111010' end it "should have the expected stop_encoding" do @code.stop_encoding.must_equal '111010111' end it "should have a default narrow_width of 1" do @code.narrow_width.must_equal 1 end it "should have a default wide_width equal to narrow_width * 3" do @code.wide_width.must_equal @code.narrow_width * 3 @code.narrow_width = 2 @code.wide_width.must_equal 6 end it "should have a default space_width equal to narrow_width" do @code.space_width.must_equal @code.narrow_width @code.narrow_width = 23 @code.space_width.must_equal 23 end it "should have the expected digit_encodings" do @code.digit_encodings.must_equal %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110) end it "should have the expected digit_encodings_with_checksum" do @code.digit_encodings_with_checksum.must_equal %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110 10101110111010) end it "should have the expected data_encoding" do @code.data_encoding.must_equal "11101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110" end it "should have the expected checksum" do @code.checksum.must_equal 0 end it "should have the expected checksum_encoding" do @code.checksum_encoding.must_equal '10101110111010' end it "should have the expected encoding" do @code.encoding.must_equal "111011101011101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110111010111" end it "should be valid" do assert @code.valid? end it "should not be valid" do @code.data = 'abc' refute @code.valid? end it "should raise on encoding methods that include data encoding if not valid" do @code.data = 'abc' lambda{ @code.encoding }.must_raise ArgumentError lambda{ @code.data_encoding }.must_raise ArgumentError lambda{ @code.data_encoding_with_checksum }.must_raise ArgumentError lambda{ @code.digit_encodings }.must_raise ArgumentError lambda{ @code.digit_encodings_with_checksum }.must_raise ArgumentError end it "should return all characters in sequence on to_s" do @code.to_s.must_equal @code.characters.join end it "should include checksum in to_s when include_checksum is true" do @code.include_checksum = true @code.to_s.must_equal @code.characters_with_checksum.join end end diff --git a/test/code_39_test.rb b/test/code_39_test.rb index 289632b..2fff220 100644 --- a/test/code_39_test.rb +++ b/test/code_39_test.rb @@ -1,208 +1,209 @@ require 'test_helper' +require 'barby/barcode/code_39' class Code39Test < Barby::TestCase before do @data = 'TEST8052' @code = Code39.new(@data) @code.spacing = 3 end it "should yield self on initialize" do c1 = nil c2 = Code39.new('TEST'){|c| c1 = c } c1.must_equal c2 end it "should have the expected data" do @code.data.must_equal @data end it "should have the expected characters" do @code.characters.must_equal @data.split(//) end it "should have the expected start_encoding" do @code.start_encoding.must_equal '100101101101' end it "should have the expected stop_encoding" do @code.stop_encoding.must_equal '100101101101' end it "should have the expected spacing_encoding" do @code.spacing_encoding.must_equal '000' end it "should have the expected encoded characters" do @code.encoded_characters.must_equal %w(101011011001 110101100101 101101011001 101011011001 110100101101 101001101101 110100110101 101100101011) end it "should have the expected data_encoding" do @code.data_encoding.must_equal '101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011' end it "should have the expected encoding" do @code.encoding.must_equal '100101101101000101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011000100101101101' end it "should be valid" do assert @code.valid? end it "should not be valid" do @code.data = "123\200456" refute @code.valid? end it "should raise an exception when data is not valid on initialization" do lambda{ Code39.new('abc') }.must_raise(ArgumentError) end it "should return all characters in sequence without checksum on to_s" do @code.to_s.must_equal @data end describe "Checksumming" do before do @code = Code39.new('CODE39') end it "should have the expected checksum" do @code.checksum.must_equal 32 end it "should have the expected checksum_character" do @code.checksum_character.must_equal 'W' end it "should have the expected checksum_encoding" do @code.checksum_encoding.must_equal '110011010101' end it "should have the expected characters_with_checksum" do @code.characters_with_checksum.must_equal %w(C O D E 3 9 W) end it "should have the expected encoded_characters_with_checksum" do @code.encoded_characters_with_checksum.must_equal %w(110110100101 110101101001 101011001011 110101100101 110110010101 101100101101 110011010101) end it "should have the expected data_encoding_with_checksum" do @code.data_encoding_with_checksum.must_equal "110110100101011010110100101010110010110110101100101011011001010101011001011010110011010101" end it "should have the expected encoding_with_checksum" do @code.encoding_with_checksum.must_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" end it "should return the encoding with checksum when include_checksum == true" do @code.include_checksum = true @code.encoding.must_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" end end describe "Normal encoding" do before do @data = 'ABC$%' @code = Code39.new(@data) end it "should have the expected characters" do @code.characters.must_equal %w(A B C $ %) end it "should have the expected encoded_characters" do @code.encoded_characters.must_equal %w(110101001011 101101001011 110110100101 100100100101 101001001001) end it "should have the expected data_encoding" do @code.data_encoding.must_equal '1101010010110101101001011011011010010101001001001010101001001001' end it "should not be valid" do @code.data = 'abc' refute @code.valid? end end describe "Extended encoding" do before do @data = '<abc>' @code = Code39.new(@data, true) end it "should return true on extended?" do assert @code.extended? end it "should have the expected characters" do @code.characters.must_equal %w(% G + A + B + C % I) end it "should have the expected encoded_characters" do @code.encoded_characters.must_equal %w(101001001001 101010011011 100101001001 110101001011 100101001001 101101001011 100101001001 110110100101 101001001001 101101001101) end it "should have the expected data_encoding" do @code.data_encoding.must_equal '101001001001010101001101101001010010010110101001011010010100100101011010010110100101001001011011010010101010010010010101101001101' end it "should have the expected encoding" do @code.encoding.must_equal '10010110110101010010010010101010011011010010100100101101010010110100101001001'+ '010110100101101001010010010110110100101010100100100101011010011010100101101101' end it "should take a second parameter on initialize indicating it is extended" do assert Code39.new('abc', true).extended? refute Code39.new('ABC', false).extended? refute Code39.new('ABC').extended? end it "should be valid" do assert @code.valid? end it "should not be valid" do @code.data = "abc\200123" refute @code.valid? end it "should return all characters in sequence without checksum on to_s" do @code.to_s.must_equal @data end end describe "Variable widths" do before do @data = 'ABC$%' @code = Code39.new(@data) @code.narrow_width = 2 @code.wide_width = 5 end it "should have the expected encoded_characters" do @code.encoded_characters.must_equal %w(111110011001100000110011111 110011111001100000110011111 111110011111001100000110011 110000011000001100000110011 110011000001100000110000011) end it "should have the expected data_encoding" do # A SB SC S$ S% @code.data_encoding.must_equal '1111100110011000001100111110110011111001100000110011111011111001111100110000011001101100000110000011000001100110110011000001100000110000011' @code.spacing = 3 # A S B S C S $ S % @code.data_encoding.must_equal '111110011001100000110011111000110011111001100000110011111000111110011111001100000110011000110000011000001100000110011000110011000001100000110000011' end end end diff --git a/test/code_93_test.rb b/test/code_93_test.rb index d59203e..749b39b 100644 --- a/test/code_93_test.rb +++ b/test/code_93_test.rb @@ -1,142 +1,143 @@ require 'test_helper' +require 'barby/barcode/code_93' class Code93Test < Barby::TestCase before do @data = 'TEST93' @code = Code93.new(@data) end it "should return the same data we put in" do @code.data.must_equal @data end it "should have the expected characters" do @code.characters.must_equal @data.split(//) end it "should have the expected start_encoding" do @code.start_encoding.must_equal '101011110' end it "should have the expected stop_encoding" do # STOP TERM @code.stop_encoding.must_equal '1010111101' end it "should have the expected encoded characters" do # T E S T 9 3 @code.encoded_characters.must_equal %w(110100110 110010010 110101100 110100110 100001010 101000010) end it "should have the expected data_encoding" do # T E S T 9 3 @code.data_encoding.must_equal "110100110110010010110101100110100110100001010101000010" end it "should have the expected data_encoding_with_checksums" do # T E S T 9 3 + (C) 6 (K) @code.data_encoding_with_checksums.must_equal "110100110110010010110101100110100110100001010101000010101110110100100010" end it "should have the expected encoding" do # START T E S T 9 3 + (C) 6 (K) STOP TERM @code.encoding.must_equal "1010111101101001101100100101101011001101001101000010101010000101011101101001000101010111101" end it "should have the expected checksum_values" do @code.checksum_values.must_equal [29, 14, 28, 29, 9, 3].reverse #! end it "should have the expected c_checksum" do @code.c_checksum.must_equal 41 #calculate this first! end it "should have the expected c_checksum_character" do @code.c_checksum_character.must_equal '+' end it "should have the expected c_checksum_encoding" do @code.c_checksum_encoding.must_equal '101110110' end it "should have the expected checksum_values_with_c_checksum" do @code.checksum_values_with_c_checksum.must_equal [29, 14, 28, 29, 9, 3, 41].reverse #! end it "should have the expected k_checksum" do @code.k_checksum.must_equal 6 #calculate this first! end it "should have the expected k_checksum_character" do @code.k_checksum_character.must_equal '6' end it "should have the expected k_checksum_encoding" do @code.k_checksum_encoding.must_equal '100100010' end it "should have the expected checksums" do @code.checksums.must_equal [41, 6] end it "should have the expected checksum_characters" do @code.checksum_characters.must_equal ['+', '6'] end it "should have the expected checksum_encodings" do @code.checksum_encodings.must_equal %w(101110110 100100010) end it "should have the expected checksum_encoding" do @code.checksum_encoding.must_equal '101110110100100010' end it "should be valid" do assert @code.valid? end it "should not be valid when not in extended mode" do @code.data = 'not extended' end it "should return data with no checksums on to_s" do @code.to_s.must_equal 'TEST93' end describe "Extended mode" do before do @data = "Extended!" @code = Code93.new(@data) end it "should be extended" do assert @code.extended? end it "should convert extended characters to special shift characters" do @code.characters.must_equal ["E", "\304", "X", "\304", "T", "\304", "E", "\304", "N", "\304", "D", "\304", "E", "\304", "D", "\303", "A"] end it "should have the expected data_encoding" do @code.data_encoding.must_equal '110010010100110010101100110100110010110100110100110010110010010'+ '100110010101000110100110010110010100100110010110010010100110010110010100111010110110101000' end it "should have the expected c_checksum" do @code.c_checksum.must_equal 9 end it "should have the expected k_checksum" do @code.k_checksum.must_equal 46 end it "should return the original data on to_s with no checksums" do @code.to_s.must_equal 'Extended!' end end end diff --git a/test/ean13_test.rb b/test/ean13_test.rb index a079f58..82222db 100644 --- a/test/ean13_test.rb +++ b/test/ean13_test.rb @@ -1,168 +1,169 @@ require 'test_helper' +require 'barby/barcode/ean_13' class EAN13Test < Barby::TestCase describe 'validations' do before do @valid = EAN13.new('123456789012') end it "should be valid with 12 digits" do assert @valid.valid? end it "should not be valid with non-digit characters" do @valid.data = "The shit apple doesn't fall far from the shit tree" refute @valid.valid? end it "should not be valid with less than 12 digits" do @valid.data = "12345678901" refute @valid.valid? end it "should not be valid with more than 12 digits" do @valid.data = "1234567890123" refute @valid.valid? end it "should raise an exception when data is invalid" do lambda{ EAN13.new('123') }.must_raise(ArgumentError) end end describe 'data' do before do @data = '007567816412' @code = EAN13.new(@data) end it "should have the same data as was passed to it" do @code.data.must_equal @data end it "should have the expected characters" do @code.characters.must_equal @data.split(//) end it "should have the expected numbers" do @code.numbers.must_equal @data.split(//).map{|s| s.to_i } end it "should have the expected odd_and_even_numbers" do @code.odd_and_even_numbers.must_equal [[2,4,1,7,5,0], [1,6,8,6,7,0]] end it "should have the expected left_numbers" do #0=second number in number system code @code.left_numbers.must_equal [0,7,5,6,7,8] end it "should have the expected right_numbers" do @code.right_numbers.must_equal [1,6,4,1,2,5]#5=checksum end it "should have the expected numbers_with_checksum" do @code.numbers_with_checksum.must_equal @data.split(//).map{|s| s.to_i } + [5] end it "should have the expected data_with_checksum" do @code.data_with_checksum.must_equal @data+'5' end it "should return all digits and the checksum on to_s" do @code.to_s.must_equal '0075678164125' end end describe 'checksum' do before do @code = EAN13.new('007567816412') end it "should have the expected weighted_sum" do @code.weighted_sum.must_equal 85 @code.data = '007567816413' @code.weighted_sum.must_equal 88 end it "should have the correct checksum" do @code.checksum.must_equal 5 @code.data = '007567816413' @code.checksum.must_equal 2 end it "should have the correct checksum_encoding" do @code.checksum_encoding.must_equal '1001110' end end describe 'encoding' do before do @code = EAN13.new('750103131130') end it "should have the expected checksum" do @code.checksum.must_equal 9 end it "should have the expected checksum_encoding" do @code.checksum_encoding.must_equal '1110100' end it "should have the expected left_parity_map" do @code.left_parity_map.must_equal [:odd, :even, :odd, :even, :odd, :even] end it "should have the expected left_encodings" do @code.left_encodings.must_equal %w(0110001 0100111 0011001 0100111 0111101 0110011) end it "should have the expected right_encodings" do @code.right_encodings.must_equal %w(1000010 1100110 1100110 1000010 1110010 1110100) end it "should have the expected left_encoding" do @code.left_encoding.must_equal '011000101001110011001010011101111010110011' end it "should have the expected right_encoding" do @code.right_encoding.must_equal '100001011001101100110100001011100101110100' end it "should have the expected encoding" do #Start Left Center Right Stop @code.encoding.must_equal '101' + '011000101001110011001010011101111010110011' + '01010' + '100001011001101100110100001011100101110100' + '101' end end describe 'static data' do before :each do @code = EAN13.new('123456789012') end it "should have the expected start_encoding" do @code.start_encoding.must_equal '101' end it "should have the expected stop_encoding" do @code.stop_encoding.must_equal '101' end it "should have the expected center_encoding" do @code.center_encoding.must_equal '01010' end end end diff --git a/test/ean8_test.rb b/test/ean8_test.rb index 88bd1d3..db72edd 100644 --- a/test/ean8_test.rb +++ b/test/ean8_test.rb @@ -1,99 +1,100 @@ require 'test_helper' +require 'barby/barcode/ean_8' class EAN8Test < Barby::TestCase describe 'validations' do before do @valid = EAN8.new('1234567') end it "should be valid with 7 digits" do assert @valid.valid? end it "should not be valid with less than 7 digits" do @valid.data = '123456' refute @valid.valid? end it "should not be valid with more than 7 digits" do @valid.data = '12345678' refute @valid.valid? end it "should not be valid with non-digits" do @valid.data = 'abcdefg' refute @valid.valid? end end describe 'checksum' do before :each do @code = EAN8.new('5512345') end it "should have the expected weighted_sum" do @code.weighted_sum.must_equal 53 end it "should have the expected checksum" do @code.checksum.must_equal 7 end end describe 'data' do before :each do @data = '5512345' @code = EAN8.new(@data) end it "should have the expected data" do @code.data.must_equal @data end it "should have the expected odd_and_even_numbers" do @code.odd_and_even_numbers.must_equal [[5,3,1,5],[4,2,5]] end it "should have the expected left_numbers" do #EAN-8 includes the first character in the left-hand encoding, unlike EAN-13 @code.left_numbers.must_equal [5,5,1,2] end it "should have the expected right_numbers" do @code.right_numbers.must_equal [3,4,5,7] end it "should return the data with checksum on to_s" do @code.to_s.must_equal '55123457' end end describe 'encoding' do before :each do @code = EAN8.new('5512345') end it "should have the expected left_parity_map" do @code.left_parity_map.must_equal [:odd, :odd, :odd, :odd] end it "should have the expected left_encoding" do @code.left_encoding.must_equal '0110001011000100110010010011' end it "should have the expected right_encoding" do @code.right_encoding.must_equal '1000010101110010011101000100' end end end diff --git a/test/gs1_128_test.rb b/test/gs1_128_test.rb index 1aee0b4..bf3575e 100644 --- a/test/gs1_128_test.rb +++ b/test/gs1_128_test.rb @@ -1,66 +1,67 @@ require 'test_helper' +require 'barby/barcode/gs1_128' class GS1128Test < Barby::TestCase before do @code = GS1128.new('071230', 'C', '11') end it "should inherit Code128" do GS1128.superclass.must_equal Code128 end it "should have an application_identifier attribute" do @code.must_respond_to(:application_identifier) @code.must_respond_to(:application_identifier=) end it "should have the given application identifier" do @code.application_identifier.must_equal '11' end it "should have an application_identifier_encoding" do @code.must_respond_to(:application_identifier_encoding) end it "should have the expected application_identifier_number" do @code.application_identifier_number.must_equal 11 end it "should have the expected application identifier encoding" do @code.application_identifier_encoding.must_equal '11000100100'#Code C number 11 end it "should have data with FNC1 and AI" do @code.data.must_equal "\30111071230" end it "should have partial_data without FNC1 or AI" do @code.partial_data.must_equal '071230' end it "should have characters that include FNC1 and AI" do @code.characters.must_equal %W(\301 11 07 12 30) end it "should have data_encoding that includes FNC1 and the AI" do @code.data_encoding.must_equal '1111010111011000100100100110001001011001110011011011000' end it "should have the expected checksum" do @code.checksum.must_equal 36 end it "should have the expected checksum encoding" do @code.checksum_encoding == '10110001000' end it "should have the expected encoding" do @code.encoding.must_equal '110100111001111010111011000100100100110001001011001110011011011000101100010001100011101011' end it "should return full data excluding change codes, including AI on to_s" do @code.to_s.must_equal '(11) 071230' end end diff --git a/test/pdf_417_test.rb b/test/pdf_417_test.rb index 86a9569..7221b39 100644 --- a/test/pdf_417_test.rb +++ b/test/pdf_417_test.rb @@ -1,42 +1,45 @@ -require 'test_helper' - -class Pdf417 < Barby::TestCase +if defined? JRUBY_VERSION + require 'test_helper' require 'barby/barcode/pdf_417' - - it "should produce a nice code" do - enc = Pdf417.new('Ereshkigal').encoding - enc.must_equal [ - "111111111101010100101111010110011110100111010110001110100011101101011100100001111111101000110100100", - "111111111101010100101111010110000100100110100101110000101011111110101001111001111111101000110100100", - "111111111101010100101101010111111000100100011100110011111010101100001111100001111111101000110100100", - "111111111101010100101111101101111110110100010100011101111011010111110111111001111111101000110100100", - "111111111101010100101101011110000010100110010101110010100011101101110001110001111111101000110100100", - "111111111101010100101111101101110000110101101100000011110011110110111110111001111111101000110100100", - "111111111101010100101101001111001111100110001101001100100010100111101110100001111111101000110100100", - "111111111101010100101111110110010111100111100100101000110010101111111001111001111111101000110100100", - "111111111101010100101010011101111100100101111110001110111011111101001110110001111111101000110100100", - "111111111101010100101010001111011100100100111110111110111010100101100011100001111111101000110100100", - "111111111101010100101101001111000010100110001101110000101011101100111001110001111111101000110100100", - "111111111101010100101101000110011111100101111111011101100011111110100011100101111111101000110100100", - "111111111101010100101010000101010000100100011100001100101010100100110000111001111111101000110100100", - "111111111101010100101111010100100001100100010100111100101011110110001001100001111111101000110100100", - "111111111101010100101111010100011110110110011111101001100010100100001001111101111111101000110100100" - ] - enc.length.must_equal 15 - enc[0].length.must_equal 99 - end - it "should produce a 19x135 code with default aspect_ratio" do - enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3).encoding - enc.length.must_equal 19 - enc[0].length.must_equal 135 - end + class Pdf417Test < Barby::TestCase + + it "should produce a nice code" do + enc = Pdf417.new('Ereshkigal').encoding + enc.must_equal [ + "111111111101010100101111010110011110100111010110001110100011101101011100100001111111101000110100100", + "111111111101010100101111010110000100100110100101110000101011111110101001111001111111101000110100100", + "111111111101010100101101010111111000100100011100110011111010101100001111100001111111101000110100100", + "111111111101010100101111101101111110110100010100011101111011010111110111111001111111101000110100100", + "111111111101010100101101011110000010100110010101110010100011101101110001110001111111101000110100100", + "111111111101010100101111101101110000110101101100000011110011110110111110111001111111101000110100100", + "111111111101010100101101001111001111100110001101001100100010100111101110100001111111101000110100100", + "111111111101010100101111110110010111100111100100101000110010101111111001111001111111101000110100100", + "111111111101010100101010011101111100100101111110001110111011111101001110110001111111101000110100100", + "111111111101010100101010001111011100100100111110111110111010100101100011100001111111101000110100100", + "111111111101010100101101001111000010100110001101110000101011101100111001110001111111101000110100100", + "111111111101010100101101000110011111100101111111011101100011111110100011100101111111101000110100100", + "111111111101010100101010000101010000100100011100001100101010100100110000111001111111101000110100100", + "111111111101010100101111010100100001100100010100111100101011110110001001100001111111101000110100100", + "111111111101010100101111010100011110110110011111101001100010100100001001111101111111101000110100100" + ] + enc.length.must_equal 15 + enc[0].length.must_equal 99 + end - it "should produce a 29x117 code with 0.7 aspect_ratio" do - enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3, :aspect_ratio => 0.7).encoding - enc.length.must_equal 29 - enc[0].length.must_equal 117 + it "should produce a 19x135 code with default aspect_ratio" do + enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3).encoding + enc.length.must_equal 19 + enc[0].length.must_equal 135 + end + + it "should produce a 29x117 code with 0.7 aspect_ratio" do + enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3, :aspect_ratio => 0.7).encoding + enc.length.must_equal 29 + enc[0].length.must_equal 117 + end + end - -end if defined?(JRUBY_VERSION) + +end diff --git a/test/qr_code_test.rb b/test/qr_code_test.rb index bb89a4a..fc20644 100644 --- a/test/qr_code_test.rb +++ b/test/qr_code_test.rb @@ -1,77 +1,78 @@ require 'test_helper' +require 'barby/barcode/qr_code' class QrCodeTest < Barby::TestCase before do @data = 'Ereshkigal' @code = QrCode.new(@data) end it "should have the expected data" do @code.data.must_equal @data end it "should have the expected encoding" do # Should be an array of strings, where each string represents a "line" @code.encoding.must_equal(rqrcode(@code).modules.map do |line| line.inject(''){|s,m| s << (m ? '1' : '0') } end) end it "should be able to change its data and output a different encoding" do @code.data = 'hades' @code.data.must_equal 'hades' @code.encoding.must_equal(rqrcode(@code).modules.map do |line| line.inject(''){|s,m| s << (m ? '1' : '0') } end) end it "should have a 'level' accessor" do @code.must_respond_to :level @code.must_respond_to :level= end it "should set size according to size of data" do QrCode.new('1'*15, :level => :l).size.must_equal 1 QrCode.new('1'*15, :level => :m).size.must_equal 2 QrCode.new('1'*15, :level => :q).size.must_equal 2 QrCode.new('1'*15, :level => :h).size.must_equal 3 QrCode.new('1'*30, :level => :l).size.must_equal 2 QrCode.new('1'*30, :level => :m).size.must_equal 3 QrCode.new('1'*30, :level => :q).size.must_equal 3 QrCode.new('1'*30, :level => :h).size.must_equal 4 QrCode.new('1'*270, :level => :l).size.must_equal 10 end it "should allow size to be set manually" do code = QrCode.new('1'*15, :level => :l, :size => 2) code.size.must_equal 2 code.encoding.must_equal(rqrcode(code).modules.map do |line| line.inject(''){|s,m| s << (m ? '1' : '0') } end) end it "should raise ArgumentError when data too large" do assert QrCode.new('1'*2953, :level => :l) lambda{ QrCode.new('1'*2954, :level => :l) }.must_raise ArgumentError end it "should return the original data on to_s" do @code.to_s.must_equal 'Ereshkigal' end it "should include at most 20 characters on to_s" do QrCode.new('123456789012345678901234567890').to_s.must_equal '12345678901234567890' end private def rqrcode(code) RQRCode::QRCode.new(code.data, :level => code.level, :size => code.size) end end diff --git a/test/upc_supplemental_test.rb b/test/upc_supplemental_test.rb index cb209ef..3776fa7 100644 --- a/test/upc_supplemental_test.rb +++ b/test/upc_supplemental_test.rb @@ -1,108 +1,109 @@ require 'test_helper' +require 'barby/barcode/upc_supplemental' class UpcSupplementalTest < Barby::TestCase it 'should be valid with 2 or 5 digits' do assert UPCSupplemental.new('12345').valid? assert UPCSupplemental.new('12').valid? end it 'should not be valid with any number of digits other than 2 or 5' do refute UPCSupplemental.new('1234').valid? refute UPCSupplemental.new('123').valid? refute UPCSupplemental.new('1').valid? refute UPCSupplemental.new('123456').valid? refute UPCSupplemental.new('123456789012').valid? end it 'should not be valid with non-digit characters' do refute UPCSupplemental.new('abcde').valid? refute UPCSupplemental.new('ABC').valid? refute UPCSupplemental.new('1234e').valid? refute UPCSupplemental.new('!2345').valid? refute UPCSupplemental.new('ab').valid? refute UPCSupplemental.new('1b').valid? refute UPCSupplemental.new('a1').valid? end describe 'checksum for 5 digits' do it 'should have the expected odd_digits' do UPCSupplemental.new('51234').odd_digits.must_equal [4,2,5] UPCSupplemental.new('54321').odd_digits.must_equal [1,3,5] UPCSupplemental.new('99990').odd_digits.must_equal [0,9,9] end it 'should have the expected even_digits' do UPCSupplemental.new('51234').even_digits.must_equal [3,1] UPCSupplemental.new('54321').even_digits.must_equal [2,4] UPCSupplemental.new('99990').even_digits.must_equal [9,9] end it 'should have the expected odd and even sums' do UPCSupplemental.new('51234').odd_sum.must_equal 33 UPCSupplemental.new('54321').odd_sum.must_equal 27 UPCSupplemental.new('99990').odd_sum.must_equal 54 UPCSupplemental.new('51234').even_sum.must_equal 36 UPCSupplemental.new('54321').even_sum.must_equal 54 UPCSupplemental.new('99990').even_sum.must_equal 162 end it 'should have the expected checksum' do UPCSupplemental.new('51234').checksum.must_equal 9 UPCSupplemental.new('54321').checksum.must_equal 1 UPCSupplemental.new('99990').checksum.must_equal 6 end end describe 'checksum for 2 digits' do it 'should have the expected checksum' do UPCSupplemental.new('51').checksum.must_equal 3 UPCSupplemental.new('21').checksum.must_equal 1 UPCSupplemental.new('99').checksum.must_equal 3 end end describe 'encoding' do before do @data = '51234' @code = UPCSupplemental.new(@data) end it 'should have the expected encoding' do # START 5 1 2 3 4 UPCSupplemental.new('51234').encoding.must_equal '1011 0110001 01 0011001 01 0011011 01 0111101 01 0011101'.tr(' ', '') # 9 9 9 9 0 UPCSupplemental.new('99990').encoding.must_equal '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') # START 5 1 UPCSupplemental.new('51').encoding.must_equal '1011 0111001 01 0110011'.tr(' ', '') # 2 2 UPCSupplemental.new('22').encoding.must_equal '1011 0011011 01 0010011'.tr(' ', '') end it 'should be able to change its data' do prev_encoding = @code.encoding @code.data = '99990' @code.encoding.wont_equal prev_encoding # 9 9 9 9 0 @code.encoding.must_equal '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') prev_encoding = @code.encoding @code.data = '22' @code.encoding.wont_equal prev_encoding # 2 2 @code.encoding.must_equal '1011 0011011 01 0010011'.tr(' ', '') end end end
toretore/barby
639e0bcaa053e14a5f66337f518f30747b98d426
0.4.5 - Don't automatically require qr_code, which needs rqrcode
diff --git a/lib/barby.rb b/lib/barby.rb index b6c9849..634119b 100644 --- a/lib/barby.rb +++ b/lib/barby.rb @@ -1,18 +1,17 @@ require 'barby/vendor' require 'barby/version' require 'barby/barcode' require 'barby/barcode/code_128' require 'barby/barcode/gs1_128' require 'barby/barcode/code_39' require 'barby/barcode/code_93' require 'barby/barcode/ean_13' require 'barby/barcode/ean_8' require 'barby/barcode/upc_supplemental' require 'barby/barcode/bookland' -require 'barby/barcode/qr_code' require 'barby/barcode/code_25' require 'barby/barcode/code_25_interleaved' require 'barby/barcode/code_25_iata' require 'barby/outputter' diff --git a/lib/barby/version.rb b/lib/barby/version.rb index 484a415..6e29fa8 100644 --- a/lib/barby/version.rb +++ b/lib/barby/version.rb @@ -1,9 +1,9 @@ module Barby #:nodoc: module VERSION #:nodoc: MAJOR = 0 MINOR = 4 - TINY = 4 + TINY = 5 STRING = [MAJOR, MINOR, TINY].join('.') end end
toretore/barby
ea1c9e19b9d09f1f35851f47a51302b4b47044b4
Add supported formats
diff --git a/README b/README index 13d3bca..d231c8f 100644 --- a/README +++ b/README @@ -1,51 +1,62 @@ Barby is a Ruby library that generates barcodes in a variety of symbologies. Its functionality is split into barcode and "outputter" objects. Barcode objects turn data into a binary representation for a given symbology. Outputters then take this representation and turns it into images, PDF, etc. You can easily add a symbology without having to worry about graphical representation. If it can be represented as the usual 1D or 2D matrix of lines or squares, outputters will do that for you. Likewise, you can easily add an outputter for a format that doesn't have one yet, and it will work with all existing symbologies. See Barby::Barcode and Barby::Outputter for more information. require 'barby' require 'barby/outputter/ascii_outputter' barcode = Barby::Code128B.new('BARBY') puts barcode.to_ascii #Implicitly uses the AsciiOutputter ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## B A R B Y + Supported symbologies: * Code 25 * Interleaved * IATA * Code 39 * Code 93 * Code 128 * GS1 128 * EAN-13 * Bookland * UPC-A * EAN-8 * UPC/EAN supplemental, 2 & 5 digits * QR Code * DataMatrix (Semacode) * PDF417 (requires JRuby) + + +Formats supported by outputters: + +* Text (mostly for testing) +* PNG, JPEG, GIF +* PS, EPS +* SVG +* PDF +* HTML
toretore/barby
581b7a08fb494a68babbfd43a9e543dda2869ff6
Remove lie.
diff --git a/README b/README index de65a39..5d9dbd6 100644 --- a/README +++ b/README @@ -1,29 +1,28 @@ -Barby is a Ruby barcode generator. It does not depend on other libraries -(for the core functionality) and is easily extentable. +Barby is a Ruby barcode generator. It is easily extendable. The barcode objects are separated from the process of generating graphical (or other) representations. A barcode's only responsibility is to provide a string representation consisting of 1s and 0s representing bars and spaces. This string can then be used to generate (for example) an image with the RMagickOutputter, or an ASCII string such as the one below. See Barby::Barcode and Barby::Outputter for more information. require 'barby' require 'barby/outputter/ascii_outputter' barcode = Barby::Code128B.new('BARBY') puts barcode.to_ascii ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## ## # # # # ## # # ## ## # ### # # ## ### ## # ## ### ### ## ### # ## B A R B Y
toretore/barby
235104b2e4f4ac43031d5ea5f9e1e4f91092a04d
replaced obsolete to_a (failing with ruby 1.9.2)
diff --git a/lib/barby/outputter/html_outputter.rb b/lib/barby/outputter/html_outputter.rb index 75e81c0..1c8e200 100644 --- a/lib/barby/outputter/html_outputter.rb +++ b/lib/barby/outputter/html_outputter.rb @@ -1,88 +1,88 @@ require 'barby/outputter' module Barby # Outputs an HTML representation of the barcode. # # Registers to_html # # Allowed options include. # :width - Applied to parent element's style attribute. Default 100. # :height - Applied to parent element's style attribute. Default 100. # :css - Include Barby::HtmlOutputter.css in output's style tag. If you pass false # you can include the output of Barby::HtmlOutputter.css in single place like # your own stylesheet on once on the page. Default true. # :parent_style - Include inline style for things like width and height on parent element. # Useful if you want to style these attributes elsewhere globally. Default true. class HtmlOutputter < Outputter register :to_html def self.css <<-CSS table.barby_code { border: 0 none transparent !important; border-collapse: collapse !important; } table.barby_code tr.barby_row { border: 0 none transparent !important; border-collapse: collapse !important; margin: 0 !important; padding: 0 !important; } table.barby_code tr.barby_row td { border: 0 none transparent !important; } table.barby_code tr.barby_row td.barby_black { background-color: black !important; } table.barby_code tr.barby_row td.barby_white { background-color: white !important; } CSS end def to_html(options={}) default_options = {:width => 100, :height => 100, :css => true, :parent_style => :true} options = default_options.merge(options) elements = if barcode.two_dimensional? booleans.map do |bools| line_to_elements_row(bools, options) end.join("\n") else line_to_elements_row(booleans, options) end html = %|<#{parent_element} class="barby_code" #{parent_style_attribute(options)}>\n#{elements}\n</#{parent_element}>| options[:css] ? "<style>#{self.class.css}</style>\n#{html}" : html end private def line_to_elements_row(bools, options) elements = bools.map{ |b| b ? black_tag : white_tag }.join - %|<#{row_element} class="barby_row">#{elements}</#{row_element}>|.to_a + Array(%|<#{row_element} class="barby_row">#{elements}</#{row_element}>|) end def black_tag '<td class="barby_black"></td>' end def white_tag '<td class="barby_white"></td>' end def row_element 'tr' end def parent_element 'table' end def parent_style_attribute(options) return unless options[:parent_style] s = '' s << "width: #{options[:width]}px; " if options[:width] s << "height: #{options[:height]}px; " if options[:height] s.strip! s.empty? ? nil : %|style="#{s}"| end end end
toretore/barby
bb229e39f66c343611299a52d196cd2018adbb12
New HTML outputter.
diff --git a/lib/barby/outputter/html_outputter.rb b/lib/barby/outputter/html_outputter.rb new file mode 100644 index 0000000..75e81c0 --- /dev/null +++ b/lib/barby/outputter/html_outputter.rb @@ -0,0 +1,88 @@ +require 'barby/outputter' + +module Barby + + # Outputs an HTML representation of the barcode. + # + # Registers to_html + # + # Allowed options include. + # :width - Applied to parent element's style attribute. Default 100. + # :height - Applied to parent element's style attribute. Default 100. + # :css - Include Barby::HtmlOutputter.css in output's style tag. If you pass false + # you can include the output of Barby::HtmlOutputter.css in single place like + # your own stylesheet on once on the page. Default true. + # :parent_style - Include inline style for things like width and height on parent element. + # Useful if you want to style these attributes elsewhere globally. Default true. + class HtmlOutputter < Outputter + + register :to_html + + def self.css + <<-CSS + table.barby_code { + border: 0 none transparent !important; + border-collapse: collapse !important; + } + table.barby_code tr.barby_row { + border: 0 none transparent !important; + border-collapse: collapse !important; + margin: 0 !important; + padding: 0 !important; + } + table.barby_code tr.barby_row td { border: 0 none transparent !important; } + table.barby_code tr.barby_row td.barby_black { background-color: black !important; } + table.barby_code tr.barby_row td.barby_white { background-color: white !important; } + CSS + end + + def to_html(options={}) + default_options = {:width => 100, :height => 100, :css => true, :parent_style => :true} + options = default_options.merge(options) + elements = if barcode.two_dimensional? + booleans.map do |bools| + line_to_elements_row(bools, options) + end.join("\n") + else + line_to_elements_row(booleans, options) + end + html = %|<#{parent_element} class="barby_code" #{parent_style_attribute(options)}>\n#{elements}\n</#{parent_element}>| + options[:css] ? "<style>#{self.class.css}</style>\n#{html}" : html + end + + + private + + def line_to_elements_row(bools, options) + elements = bools.map{ |b| b ? black_tag : white_tag }.join + %|<#{row_element} class="barby_row">#{elements}</#{row_element}>|.to_a + end + + def black_tag + '<td class="barby_black"></td>' + end + + def white_tag + '<td class="barby_white"></td>' + end + + def row_element + 'tr' + end + + def parent_element + 'table' + end + + def parent_style_attribute(options) + return unless options[:parent_style] + s = '' + s << "width: #{options[:width]}px; " if options[:width] + s << "height: #{options[:height]}px; " if options[:height] + s.strip! + s.empty? ? nil : %|style="#{s}"| + end + + end + +end diff --git a/test/outputter/html_outputter_test.rb b/test/outputter/html_outputter_test.rb new file mode 100644 index 0000000..66826ca --- /dev/null +++ b/test/outputter/html_outputter_test.rb @@ -0,0 +1,25 @@ +require 'test_helper' + +class HtmlOutputterTest < Barby::TestCase + + before do + load_outputter('html') + @barcode = Barby::Code128B.new('BARBY') + @outputter = HtmlOutputter.new(@barcode) + end + + it "should register to_html" do + Barcode.outputters.must_include(:to_html) + end + + it "should include css style tag by default with option to leave out" do + @barcode.to_html.must_include "<style>#{Barby::HtmlOutputter.css}</style>" + @barcode.to_html(:css => false).wont_include "<style>#{Barby::HtmlOutputter.css}</style>" + end + + it "should include inline parent style for width and height with option to disable" do + @barcode.to_html.must_include '<table class="barby_code" style="width: 100px; height: 100px;">' + @barcode.to_html(:parent_style => false).must_include '<table class="barby_code" >' + end + +end
toretore/barby
67cfb38bd6893775675e00c389ed3d31e8d8b9d2
Remove rqrcode from official gemspec since QRCodes are an optional usage.
diff --git a/Gemfile b/Gemfile index 6744ce0..013d346 100644 --- a/Gemfile +++ b/Gemfile @@ -1,23 +1,24 @@ source :rubygems gemspec group :development do gem 'rake', '0.8.7' end group :test do gem 'minitest', '2.3.1' end group :outputters do + gem 'rqrcode', '~> 0.3.3' gem 'cairo', '1.10.0' gem 'prawn', '0.11.1' gem 'rmagick', '2.13.1' gem 'chunky_png', '1.2.0' platforms :ruby_18 do gem 'semacode', '0.7.4' gem 'pdf-writer', '1.1.8' end end diff --git a/barby.gemspec b/barby.gemspec index bbaa635..67c96bd 100644 --- a/barby.gemspec +++ b/barby.gemspec @@ -1,24 +1,22 @@ $:.push File.expand_path("../lib", __FILE__) require "barby/version" Gem::Specification.new do |s| s.name = "barby" s.version = Barby::VERSION::STRING s.platform = Gem::Platform::RUBY s.summary = "The Ruby barcode generator" s.email = "toredarell@gmail.com" s.homepage = "http://toretore.github.com/barby" s.description = "Barby creates barcodes." s.authors = ['Tore Darell'] s.rubyforge_project = "barby" s.has_rdoc = true s.extra_rdoc_files = ["README"] s.files = Dir['CHANGELOG', 'README', 'LICENSE', 'lib/**/*', 'vendor/**/*', 'bin/*'] s.executables = ['barby'] s.require_paths = ["lib"] - - s.add_dependency 'rqrcode', '~> 0.3.3' end
toretore/barby
4fe1ae7140636872ca051af59a90cb26b912eeb0
Move to MiniTest::Spec vs RSpec.
diff --git a/Gemfile b/Gemfile index d8988dc..c30b211 100644 --- a/Gemfile +++ b/Gemfile @@ -1,20 +1,21 @@ source :rubygems gemspec group :development do gem 'rake', '0.8.7' end group :test do - gem 'rspec', '2.5.0' + gem 'minitest', '2.3.1' end group :outputters do gem 'cairo', '1.10.0' gem 'semacode', '0.7.4' gem 'pdf-writer', '1.1.8' gem 'prawn', '0.11.1' gem 'rmagick', '2.13.1' + gem 'chunky_png', '1.2.0' end diff --git a/Rakefile b/Rakefile index 9e3b3b5..d17dc85 100644 --- a/Rakefile +++ b/Rakefile @@ -1,26 +1,27 @@ require 'rake' require 'rake/gempackagetask' +require 'rake/testtask' require 'fileutils' -require 'rake' -require 'spec/rake/spectask' + include FileUtils +spec = eval(File.read('barby.gemspec')) + Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = false end task :default => "pkg/#{spec.name}-#{spec.version}.gem" do puts "generated latest version" end -desc "Run all examples" -Spec::Rake::SpecTask.new('spec') do |t| - t.libs << './lib' - t.ruby_opts << '-rubygems' - t.spec_files = FileList['spec/*.rb'] +Rake::TestTask.new do |t| + t.libs = ['lib','test'] + t.test_files = Dir.glob("test/**/*_test.rb").sort + t.verbose = true end desc "Build RDoc" task :doc do system "rm -rf site/rdoc; rdoc -tBarby -xvendor -osite/rdoc -mREADME lib/**/* README" end diff --git a/spec/bookland_spec.rb b/spec/bookland_spec.rb deleted file mode 100644 index 936b66f..0000000 --- a/spec/bookland_spec.rb +++ /dev/null @@ -1,62 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/bookland' -include Barby - -describe Bookland do - - before :each do - @isbn = '968-26-1240-3' - @code = Bookland.new(@isbn) - end - - it "should not touch the ISBN" do - @code.isbn.should == @isbn - end - - it "should have an isbn_only" do - @code.isbn_only.should == '968261240' - end - - it "should have the expected data" do - @code.data.should == '978968261240' - end - - it "should have the expected numbers" do - @code.numbers.should == [9,7,8,9,6,8,2,6,1,2,4,0] - end - - it "should have the expected checksum" do - @code.checksum.should == 4 - end - - it "should raise an error when data not valid" do - lambda{ Bookland.new('1234') }.should raise_error(ArgumentError) - end - -end - - -describe Bookland, 'ISBN conversion' do - - it "should accept ISBN with number system and check digit" do - code = nil - lambda{ code = Bookland.new('978-82-92526-14-9') }.should_not raise_error - code.should be_valid - code.data.should == '978829252614' - end - - it "should accept ISBN without number system but with check digit" do - code = nil - lambda{ code = Bookland.new('82-92526-14-9') }.should_not raise_error - code.should be_valid - code.data.should == '978829252614' - end - - it "should accept ISBN without number system or check digit" do - code = nil - lambda{ code = Bookland.new('82-92526-14') }.should_not raise_error - code.should be_valid - code.data.should == '978829252614' - end - -end diff --git a/spec/code_128_spec.rb b/spec/code_128_spec.rb deleted file mode 100644 index d43b97d..0000000 --- a/spec/code_128_spec.rb +++ /dev/null @@ -1,356 +0,0 @@ -#encoding: UTF-8 -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/code_128' -include Barby - - -describe "Common features" do - - before :each do - @data = 'ABC123' - @code = Code128A.new(@data) - end - - it "should have the expected stop encoding (including termination bar 11)" do - @code.send(:stop_encoding).should == '1100011101011' - end - - it "should find the right class for a character A, B or C" do - @code.send(:class_for, 'A').should == Code128A - @code.send(:class_for, 'B').should == Code128B - @code.send(:class_for, 'C').should == Code128C - end - - it "should find the right change code for a class" do - @code.send(:change_code_for_class, Code128A).should == Code128::CODEA - @code.send(:change_code_for_class, Code128B).should == Code128::CODEB - @code.send(:change_code_for_class, Code128C).should == Code128::CODEC - end - - it "should not allow empty data" do - lambda{ Code128B.new("") }.should raise_error(ArgumentError) - end - -end - - -describe "Common features for single encoding" do - - before :each do - @data = 'ABC123' - @code = Code128A.new(@data) - end - - it "should have the same data as when initialized" do - @code.data.should == @data - end - - it "should be able to change its data" do - @code.data = '123ABC' - @code.data.should == '123ABC' - @code.data.should_not == @data - end - - it "should not have an extra" do - @code.extra.should be_nil - end - - it "should have empty extra encoding" do - @code.extra_encoding.should == '' - end - - it "should have the correct checksum" do - @code.checksum.should == 66 - end - - it "should return all data for to_s" do - @code.to_s.should == @data - end - -end - - -describe "Common features for multiple encodings" do - - before :each do - @data = "ABC123\306def\3074567" - @code = Code128A.new(@data) - end - - it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do - @code.full_data.should == "ABC123def4567" - end - - it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do - @code.full_data_with_change_codes.should == @data - end - - it "should not matter if extras were added separately" do - code = Code128B.new("ABC") - code.extra = "\3071234" - code.full_data.should == "ABC1234" - code.full_data_with_change_codes.should == "ABC\3071234" - code.extra.extra = "\306abc" - code.full_data.should == "ABC1234abc" - code.full_data_with_change_codes.should == "ABC\3071234\306abc" - code.extra.extra.data = "abc\305DEF" - code.full_data.should == "ABC1234abcDEF" - code.full_data_with_change_codes.should == "ABC\3071234\306abc\305DEF" - code.extra.extra.full_data.should == "abcDEF" - code.extra.extra.full_data_with_change_codes.should == "abc\305DEF" - code.extra.full_data.should == "1234abcDEF" - code.extra.full_data_with_change_codes.should == "1234\306abc\305DEF" - end - - it "should have a Code B extra" do - @code.extra.should be_an_instance_of(Code128B) - end - - it "should have a valid extra" do - @code.extra.should be_valid - end - - it "the extra should also have an extra of type C" do - @code.extra.extra.should be_an_instance_of(Code128C) - end - - it "the extra's extra should be valid" do - @code.extra.extra.should be_valid - end - - it "should not have more than two extras" do - @code.extra.extra.extra.should be_nil - end - - it "should split extra data from string on data assignment" do - @code.data = "123\306abc" - @code.data.should == '123' - @code.extra.should be_an_instance_of(Code128B) - @code.extra.data.should == 'abc' - end - - it "should be be able to change its extra" do - @code.extra = "\3071234" - @code.extra.should be_an_instance_of(Code128C) - @code.extra.data.should == '1234' - end - - it "should split extra data from string on extra assignment" do - @code.extra = "\306123\3074567" - @code.extra.should be_an_instance_of(Code128B) - @code.extra.data.should == '123' - @code.extra.extra.should be_an_instance_of(Code128C) - @code.extra.extra.data.should == '4567' - end - - it "should not fail on newlines in extras" do - code = Code128B.new("ABC\305\n") - code.data.should == "ABC" - code.extra.should be_an_instance_of(Code128A) - code.extra.data.should == "\n" - code.extra.extra = "\305\n\n\n\n\n\nVALID" - code.extra.extra.data.should == "\n\n\n\n\n\nVALID" - end - - it "should raise an exception when extra string doesn't start with the special code character" do - lambda{ @code.extra = '123' }.should raise_error - end - - it "should have the correct checksum" do - @code.checksum.should == 84 - end - - it "should have the expected encoding" do - #STARTA A B C 1 2 3 - @code.encoding.should == '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ - #CODEB d e f - '10111101110100001001101011001000010110000100'+ - #CODEC 45 67 - '101110111101011101100010000101100'+ - #CHECK=84 STOP - '100111101001100011101011' - end - - it "should return all data including extras, except change codes for to_s" do - @code.to_s.should == "ABC123def4567" - end - -end - - -describe "128A" do - - before :each do - @data = 'ABC123' - @code = Code128A.new(@data) - end - - it "should be valid when given valid data" do - @code.should be_valid - end - - it "should not be valid when given invalid data" do - @code.data = 'abc123' - @code.should_not be_valid - end - - it "should have the expected characters" do - @code.characters.should == %w(A B C 1 2 3) - end - - it "should have the expected start encoding" do - @code.start_encoding.should == '11010000100' - end - - it "should have the expected data encoding" do - @code.data_encoding.should == '101000110001000101100010001000110100111001101100111001011001011100' - end - - it "should have the expected encoding" do - @code.encoding.should == '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' - end - - it "should have the expected checksum encoding" do - @code.checksum_encoding.should == '10010000110' - end - -end - - -describe "128B" do - - before :each do - @data = 'abc123' - @code = Code128B.new(@data) - end - - it "should be valid when given valid data" do - @code.should be_valid - end - - it "should not be valid when given invalid data" do - @code.data = 'abc£123' - @code.should_not be_valid - end - - it "should have the expected characters" do - @code.characters.should == %w(a b c 1 2 3) - end - - it "should have the expected start encoding" do - @code.start_encoding.should == '11010010000' - end - - it "should have the expected data encoding" do - @code.data_encoding.should == '100101100001001000011010000101100100111001101100111001011001011100' - end - - it "should have the expected encoding" do - @code.encoding.should == '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' - end - - it "should have the expected checksum encoding" do - @code.checksum_encoding.should == '11011101110' - end - -end - - -describe "128C" do - - before :each do - @data = '123456' - @code = Code128C.new(@data) - end - - it "should be valid when given valid data" do - @code.should be_valid - end - - it "should not be valid when given invalid data" do - @code.data = '123' - @code.should_not be_valid - @code.data = 'abc' - @code.should_not be_valid - end - - it "should have the expected characters" do - @code.characters.should == %w(12 34 56) - end - - it "should have the expected start encoding" do - @code.start_encoding.should == '11010011100' - end - - it "should have the expected data encoding" do - @code.data_encoding.should == '101100111001000101100011100010110' - end - - it "should have the expected encoding" do - @code.encoding.should == '11010011100101100111001000101100011100010110100011011101100011101011' - end - - it "should have the expected checksum encoding" do - @code.checksum_encoding.should == '10001101110' - end - -end - - -describe "Function characters" do - - it "should retain the special symbols in the data accessor" do - Code128A.new("\301ABC\301DEF").data.should == "\301ABC\301DEF" - Code128B.new("\301ABC\302DEF").data.should == "\301ABC\302DEF" - Code128C.new("\301123456").data.should == "\301123456" - Code128C.new("12\30134\30156").data.should == "12\30134\30156" - end - - it "should keep the special symbols as characters" do - Code128A.new("\301ABC\301DEF").characters.should == %W(\301 A B C \301 D E F) - Code128B.new("\301ABC\302DEF").characters.should == %W(\301 A B C \302 D E F) - Code128C.new("\301123456").characters.should == %W(\301 12 34 56) - Code128C.new("12\30134\30156").characters.should == %W(12 \301 34 \301 56) - end - - it "should not allow FNC > 1 for Code C" do - lambda{ Code128C.new("12\302") }.should raise_error - lambda{ Code128C.new("\30312") }.should raise_error - lambda{ Code128C.new("12\304") }.should raise_error - end - - it "should be included in the encoding" do - a = Code128A.new("\301AB") - a.data_encoding.should == '111101011101010001100010001011000' - a.encoding.should == '11010000100111101011101010001100010001011000101000011001100011101011' - end - -end - - -describe "Code128 with type" do - - it "should raise an exception when not given a type" do - lambda{ Code128.new('abc') }.should raise_error(ArgumentError) - end - - it "should raise an exception when given a non-existent type" do - lambda{ Code128.new('abc', 'F') }.should raise_error(ArgumentError) - end - - it "should give the right encoding for type A" do - code = Code128.new('ABC123', 'A') - code.encoding.should == '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' - end - - it "should give the right encoding for type B" do - code = Code128.new('abc123', 'B') - code.encoding.should == '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' - end - - it "should give the right encoding for type B" do - code = Code128.new('123456', 'C') - code.encoding.should == '11010011100101100111001000101100011100010110100011011101100011101011' - end - -end diff --git a/spec/code_25_iata_spec.rb b/spec/code_25_iata_spec.rb deleted file mode 100644 index bd9ca0f..0000000 --- a/spec/code_25_iata_spec.rb +++ /dev/null @@ -1,20 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/code_25_iata' -include Barby - -describe Code25IATA do - - before :each do - @data = '0123456789' - @code = Code25IATA.new(@data) - end - - it "should have the expected start_encoding" do - @code.start_encoding.should == '1010' - end - - it "should have the expected stop_encoding" do - @code.stop_encoding.should == '11101' - end - -end diff --git a/spec/code_25_interleaved_spec.rb b/spec/code_25_interleaved_spec.rb deleted file mode 100644 index 437c02c..0000000 --- a/spec/code_25_interleaved_spec.rb +++ /dev/null @@ -1,117 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/code_25_interleaved' -include Barby - -describe Code25Interleaved do - - before :each do - @data = '12345670' - @code = Code25Interleaved.new(@data) - end - - it "should have the expected digit_pairs" do - @code.digit_pairs.should == [[1,2],[3,4],[5,6],[7,0]] - end - - it "should have the expected digit_encodings" do - @code.digit_encodings.should == %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110) - end - - it "should have the expected start_encoding" do - @code.start_encoding.should == '1010' - end - - it "should have the expected stop_encoding" do - @code.stop_encoding.should == '11101' - end - - it "should have the expected data_encoding" do - @code.data_encoding.should == "111010001010111000111011101000101000111010001110001010101010001110001110" - end - - it "should have the expected encoding" do - @code.encoding.should == "101011101000101011100011101110100010100011101000111000101010101000111000111011101" - end - - it "should be valid" do - @code.should be_valid - end - - it "should return the expected encoding for parameters passed to encoding_for_interleaved" do - w, n = Code25Interleaved::WIDE, Code25Interleaved::NARROW - # 1 2 1 2 1 2 1 2 1 2 digits 1 and 2 - # B S B S B S B S B S bars and spaces - @code.encoding_for_interleaved(w,n,n,w,n,n,n,n,w,w).should == '111010001010111000' - # 3 4 3 4 3 4 3 4 3 4 digits 3 and 4 - # B S B S B S B S B S bars and spaces - @code.encoding_for_interleaved(w,n,w,n,n,w,n,n,n,w).should == '111011101000101000' - end - - it "should return all characters in sequence for to_s" do - @code.to_s.should == @code.characters.join - end - -end - -describe "Code25Interleaved with checksum" do - - - before :each do - @data = '1234567' - @code = Code25Interleaved.new(@data) - @code.include_checksum = true - end - - - it "should have the expected digit_pairs_with_checksum" do - @code.digit_pairs_with_checksum.should == [[1,2],[3,4],[5,6],[7,0]] - end - - it "should have the expected digit_encodings_with_checksum" do - @code.digit_encodings_with_checksum.should == %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110) - end - - it "should have the expected data_encoding_with_checksum" do - @code.data_encoding_with_checksum.should == "111010001010111000111011101000101000111010001110001010101010001110001110" - end - - it "should have the expected encoding" do - @code.encoding.should == "101011101000101011100011101110100010100011101000111000101010101000111000111011101" - end - - it "should be valid" do - @code.should be_valid - end - - it "should return all characters including checksum in sequence on to_s" do - @code.to_s.should == @code.characters_with_checksum.join - end - - -end - -describe "Code25Interleaved with invalid number of digits" do - - - before :each do - @data = '1234567' - @code = Code25Interleaved.new(@data) - end - - it "should not be valid" do - @code.should_not be_valid - end - - it "should raise ArgumentError on all encoding methods" do - lambda{ @code.encoding }.should raise_error(ArgumentError) - lambda{ @code.data_encoding }.should raise_error(ArgumentError) - lambda{ @code.digit_encodings }.should raise_error(ArgumentError) - end - - it "should not raise ArgumentError on encoding methods that include checksum" do - lambda{ b=Code25Interleaved.new(@data); b.include_checksum=true; b.encoding }.should_not raise_error(ArgumentError) - lambda{ @code.data_encoding_with_checksum }.should_not raise_error(ArgumentError) - lambda{ @code.digit_encodings_with_checksum }.should_not raise_error(ArgumentError) - end - -end diff --git a/spec/code_25_spec.rb b/spec/code_25_spec.rb deleted file mode 100644 index a417ce6..0000000 --- a/spec/code_25_spec.rb +++ /dev/null @@ -1,111 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/code_25' -include Barby - -describe Code25 do - - before :each do - @data = "1234567" - @code = Code25.new(@data) - end - - it "should return the same data it was given" do - @code.data.should == @data - end - - it "should have the expected characters" do - @code.characters.should == %w(1 2 3 4 5 6 7) - end - - it "should have the expected characters_with_checksum" do - @code.characters_with_checksum.should == %w(1 2 3 4 5 6 7 0) - end - - it "should have the expected digits" do - @code.digits.should == [1,2,3,4,5,6,7] - end - - it "should have the expected digits_with_checksum" do - @code.digits_with_checksum.should == [1,2,3,4,5,6,7,0] - end - - it "should have the expected even_and_odd_digits" do - @code.even_and_odd_digits.should == [[7,5,3,1], [6,4,2]] - end - - it "should have the expected start_encoding" do - @code.start_encoding.should == '1110111010' - end - - it "should have the expected stop_encoding" do - @code.stop_encoding.should == '111010111' - end - - it "should have a default narrow_width of 1" do - @code.narrow_width.should == 1 - end - - it "should have a default wide_width equal to narrow_width * 3" do - @code.wide_width.should == @code.narrow_width * 3 - @code.narrow_width = 2 - @code.wide_width.should == 6 - end - - it "should have a default space_width equal to narrow_width" do - @code.space_width.should == @code.narrow_width - @code.narrow_width = 23 - @code.space_width.should == 23 - end - - it "should have the expected digit_encodings" do - @code.digit_encodings.should == %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110) - end - - it "should have the expected digit_encodings_with_checksum" do - @code.digit_encodings_with_checksum.should == %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110 10101110111010) - end - - it "should have the expected data_encoding" do - @code.data_encoding.should == "11101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110" - end - - it "should have the expected checksum" do - @code.checksum.should == 0 - end - - it "should have the expected checksum_encoding" do - @code.checksum_encoding.should == '10101110111010' - end - - it "should have the expected encoding" do - @code.encoding.should == "111011101011101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110111010111" - end - - it "should be valid" do - @code.should be_valid - end - - it "should not be valid" do - @code.data = 'abc' - @code.should_not be_valid - end - - it "should raise on encoding methods that include data encoding if not valid" do - @code.data = 'abc' - lambda{ @code.encoding }.should raise_error - lambda{ @code.data_encoding }.should raise_error - lambda{ @code.data_encoding_with_checksum }.should raise_error - lambda{ @code.digit_encodings }.should raise_error - lambda{ @code.digit_encodings_with_checksum }.should raise_error - end - - it "should return all characters in sequence on to_s" do - @code.to_s.should == @code.characters.join - end - - it "should include checksum in to_s when include_checksum is true" do - @code.include_checksum = true - @code.to_s.should == @code.characters_with_checksum.join - end - -end diff --git a/spec/code_39_spec.rb b/spec/code_39_spec.rb deleted file mode 100644 index 6cdd7a0..0000000 --- a/spec/code_39_spec.rb +++ /dev/null @@ -1,211 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/code_39' -include Barby - -describe Code39 do - - before :each do - @data = 'TEST8052' - @code = Code39.new(@data) - @code.spacing = 3 - end - - it "should yield self on initialize" do - c1 = nil - c2 = Code39.new('TEST'){|c| c1 = c } - c1.should == c2 - end - - it "should have the expected data" do - @code.data.should == @data - end - - it "should have the expected characters" do - @code.characters.should == @data.split(//) - end - - it "should have the expected start_encoding" do - @code.start_encoding.should == '100101101101' - end - - it "should have the expected stop_encoding" do - @code.stop_encoding.should == '100101101101' - end - - it "should have the expected spacing_encoding" do - @code.spacing_encoding.should == '000' - end - - it "should have the expected encoded characters" do - @code.encoded_characters.should == %w(101011011001 110101100101 101101011001 101011011001 110100101101 101001101101 110100110101 101100101011) - end - - it "should have the expected data_encoding" do - @code.data_encoding.should == '101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011' - end - - it "should have the expected encoding" do - @code.encoding.should == '100101101101000101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011000100101101101' - end - - it "should be valid" do - @code.should be_valid - end - - it "should not be valid" do - @code.data = "123\200456" - @code.should_not be_valid - end - - it "should raise an exception when data is not valid on initialization" do - lambda{ Code39.new('abc') }.should raise_error(ArgumentError) - end - - it "should return all characters in sequence without checksum on to_s" do - @code.to_s.should == @data - end - -end - -describe "Checksumming" do - - before :each do - @code = Code39.new('CODE39') - end - - it "should have the expected checksum" do - @code.checksum.should == 32 - end - - it "should have the expected checksum_character" do - @code.checksum_character.should == 'W' - end - - it "should have the expected checksum_encoding" do - @code.checksum_encoding.should == '110011010101' - end - - it "should have the expected characters_with_checksum" do - @code.characters_with_checksum.should == %w(C O D E 3 9 W) - end - - it "should have the expected encoded_characters_with_checksum" do - @code.encoded_characters_with_checksum.should == %w(110110100101 110101101001 101011001011 110101100101 110110010101 101100101101 110011010101) - end - - it "should have the expected data_encoding_with_checksum" do - @code.data_encoding_with_checksum.should == "110110100101011010110100101010110010110110101100101011011001010101011001011010110011010101" - end - - it "should have the expected encoding_with_checksum" do - @code.encoding_with_checksum.should == "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" - end - - it "should return the encoding with checksum when include_checksum == true" do - @code.include_checksum = true - @code.encoding.should == "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" - end - -end - - -describe "Normal encoding" do - - before :each do - @data = 'ABC$%' - @code = Code39.new(@data) - end - - it "should have the expected characters" do - @code.characters.should == %w(A B C $ %) - end - - it "should have the expected encoded_characters" do - @code.encoded_characters.should == %w(110101001011 101101001011 110110100101 100100100101 101001001001) - end - - it "should have the expected data_encoding" do - @code.data_encoding.should == '1101010010110101101001011011011010010101001001001010101001001001' - end - - it "should not be valid" do - @code.data = 'abc' - @code.should_not be_valid - end - -end - - -describe "Extended encoding" do - - before :each do - @data = '<abc>' - @code = Code39.new(@data, true) - end - - it "should return true on extended?" do - @code.should be_extended - end - - it "should have the expected characters" do - @code.characters.should == %w(% G + A + B + C % I) - end - - it "should have the expected encoded_characters" do - @code.encoded_characters.should == %w(101001001001 101010011011 100101001001 110101001011 100101001001 101101001011 100101001001 110110100101 101001001001 101101001101) - end - - it "should have the expected data_encoding" do - @code.data_encoding.should == '101001001001010101001101101001010010010110101001011010010100100101011010010110100101001001011011010010101010010010010101101001101' - end - - it "should have the expected encoding" do - @code.encoding.should == '10010110110101010010010010101010011011010010100100101101010010110100101001001'+ - '010110100101101001010010010110110100101010100100100101011010011010100101101101' - end - - it "should take a second parameter on initialize indicating it is extended" do - Code39.new('abc', true).should be_extended - Code39.new('ABC', false).should_not be_extended - Code39.new('ABC').should_not be_extended - end - - it "should be valid" do - @code.should be_valid - end - - it "should not be valid" do - @code.data = "abc\200123" - @code.should_not be_valid - end - - it "should return all characters in sequence without checksum on to_s" do - @code.to_s.should == @data - end - -end - - -describe "Variable widths" do - - before :each do - @data = 'ABC$%' - @code = Code39.new(@data) - @code.narrow_width = 2 - @code.wide_width = 5 - end - - it "should have the expected encoded_characters" do - @code.encoded_characters.should == %w(111110011001100000110011111 110011111001100000110011111 111110011111001100000110011 110000011000001100000110011 110011000001100000110000011) - end - - it "should have the expected data_encoding" do - # A SB SC S$ S% - @code.data_encoding.should == '1111100110011000001100111110110011111001100000110011111011111001111100110000011001101100000110000011000001100110110011000001100000110000011' - - @code.spacing = 3 - # A S B S C S $ S % - @code.data_encoding.should == '111110011001100000110011111000110011111001100000110011111000111110011111001100000110011000110000011000001100000110011000110011000001100000110000011' - end - -end diff --git a/spec/code_93_spec.rb b/spec/code_93_spec.rb deleted file mode 100644 index 8ef335c..0000000 --- a/spec/code_93_spec.rb +++ /dev/null @@ -1,145 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/code_93' -include Barby - -describe Code93 do - - before :each do - @data = 'TEST93' - @code = Code93.new(@data) - end - - it "should return the same data we put in" do - @code.data.should == @data - end - - it "should have the expected characters" do - @code.characters.should == @data.split(//) - end - - it "should have the expected start_encoding" do - @code.start_encoding.should == '101011110' - end - - it "should have the expected stop_encoding" do - # STOP TERM - @code.stop_encoding.should == '1010111101' - end - - it "should have the expected encoded characters" do - # T E S T 9 3 - @code.encoded_characters.should == %w(110100110 110010010 110101100 110100110 100001010 101000010) - end - - it "should have the expected data_encoding" do - # T E S T 9 3 - @code.data_encoding.should == "110100110110010010110101100110100110100001010101000010" - end - - it "should have the expected data_encoding_with_checksums" do - # T E S T 9 3 + (C) 6 (K) - @code.data_encoding_with_checksums.should == "110100110110010010110101100110100110100001010101000010101110110100100010" - end - - it "should have the expected encoding" do - # START T E S T 9 3 + (C) 6 (K) STOP TERM - @code.encoding.should == "1010111101101001101100100101101011001101001101000010101010000101011101101001000101010111101" - end - - it "should have the expected checksum_values" do - @code.checksum_values.should == [29, 14, 28, 29, 9, 3].reverse #! - end - - it "should have the expected c_checksum" do - @code.c_checksum.should == 41 #calculate this first! - end - - it "should have the expected c_checksum_character" do - @code.c_checksum_character.should == '+' - end - - it "should have the expected c_checksum_encoding" do - @code.c_checksum_encoding.should == '101110110' - end - - it "should have the expected checksum_values_with_c_checksum" do - @code.checksum_values_with_c_checksum.should == [29, 14, 28, 29, 9, 3, 41].reverse #! - end - - it "should have the expected k_checksum" do - @code.k_checksum.should == 6 #calculate this first! - end - - it "should have the expected k_checksum_character" do - @code.k_checksum_character.should == '6' - end - - it "should have the expected k_checksum_encoding" do - @code.k_checksum_encoding.should == '100100010' - end - - it "should have the expected checksums" do - @code.checksums.should == [41, 6] - end - - it "should have the expected checksum_characters" do - @code.checksum_characters.should == ['+', '6'] - end - - it "should have the expected checksum_encodings" do - @code.checksum_encodings.should == %w(101110110 100100010) - end - - it "should have the expected checksum_encoding" do - @code.checksum_encoding.should == '101110110100100010' - end - - it "should be valid" do - @code.should be_valid - end - - it "should not be valid when not in extended mode" do - @code.data = 'not extended' - end - - it "should return data with no checksums on to_s" do - @code.to_s.should == 'TEST93' - end - -end - - -describe "Extended mode" do - - before :each do - @data = "Extended!" - @code = Code93.new(@data) - end - - it "should be extended" do - @code.should be_extended - end - - #TODO: For some reason the encoding gets screwed up when using RSpec - it "should convert extended characters to special shift characters" do - @code.characters.should == ["E", "\304", "X", "\304", "T", "\304", "E", "\304", "N", "\304", "D", "\304", "E", "\304", "D", "\303", "A"] - end - - it "should have the expected data_encoding" do - @code.data_encoding.should == '110010010100110010101100110100110010110100110100110010110010010'+ - '100110010101000110100110010110010100100110010110010010100110010110010100111010110110101000' - end - - it "should have the expected c_checksum" do - @code.c_checksum.should == 9 - end - - it "should have the expected k_checksum" do - @code.k_checksum.should == 46 - end - - it "should return the original data on to_s with no checksums" do - @code.to_s.should == 'Extended!' - end - -end diff --git a/spec/ean13_spec.rb b/spec/ean13_spec.rb deleted file mode 100644 index a71e240..0000000 --- a/spec/ean13_spec.rb +++ /dev/null @@ -1,169 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/ean_13' -include Barby - -describe EAN13, ' validations' do - - before :each do - @valid = EAN13.new('123456789012') - end - - it "should be valid with 12 digits" do - @valid.should be_valid - end - - it "should not be valid with non-digit characters" do - @valid.data = "The shit apple doesn't fall far from the shit tree" - @valid.should_not be_valid - end - - it "should not be valid with less than 12 digits" do - @valid.data = "12345678901" - @valid.should_not be_valid - end - - it "should not be valid with more than 12 digits" do - @valid.data = "1234567890123" - @valid.should_not be_valid - end - - it "should raise an exception when data is invalid" do - lambda{ EAN13.new('123') }.should raise_error(ArgumentError) - end - -end - - -describe EAN13, ' data' do - - before :each do - @data = '007567816412' - @code = EAN13.new(@data) - end - - it "should have the same data as was passed to it" do - @code.data.should == @data - end - - it "should have the expected characters" do - @code.characters.should == @data.split(//) - end - - it "should have the expected numbers" do - @code.numbers.should == @data.split(//).map{|s| s.to_i } - end - - it "should have the expected odd_and_even_numbers" do - @code.odd_and_even_numbers.should == [[2,4,1,7,5,0], [1,6,8,6,7,0]] - end - - it "should have the expected left_numbers" do - #0=second number in number system code - @code.left_numbers.should == [0,7,5,6,7,8] - end - - it "should have the expected right_numbers" do - @code.right_numbers.should == [1,6,4,1,2,5]#5=checksum - end - - it "should have the expected numbers_with_checksum" do - @code.numbers_with_checksum.should == @data.split(//).map{|s| s.to_i } + [5] - end - - it "should have the expected data_with_checksum" do - @code.data_with_checksum.should == @data+'5' - end - - it "should return all digits and the checksum on to_s" do - @code.to_s.should == '0075678164125' - end - -end - - -describe EAN13, ' checksum' do - - before :each do - @code = EAN13.new('007567816412') - end - - it "should have the expected weighted_sum" do - @code.weighted_sum.should == 85 - @code.data = '007567816413' - @code.weighted_sum.should == 88 - end - - it "should have the correct checksum" do - @code.checksum.should == 5 - @code.data = '007567816413' - @code.checksum.should == 2 - end - - it "should have the correct checksum_encoding" do - @code.checksum_encoding.should == '1001110' - end - -end - - -describe EAN13, ' encoding' do - - before :each do - @code = EAN13.new('750103131130') - end - - it "should have the expected checksum" do - @code.checksum.should == 9 - end - - it "should have the expected checksum_encoding" do - @code.checksum_encoding.should == '1110100' - end - - it "should have the expected left_parity_map" do - @code.left_parity_map.should == [:odd, :even, :odd, :even, :odd, :even] - end - - it "should have the expected left_encodings" do - @code.left_encodings.should == %w(0110001 0100111 0011001 0100111 0111101 0110011) - end - - it "should have the expected right_encodings" do - @code.right_encodings.should == %w(1000010 1100110 1100110 1000010 1110010 1110100) - end - - it "should have the expected left_encoding" do - @code.left_encoding.should == '011000101001110011001010011101111010110011' - end - - it "should have the expected right_encoding" do - @code.right_encoding.should == '100001011001101100110100001011100101110100' - end - - it "should have the expected encoding" do - #Start Left Center Right Stop - @code.encoding.should == '101' + '011000101001110011001010011101111010110011' + '01010' + '100001011001101100110100001011100101110100' + '101' - end - -end - - -describe EAN13, 'static data' do - - before :each do - @code = EAN13.new('123456789012') - end - - it "should have the expected start_encoding" do - @code.start_encoding.should == '101' - end - - it "should have the expected stop_encoding" do - @code.stop_encoding.should == '101' - end - - it "should have the expected center_encoding" do - @code.center_encoding.should == '01010' - end - -end diff --git a/spec/ean8_spec.rb b/spec/ean8_spec.rb deleted file mode 100644 index ba41fbd..0000000 --- a/spec/ean8_spec.rb +++ /dev/null @@ -1,99 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/ean_8' -include Barby - -describe EAN8, 'validations' do - - before :each do - @valid = EAN8.new('1234567') - end - - it "should be valid with 7 digits" do - @valid.should be_valid - end - - it "should not be valid with less than 7 digits" do - @valid.data = '123456' - @valid.should_not be_valid - end - - it "should not be valid with more than 7 digits" do - @valid.data = '12345678' - @valid.should_not be_valid - end - - it "should not be valid with non-digits" do - @valid.data = 'abcdefg' - @valid.should_not be_valid - end - -end - - -describe EAN8, 'checksum' do - - before :each do - @code = EAN8.new('5512345') - end - - it "should have the expected weighted_sum" do - @code.weighted_sum.should == 53 - end - - it "should have the expected checksum" do - @code.checksum.should == 7 - end - -end - - -describe EAN8, 'data' do - - before :each do - @data = '5512345' - @code = EAN8.new(@data) - end - - it "should have the expected data" do - @code.data.should == @data - end - - it "should have the expected odd_and_even_numbers" do - @code.odd_and_even_numbers.should == [[5,3,1,5],[4,2,5]] - end - - it "should have the expected left_numbers" do - #EAN-8 includes the first character in the left-hand encoding, unlike EAN-13 - @code.left_numbers.should == [5,5,1,2] - end - - it "should have the expected right_numbers" do - @code.right_numbers.should == [3,4,5,7] - end - - it "should return the data with checksum on to_s" do - @code.to_s.should == '55123457' - end - -end - - -describe EAN8, 'encoding' do - - before :each do - @code = EAN8.new('5512345') - end - - it "should have the expected left_parity_map" do - @code.left_parity_map.should == [:odd, :odd, :odd, :odd] - end - - it "should have the expected left_encoding" do - @code.left_encoding.should == '0110001011000100110010010011' - end - - it "should have the expected right_encoding" do - @code.right_encoding.should == '1000010101110010011101000100' - end - -end diff --git a/spec/outputter_spec.rb b/spec/outputter_spec.rb deleted file mode 100644 index 5710db4..0000000 --- a/spec/outputter_spec.rb +++ /dev/null @@ -1,136 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/outputter' -include Barby - - -describe "Outputter classes" do - - before :each do - @outputter = Class.new(Outputter) - end - - it "should be able to register an output method for barcodes" do - @outputter.register :foo - Barcode.outputters.should include(:foo) - @outputter.register :bar, :baz - Barcode.outputters.should include(:bar, :baz) - @outputter.register :quux => :my_quux - Barcode.outputters.should include(:quux) - end - -end - - -describe "Outputter instances" do - - before :each do - @barcode = Barcode.new - class << @barcode; attr_accessor :encoding; end - @barcode.encoding = '101100111000' - @outputter = Outputter.new(@barcode) - end - - it "should have a method 'booleans' which converts the barcode encoding to an array of true,false values" do - @outputter.send(:booleans).length.should == @barcode.encoding.length - t, f = true, false - @outputter.send(:booleans).should == [t,f,t,t,f,f,t,t,t,f,f,f] - end - - it "should convert 2D encodings with 'booleans'" do - barcode = Barcode2D.new - def barcode.encoding; ['101100','110010']; end - outputter = Outputter.new(barcode) - outputter.send(:booleans).length.should == barcode.encoding.length - t, f = true, false - outputter.send(:booleans).should == [[t,f,t,t,f,f], [t,t,f,f,t,f]] - end - - it "should have an 'encoding' attribute" do - @outputter.send(:encoding).should == @barcode.encoding - end - - it "should cache encoding" do - @outputter.send(:encoding).should == @barcode.encoding - previous_encoding = @barcode.encoding - @barcode.encoding = '101010' - @outputter.send(:encoding).should == previous_encoding - @outputter.send(:encoding, true).should == @barcode.encoding - end - - it "should have a boolean_groups attribute which collects continuous bars and spaces" do - t, f = true, false - # 1 0 11 00 111 000 - @outputter.send(:boolean_groups).should == [[t,1],[f,1],[t,2],[f,2],[t,3],[f,3]] - - barcode = Barcode2D.new - def barcode.encoding; ['1100', '111000']; end - outputter = Outputter.new(barcode) - outputter.send(:boolean_groups).should == [[[t,2],[f,2]],[[t,3],[f,3]]] - end - - it "should have a with_options method which sets the instance's attributes temporarily while the block gets yielded" do - class << @outputter; attr_accessor :foo, :bar; end - @outputter.foo, @outputter.bar = 'humbaba', 'scorpion man' - @outputter.send(:with_options, :foo => 'horse', :bar => 'donkey') do - @outputter.foo.should == 'horse' - @outputter.bar.should == 'donkey' - end - @outputter.foo.should == 'humbaba' - @outputter.bar.should == 'scorpion man' - end - - it "should return the block value on with_options" do - @outputter.send(:with_options, {}){ 'donkey' }.should == 'donkey' - end - - it "should have a two_dimensional? method which returns true if the barcode is 2d" do - Outputter.new(Barcode1D.new).should_not be_two_dimensional - Outputter.new(Barcode2D.new).should be_two_dimensional - end - - it "should not require the barcode object to respond to two_dimensional?" do - barcode = Object.new - def barcode.encoding; "101100111000"; end - outputter = Outputter.new(barcode) - lambda{ outputter.send :booleans }.should_not raise_error(NoMethodError) - lambda{ outputter.send :boolean_groups }.should_not raise_error(NoMethodError) - end - -end - - -describe "Barcode instances" do - - before :all do - @outputter = Class.new(Outputter) - @outputter.register :foo - @outputter.register :bar => :my_bar - @outputter.class_eval{ def foo; 'foo'; end; def my_bar; 'bar'; end } - @barcode = Barcode.new - end - - it "should respond to registered output methods" do - @barcode.foo.should == 'foo' - @barcode.bar.should == 'bar' - end - - it "should send arguments to registered method on outputter class" do - @outputter.class_eval{ def foo(*a); a; end; def my_bar(*a); a; end } - @barcode.foo(1,2,3).should == [1,2,3] - @barcode.bar('humbaba').should == ['humbaba'] - end - - it "should pass block to registered methods" do - @outputter.class_eval{ def foo(*a, &b); b.call(*a); end } - @barcode.foo(1,2,3){|*a| a }.should == [1,2,3] - end - - it "should be able to get an instance of a specific outputter" do - @barcode.outputter_for(:foo).should be_an_instance_of(@outputter) - end - - it "should be able to get a specific outputter class" do - @barcode.outputter_class_for(:foo).should == @outputter - end - -end diff --git a/spec/pdfwriter_outputter_spec.rb b/spec/pdfwriter_outputter_spec.rb deleted file mode 100644 index f5700da..0000000 --- a/spec/pdfwriter_outputter_spec.rb +++ /dev/null @@ -1,34 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/outputter/pdfwriter_outputter' -require 'pdf/writer' -include Barby - -describe PDFWriterOutputter do - - before :each do - @barcode = Barcode.new - def @barcode.encoding; '101100111000'; end - @outputter = PDFWriterOutputter.new(@barcode) - @pdf = PDF::Writer.new - end - - it "should have registered annotate_pdf" do - Barcode.outputters.should include(:annotate_pdf) - end - - it "should have defined the annotate_pdf method" do - @outputter.should respond_to(:annotate_pdf) - end - - it "should return the pdf object it was given in annotate_pdf" do - @barcode.annotate_pdf(@pdf).object_id.should == @pdf.object_id - end - - it "should have x, y, height and xdim attributes" do - @outputter.should respond_to(:x) - @outputter.should respond_to(:y) - @outputter.should respond_to(:height) - @outputter.should respond_to(:xdim) - end - -end diff --git a/spec/png_outputter.rb b/spec/png_outputter.rb deleted file mode 100644 index 4ce3b2e..0000000 --- a/spec/png_outputter.rb +++ /dev/null @@ -1,50 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/outputter/png_outputter' -include Barby - -class TestBarcode < Barcode - def initialize(data) - @data = data - end - def encoding - @data - end -end - - -describe PngOutputter do - - before :each do - @barcode = TestBarcode.new('10110011100011110000') - @outputter = PngOutputter.new(@barcode) - end - - it "should register to_png and to_image" do - Barcode.outputters.should include(:to_png, :to_image) - end - - it "should return a ChunkyPNG::Datastream on to_datastream" do - @barcode.to_datastream.should be_an_instance_of(ChunkyPNG::Datastream) - end - - it "should return a string on to_png" do - @barcode.to_png.should be_an_instance_of(String) - end - - it "should return a ChunkyPNG::Image on to_canvas" do - @barcode.to_image.should be_an_instance_of(ChunkyPNG::Image) - end - - it "should have a width equal to Xdim * barcode_string.length" do - @outputter.width.should == @outputter.barcode.encoding.length * @outputter.xdim - end - - it "should have a full_width which is the sum of width + (margin*2)" do - @outputter.full_width.should == @outputter.width + (@outputter.margin*2) - end - - it "should have a full_height which is the sum of height + (margin*2)" do - @outputter.full_height.should == @outputter.height + (@outputter.margin*2) - end - -end diff --git a/spec/qr_code_spec.rb b/spec/qr_code_spec.rb deleted file mode 100644 index 8dd5c39..0000000 --- a/spec/qr_code_spec.rb +++ /dev/null @@ -1,78 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/qr_code' -include Barby - - -describe QrCode do - - before :each do - @data = 'Ereshkigal' - @code = QrCode.new(@data) - end - - it "should have the expected data" do - @code.data.should == @data - end - - it "should have the expected encoding" do - #Should be an array of strings, where each string - #represents a "line" - @code.encoding.should == rqrcode(@code).modules.map do |line| - line.inject(''){|s,m| s << (m ? '1' : '0') } - end - end - - it "should be able to change its data and output a different encoding" do - @code.data = 'hades' - @code.data.should == 'hades' - @code.encoding.should == rqrcode(@code).modules.map do |line| - line.inject(''){|s,m| s << (m ? '1' : '0') } - end - end - - it "should have a 'level' accessor" do - @code.should respond_to(:level) - @code.should respond_to(:level=) - end - - it "should set size according to size of data" do - QrCode.new('1'*15, :level => :l).size.should == 1 - QrCode.new('1'*15, :level => :m).size.should == 2 - QrCode.new('1'*15, :level => :q).size.should == 2 - QrCode.new('1'*15, :level => :h).size.should == 3 - - QrCode.new('1'*30, :level => :l).size.should == 2 - QrCode.new('1'*30, :level => :m).size.should == 3 - QrCode.new('1'*30, :level => :q).size.should == 3 - QrCode.new('1'*30, :level => :h).size.should == 4 - - QrCode.new('1'*270, :level => :l).size.should == 10 - end - - it "should allow size to be set manually" do - code = QrCode.new('1'*15, :level => :l, :size => 2) - code.size.should == 2 - code.encoding.should == rqrcode(code).modules.map do |line| - line.inject(''){|s,m| s << (m ? '1' : '0') } - end - end - - it "should raise ArgumentError when data too large" do - lambda{ QrCode.new('1'*2953, :level => :l) }.should_not raise_error(ArgumentError) - lambda{ QrCode.new('1'*2954, :level => :l) }.should raise_error(ArgumentError) - end - - it "should return the original data on to_s" do - @code.to_s.should == 'Ereshkigal' - end - - it "should include at most 20 characters on to_s" do - QrCode.new('123456789012345678901234567890').to_s.should == '12345678901234567890' - end - - - def rqrcode(code) - RQRCode::QRCode.new(code.data, :level => code.level, :size => code.size) - end - -end diff --git a/spec/rmagick_outputter_spec.rb b/spec/rmagick_outputter_spec.rb deleted file mode 100644 index 9eeaf42..0000000 --- a/spec/rmagick_outputter_spec.rb +++ /dev/null @@ -1,76 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/outputter/rmagick_outputter' -include Barby - -class TestBarcode < Barcode - def initialize(data) - @data = data - end - def encoding - @data - end -end - -describe RmagickOutputter do - - before :each do - @barcode = TestBarcode.new('10110011100011110000') - @outputter = RmagickOutputter.new(@barcode) - end - - it "should register to_png, to_gif, to_jpg, to_image" do - Barcode.outputters.should include(:to_png, :to_gif, :to_jpg, :to_image) - end - - it "should have defined to_png, to_gif, to_jpg, to_image" do - @outputter.should respond_to(:to_png, :to_gif, :to_jpg, :to_image) - end - - it "should return a string on to_png and to_gif" do - @outputter.to_png.should be_an_instance_of(String) - @outputter.to_gif.should be_an_instance_of(String) - end - - it "should return a Magick::Image instance on to_image" do - @outputter.to_image.should be_an_instance_of(Magick::Image) - end - - it "should have a width equal to the length of the barcode encoding string * x dimension" do - @outputter.xdim.should == 1#Default - @outputter.width.should == @outputter.barcode.encoding.length - @outputter.xdim = 2 - @outputter.width.should == @outputter.barcode.encoding.length * 2 - end - - it "should have a full_width equal to the width + left and right margins" do - @outputter.xdim.should == 1 - @outputter.margin.should == 10 - @outputter.full_width.should == (@outputter.width + 10 + 10) - end - - it "should have a default height of 100" do - @outputter.height.should == 100 - @outputter.height = 200 - @outputter.height.should == 200 - end - - it "should have a full_height equal to the height + top and bottom margins" do - @outputter.full_height.should == @outputter.height + (@outputter.margin * 2) - end - -end - -describe "Rmagickoutputter#to_image" do - - before :each do - @barcode = TestBarcode.new('10110011100011110000') - @outputter = RmagickOutputter.new(@barcode) - @image = @outputter.to_image - end - - it "should have a width and height equal to the outputter's full_width and full_height" do - @image.columns.should == @outputter.full_width - @image.rows.should == @outputter.full_height - end - -end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb deleted file mode 100644 index 335e6d3..0000000 --- a/spec/spec_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -$: << File.join(File.dirname(__FILE__), '..', 'lib') -require 'barby/vendor' diff --git a/spec/upc_supplemental.rb b/spec/upc_supplemental.rb deleted file mode 100644 index 524ea67..0000000 --- a/spec/upc_supplemental.rb +++ /dev/null @@ -1,110 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/upc_supplemental' -include Barby - -describe UPCSupplemental, 'validity' do - - it 'should be valid with 2 or 5 digits' do - UPCSupplemental.new('12345').should be_valid - UPCSupplemental.new('12').should be_valid - end - - it 'should not be valid with any number of digits other than 2 or 5' do - UPCSupplemental.new('1234').should_not be_valid - UPCSupplemental.new('123').should_not be_valid - UPCSupplemental.new('1').should_not be_valid - UPCSupplemental.new('123456').should_not be_valid - UPCSupplemental.new('123456789012').should_not be_valid - end - - it 'should not be valid with non-digit characters' do - UPCSupplemental.new('abcde').should_not be_valid - UPCSupplemental.new('ABC').should_not be_valid - UPCSupplemental.new('1234e').should_not be_valid - UPCSupplemental.new('!2345').should_not be_valid - UPCSupplemental.new('ab').should_not be_valid - UPCSupplemental.new('1b').should_not be_valid - UPCSupplemental.new('a1').should_not be_valid - end - -end - - -describe UPCSupplemental, 'checksum for 5 digits' do - - it 'should have the expected odd_digits' do - UPCSupplemental.new('51234').odd_digits.should == [4,2,5] - UPCSupplemental.new('54321').odd_digits.should == [1,3,5] - UPCSupplemental.new('99990').odd_digits.should == [0,9,9] - end - - it 'should have the expected even_digits' do - UPCSupplemental.new('51234').even_digits.should == [3,1] - UPCSupplemental.new('54321').even_digits.should == [2,4] - UPCSupplemental.new('99990').even_digits.should == [9,9] - end - - it 'should have the expected odd and even sums' do - UPCSupplemental.new('51234').odd_sum.should == 33 - UPCSupplemental.new('54321').odd_sum.should == 27 - UPCSupplemental.new('99990').odd_sum.should == 54 - - UPCSupplemental.new('51234').even_sum.should == 36 - UPCSupplemental.new('54321').even_sum.should == 54 - UPCSupplemental.new('99990').even_sum.should == 162 - end - - it 'should have the expected checksum' do - UPCSupplemental.new('51234').checksum.should == 9 - UPCSupplemental.new('54321').checksum.should == 1 - UPCSupplemental.new('99990').checksum.should == 6 - end - -end - - -describe UPCSupplemental, 'checksum for 2 digits' do - - - it 'should have the expected checksum' do - UPCSupplemental.new('51').checksum.should == 3 - UPCSupplemental.new('21').checksum.should == 1 - UPCSupplemental.new('99').checksum.should == 3 - end - - -end - - -describe UPCSupplemental, 'encoding' do - - before :each do - @data = '51234' - @code = UPCSupplemental.new(@data) - end - - it 'should have the expected encoding' do - # START 5 1 2 3 4 - UPCSupplemental.new('51234').encoding.should == '1011 0110001 01 0011001 01 0011011 01 0111101 01 0011101'.tr(' ', '') - # 9 9 9 9 0 - UPCSupplemental.new('99990').encoding.should == '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') - # START 5 1 - UPCSupplemental.new('51').encoding.should == '1011 0111001 01 0110011'.tr(' ', '') - # 2 2 - UPCSupplemental.new('22').encoding.should == '1011 0011011 01 0010011'.tr(' ', '') - end - - it 'should be able to change its data' do - prev_encoding = @code.encoding - @code.data = '99990' - @code.encoding.should_not == prev_encoding - # 9 9 9 9 0 - @code.encoding.should == '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') - prev_encoding = @code.encoding - @code.data = '22' - @code.encoding.should_not == prev_encoding - # 2 2 - @code.encoding.should == '1011 0011011 01 0010011'.tr(' ', '') - end - -end diff --git a/test/bookland_test.rb b/test/bookland_test.rb new file mode 100644 index 0000000..312d14c --- /dev/null +++ b/test/bookland_test.rb @@ -0,0 +1,57 @@ +require 'test_helper' + +class BooklandTest < Barby::TestCase + + before do + @isbn = '968-26-1240-3' + @code = Bookland.new(@isbn) + end + + it "should not touch the ISBN" do + @code.isbn.must_equal @isbn + end + + it "should have an isbn_only" do + @code.isbn_only.must_equal '968261240' + end + + it "should have the expected data" do + @code.data.must_equal '978968261240' + end + + it "should have the expected numbers" do + @code.numbers.must_equal [9,7,8,9,6,8,2,6,1,2,4,0] + end + + it "should have the expected checksum" do + @code.checksum.must_equal 4 + end + + it "should raise an error when data not valid" do + lambda{ Bookland.new('1234') }.must_raise ArgumentError + end + + describe 'ISBN conversion' do + + it "should accept ISBN with number system and check digit" do + code = Bookland.new('978-82-92526-14-9') + assert code.valid? + code.data.must_equal '978829252614' + end + + it "should accept ISBN without number system but with check digit" do + code = Bookland.new('82-92526-14-9') + assert code.valid? + code.data.must_equal '978829252614' + end + + it "should accept ISBN without number system or check digit" do + code = Bookland.new('82-92526-14') + assert code.valid? + code.data.must_equal '978829252614' + end + + end + +end + diff --git a/test/code_128_test.rb b/test/code_128_test.rb new file mode 100644 index 0000000..1f07a1d --- /dev/null +++ b/test/code_128_test.rb @@ -0,0 +1,347 @@ +#encoding: UTF-8 +require 'test_helper' + +class Code128Test < Barby::TestCase + + before do + @data = 'ABC123' + @code = Code128A.new(@data) + end + + it "should have the expected stop encoding (including termination bar 11)" do + @code.send(:stop_encoding).must_equal '1100011101011' + end + + it "should find the right class for a character A, B or C" do + @code.send(:class_for, 'A').must_equal Code128A + @code.send(:class_for, 'B').must_equal Code128B + @code.send(:class_for, 'C').must_equal Code128C + end + + it "should find the right change code for a class" do + @code.send(:change_code_for_class, Code128A).must_equal Code128::CODEA + @code.send(:change_code_for_class, Code128B).must_equal Code128::CODEB + @code.send(:change_code_for_class, Code128C).must_equal Code128::CODEC + end + + it "should not allow empty data" do + lambda{ Code128B.new("") }.must_raise(ArgumentError) + end + + describe "single encoding" do + + before do + @data = 'ABC123' + @code = Code128A.new(@data) + end + + it "should have the same data as when initialized" do + @code.data.must_equal @data + end + + it "should be able to change its data" do + @code.data = '123ABC' + @code.data.must_equal '123ABC' + @code.data.wont_equal @data + end + + it "should not have an extra" do + assert @code.extra.nil? + end + + it "should have empty extra encoding" do + @code.extra_encoding.must_equal '' + end + + it "should have the correct checksum" do + @code.checksum.must_equal 66 + end + + it "should return all data for to_s" do + @code.to_s.must_equal @data + end + + end + + describe "multiple encodings" do + + before do + @data = "ABC123\306def\3074567" + @code = Code128A.new(@data) + end + + it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do + @code.full_data.must_equal "ABC123def4567" + end + + it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do + @code.full_data_with_change_codes.must_equal @data + end + + it "should not matter if extras were added separately" do + code = Code128B.new("ABC") + code.extra = "\3071234" + code.full_data.must_equal "ABC1234" + code.full_data_with_change_codes.must_equal "ABC\3071234" + code.extra.extra = "\306abc" + code.full_data.must_equal "ABC1234abc" + code.full_data_with_change_codes.must_equal "ABC\3071234\306abc" + code.extra.extra.data = "abc\305DEF" + code.full_data.must_equal "ABC1234abcDEF" + code.full_data_with_change_codes.must_equal "ABC\3071234\306abc\305DEF" + code.extra.extra.full_data.must_equal "abcDEF" + code.extra.extra.full_data_with_change_codes.must_equal "abc\305DEF" + code.extra.full_data.must_equal "1234abcDEF" + code.extra.full_data_with_change_codes.must_equal "1234\306abc\305DEF" + end + + it "should have a Code B extra" do + @code.extra.must_be_instance_of(Code128B) + end + + it "should have a valid extra" do + assert @code.extra.valid? + end + + it "the extra should also have an extra of type C" do + @code.extra.extra.must_be_instance_of(Code128C) + end + + it "the extra's extra should be valid" do + assert @code.extra.extra.valid? + end + + it "should not have more than two extras" do + assert @code.extra.extra.extra.nil? + end + + it "should split extra data from string on data assignment" do + @code.data = "123\306abc" + @code.data.must_equal '123' + @code.extra.must_be_instance_of(Code128B) + @code.extra.data.must_equal 'abc' + end + + it "should be be able to change its extra" do + @code.extra = "\3071234" + @code.extra.must_be_instance_of(Code128C) + @code.extra.data.must_equal '1234' + end + + it "should split extra data from string on extra assignment" do + @code.extra = "\306123\3074567" + @code.extra.must_be_instance_of(Code128B) + @code.extra.data.must_equal '123' + @code.extra.extra.must_be_instance_of(Code128C) + @code.extra.extra.data.must_equal '4567' + end + + it "should not fail on newlines in extras" do + code = Code128B.new("ABC\305\n") + code.data.must_equal "ABC" + code.extra.must_be_instance_of(Code128A) + code.extra.data.must_equal "\n" + code.extra.extra = "\305\n\n\n\n\n\nVALID" + code.extra.extra.data.must_equal "\n\n\n\n\n\nVALID" + end + + it "should raise an exception when extra string doesn't start with the special code character" do + lambda{ @code.extra = '123' }.must_raise ArgumentError + end + + it "should have the correct checksum" do + @code.checksum.must_equal 84 + end + + it "should have the expected encoding" do + #STARTA A B C 1 2 3 + @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ + #CODEB d e f + '10111101110100001001101011001000010110000100'+ + #CODEC 45 67 + '101110111101011101100010000101100'+ + #CHECK=84 STOP + '100111101001100011101011' + end + + it "should return all data including extras, except change codes for to_s" do + @code.to_s.must_equal "ABC123def4567" + end + + end + + describe "128A" do + + before do + @data = 'ABC123' + @code = Code128A.new(@data) + end + + it "should be valid when given valid data" do + assert @code.valid? + end + + it "should not be valid when given invalid data" do + @code.data = 'abc123' + refute @code.valid? + end + + it "should have the expected characters" do + @code.characters.must_equal %w(A B C 1 2 3) + end + + it "should have the expected start encoding" do + @code.start_encoding.must_equal '11010000100' + end + + it "should have the expected data encoding" do + @code.data_encoding.must_equal '101000110001000101100010001000110100111001101100111001011001011100' + end + + it "should have the expected encoding" do + @code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' + end + + it "should have the expected checksum encoding" do + @code.checksum_encoding.must_equal '10010000110' + end + + end + + describe "128B" do + + before do + @data = 'abc123' + @code = Code128B.new(@data) + end + + it "should be valid when given valid data" do + assert @code.valid? + end + + it "should not be valid when given invalid data" do + @code.data = 'abc£123' + refute @code.valid? + end + + it "should have the expected characters" do + @code.characters.must_equal %w(a b c 1 2 3) + end + + it "should have the expected start encoding" do + @code.start_encoding.must_equal '11010010000' + end + + it "should have the expected data encoding" do + @code.data_encoding.must_equal '100101100001001000011010000101100100111001101100111001011001011100' + end + + it "should have the expected encoding" do + @code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' + end + + it "should have the expected checksum encoding" do + @code.checksum_encoding.must_equal '11011101110' + end + + end + + describe "128C" do + + before do + @data = '123456' + @code = Code128C.new(@data) + end + + it "should be valid when given valid data" do + assert @code.valid? + end + + it "should not be valid when given invalid data" do + @code.data = '123' + refute @code.valid? + @code.data = 'abc' + refute @code.valid? + end + + it "should have the expected characters" do + @code.characters.must_equal %w(12 34 56) + end + + it "should have the expected start encoding" do + @code.start_encoding.must_equal '11010011100' + end + + it "should have the expected data encoding" do + @code.data_encoding.must_equal '101100111001000101100011100010110' + end + + it "should have the expected encoding" do + @code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' + end + + it "should have the expected checksum encoding" do + @code.checksum_encoding.must_equal '10001101110' + end + + end + + describe "Function characters" do + + it "should retain the special symbols in the data accessor" do + Code128A.new("\301ABC\301DEF").data.must_equal "\301ABC\301DEF" + Code128B.new("\301ABC\302DEF").data.must_equal "\301ABC\302DEF" + Code128C.new("\301123456").data.must_equal "\301123456" + Code128C.new("12\30134\30156").data.must_equal "12\30134\30156" + end + + it "should keep the special symbols as characters" do + Code128A.new("\301ABC\301DEF").characters.must_equal %W(\301 A B C \301 D E F) + Code128B.new("\301ABC\302DEF").characters.must_equal %W(\301 A B C \302 D E F) + Code128C.new("\301123456").characters.must_equal %W(\301 12 34 56) + Code128C.new("12\30134\30156").characters.must_equal %W(12 \301 34 \301 56) + end + + it "should not allow FNC > 1 for Code C" do + lambda{ Code128C.new("12\302") }.must_raise ArgumentError + lambda{ Code128C.new("\30312") }.must_raise ArgumentError + lambda{ Code128C.new("12\304") }.must_raise ArgumentError + end + + it "should be included in the encoding" do + a = Code128A.new("\301AB") + a.data_encoding.must_equal '111101011101010001100010001011000' + a.encoding.must_equal '11010000100111101011101010001100010001011000101000011001100011101011' + end + + end + + describe "Code128 with type" do + + it "should raise an exception when not given a type" do + lambda{ Code128.new('abc') }.must_raise(ArgumentError) + end + + it "should raise an exception when given a non-existent type" do + lambda{ Code128.new('abc', 'F') }.must_raise(ArgumentError) + end + + it "should give the right encoding for type A" do + code = Code128.new('ABC123', 'A') + code.encoding.must_equal '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' + end + + it "should give the right encoding for type B" do + code = Code128.new('abc123', 'B') + code.encoding.must_equal '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' + end + + it "should give the right encoding for type B" do + code = Code128.new('123456', 'C') + code.encoding.must_equal '11010011100101100111001000101100011100010110100011011101100011101011' + end + + end + +end + diff --git a/test/code_25_iata_test.rb b/test/code_25_iata_test.rb new file mode 100644 index 0000000..5f53e10 --- /dev/null +++ b/test/code_25_iata_test.rb @@ -0,0 +1,18 @@ +require 'test_helper' + +class Code25IATATest < Barby::TestCase + + before do + @data = '0123456789' + @code = Code25IATA.new(@data) + end + + it "should have the expected start_encoding" do + @code.start_encoding.must_equal '1010' + end + + it "should have the expected stop_encoding" do + @code.stop_encoding.must_equal '11101' + end + +end diff --git a/test/code_25_interleaved_test.rb b/test/code_25_interleaved_test.rb new file mode 100644 index 0000000..c15de9b --- /dev/null +++ b/test/code_25_interleaved_test.rb @@ -0,0 +1,115 @@ +require 'test_helper' + +class Code25InterleavedTest < Barby::TestCase + + before do + @data = '12345670' + @code = Code25Interleaved.new(@data) + end + + it "should have the expected digit_pairs" do + @code.digit_pairs.must_equal [[1,2],[3,4],[5,6],[7,0]] + end + + it "should have the expected digit_encodings" do + @code.digit_encodings.must_equal %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110) + end + + it "should have the expected start_encoding" do + @code.start_encoding.must_equal '1010' + end + + it "should have the expected stop_encoding" do + @code.stop_encoding.must_equal '11101' + end + + it "should have the expected data_encoding" do + @code.data_encoding.must_equal "111010001010111000111011101000101000111010001110001010101010001110001110" + end + + it "should have the expected encoding" do + @code.encoding.must_equal "101011101000101011100011101110100010100011101000111000101010101000111000111011101" + end + + it "should be valid" do + assert @code.valid? + end + + it "should return the expected encoding for parameters passed to encoding_for_interleaved" do + w, n = Code25Interleaved::WIDE, Code25Interleaved::NARROW + # 1 2 1 2 1 2 1 2 1 2 digits 1 and 2 + # B S B S B S B S B S bars and spaces + @code.encoding_for_interleaved(w,n,n,w,n,n,n,n,w,w).must_equal '111010001010111000' + # 3 4 3 4 3 4 3 4 3 4 digits 3 and 4 + # B S B S B S B S B S bars and spaces + @code.encoding_for_interleaved(w,n,w,n,n,w,n,n,n,w).must_equal '111011101000101000' + end + + it "should return all characters in sequence for to_s" do + @code.to_s.must_equal @code.characters.join + end + + describe "with checksum" do + + before do + @data = '1234567' + @code = Code25Interleaved.new(@data) + @code.include_checksum = true + end + + it "should have the expected digit_pairs_with_checksum" do + @code.digit_pairs_with_checksum.must_equal [[1,2],[3,4],[5,6],[7,0]] + end + + it "should have the expected digit_encodings_with_checksum" do + @code.digit_encodings_with_checksum.must_equal %w(111010001010111000 111011101000101000 111010001110001010 101010001110001110) + end + + it "should have the expected data_encoding_with_checksum" do + @code.data_encoding_with_checksum.must_equal "111010001010111000111011101000101000111010001110001010101010001110001110" + end + + it "should have the expected encoding" do + @code.encoding.must_equal "101011101000101011100011101110100010100011101000111000101010101000111000111011101" + end + + it "should be valid" do + assert @code.valid? + end + + it "should return all characters including checksum in sequence on to_s" do + @code.to_s.must_equal @code.characters_with_checksum.join + end + + end + + describe "with invalid number of digits" do + + before do + @data = '1234567' + @code = Code25Interleaved.new(@data) + end + + it "should not be valid" do + refute @code.valid? + end + + it "should raise ArgumentError on all encoding methods" do + lambda{ @code.encoding }.must_raise(ArgumentError) + lambda{ @code.data_encoding }.must_raise(ArgumentError) + lambda{ @code.digit_encodings }.must_raise(ArgumentError) + end + + it "should not raise ArgumentError on encoding methods that include checksum" do + b = Code25Interleaved.new(@data) + b.include_checksum = true + b.encoding + @code.data_encoding_with_checksum + @code.digit_encodings_with_checksum + end + + end + +end + + diff --git a/test/code_25_test.rb b/test/code_25_test.rb new file mode 100644 index 0000000..ec99f44 --- /dev/null +++ b/test/code_25_test.rb @@ -0,0 +1,109 @@ +require 'test_helper' + +class Code25Test < Barby::TestCase + + before do + @data = "1234567" + @code = Code25.new(@data) + end + + it "should return the same data it was given" do + @code.data.must_equal @data + end + + it "should have the expected characters" do + @code.characters.must_equal %w(1 2 3 4 5 6 7) + end + + it "should have the expected characters_with_checksum" do + @code.characters_with_checksum.must_equal %w(1 2 3 4 5 6 7 0) + end + + it "should have the expected digits" do + @code.digits.must_equal [1,2,3,4,5,6,7] + end + + it "should have the expected digits_with_checksum" do + @code.digits_with_checksum.must_equal [1,2,3,4,5,6,7,0] + end + + it "should have the expected even_and_odd_digits" do + @code.even_and_odd_digits.must_equal [[7,5,3,1], [6,4,2]] + end + + it "should have the expected start_encoding" do + @code.start_encoding.must_equal '1110111010' + end + + it "should have the expected stop_encoding" do + @code.stop_encoding.must_equal '111010111' + end + + it "should have a default narrow_width of 1" do + @code.narrow_width.must_equal 1 + end + + it "should have a default wide_width equal to narrow_width * 3" do + @code.wide_width.must_equal @code.narrow_width * 3 + @code.narrow_width = 2 + @code.wide_width.must_equal 6 + end + + it "should have a default space_width equal to narrow_width" do + @code.space_width.must_equal @code.narrow_width + @code.narrow_width = 23 + @code.space_width.must_equal 23 + end + + it "should have the expected digit_encodings" do + @code.digit_encodings.must_equal %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110) + end + + it "should have the expected digit_encodings_with_checksum" do + @code.digit_encodings_with_checksum.must_equal %w(11101010101110 10111010101110 11101110101010 10101110101110 11101011101010 10111011101010 10101011101110 10101110111010) + end + + it "should have the expected data_encoding" do + @code.data_encoding.must_equal "11101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110" + end + + it "should have the expected checksum" do + @code.checksum.must_equal 0 + end + + it "should have the expected checksum_encoding" do + @code.checksum_encoding.must_equal '10101110111010' + end + + it "should have the expected encoding" do + @code.encoding.must_equal "111011101011101010101110101110101011101110111010101010101110101110111010111010101011101110101010101011101110111010111" + end + + it "should be valid" do + assert @code.valid? + end + + it "should not be valid" do + @code.data = 'abc' + refute @code.valid? + end + + it "should raise on encoding methods that include data encoding if not valid" do + @code.data = 'abc' + lambda{ @code.encoding }.must_raise ArgumentError + lambda{ @code.data_encoding }.must_raise ArgumentError + lambda{ @code.data_encoding_with_checksum }.must_raise ArgumentError + lambda{ @code.digit_encodings }.must_raise ArgumentError + lambda{ @code.digit_encodings_with_checksum }.must_raise ArgumentError + end + + it "should return all characters in sequence on to_s" do + @code.to_s.must_equal @code.characters.join + end + + it "should include checksum in to_s when include_checksum is true" do + @code.include_checksum = true + @code.to_s.must_equal @code.characters_with_checksum.join + end + +end diff --git a/test/code_39_test.rb b/test/code_39_test.rb new file mode 100644 index 0000000..289632b --- /dev/null +++ b/test/code_39_test.rb @@ -0,0 +1,208 @@ +require 'test_helper' + +class Code39Test < Barby::TestCase + + before do + @data = 'TEST8052' + @code = Code39.new(@data) + @code.spacing = 3 + end + + it "should yield self on initialize" do + c1 = nil + c2 = Code39.new('TEST'){|c| c1 = c } + c1.must_equal c2 + end + + it "should have the expected data" do + @code.data.must_equal @data + end + + it "should have the expected characters" do + @code.characters.must_equal @data.split(//) + end + + it "should have the expected start_encoding" do + @code.start_encoding.must_equal '100101101101' + end + + it "should have the expected stop_encoding" do + @code.stop_encoding.must_equal '100101101101' + end + + it "should have the expected spacing_encoding" do + @code.spacing_encoding.must_equal '000' + end + + it "should have the expected encoded characters" do + @code.encoded_characters.must_equal %w(101011011001 110101100101 101101011001 101011011001 110100101101 101001101101 110100110101 101100101011) + end + + it "should have the expected data_encoding" do + @code.data_encoding.must_equal '101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011' + end + + it "should have the expected encoding" do + @code.encoding.must_equal '100101101101000101011011001000110101100101000101101011001000101011011001000110100101101000101001101101000110100110101000101100101011000100101101101' + end + + it "should be valid" do + assert @code.valid? + end + + it "should not be valid" do + @code.data = "123\200456" + refute @code.valid? + end + + it "should raise an exception when data is not valid on initialization" do + lambda{ Code39.new('abc') }.must_raise(ArgumentError) + end + + it "should return all characters in sequence without checksum on to_s" do + @code.to_s.must_equal @data + end + + describe "Checksumming" do + + before do + @code = Code39.new('CODE39') + end + + it "should have the expected checksum" do + @code.checksum.must_equal 32 + end + + it "should have the expected checksum_character" do + @code.checksum_character.must_equal 'W' + end + + it "should have the expected checksum_encoding" do + @code.checksum_encoding.must_equal '110011010101' + end + + it "should have the expected characters_with_checksum" do + @code.characters_with_checksum.must_equal %w(C O D E 3 9 W) + end + + it "should have the expected encoded_characters_with_checksum" do + @code.encoded_characters_with_checksum.must_equal %w(110110100101 110101101001 101011001011 110101100101 110110010101 101100101101 110011010101) + end + + it "should have the expected data_encoding_with_checksum" do + @code.data_encoding_with_checksum.must_equal "110110100101011010110100101010110010110110101100101011011001010101011001011010110011010101" + end + + it "should have the expected encoding_with_checksum" do + @code.encoding_with_checksum.must_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" + end + + it "should return the encoding with checksum when include_checksum == true" do + @code.include_checksum = true + @code.encoding.must_equal "10010110110101101101001010110101101001010101100101101101011001010110110010101010110010110101100110101010100101101101" + end + + end + + describe "Normal encoding" do + + before do + @data = 'ABC$%' + @code = Code39.new(@data) + end + + it "should have the expected characters" do + @code.characters.must_equal %w(A B C $ %) + end + + it "should have the expected encoded_characters" do + @code.encoded_characters.must_equal %w(110101001011 101101001011 110110100101 100100100101 101001001001) + end + + it "should have the expected data_encoding" do + @code.data_encoding.must_equal '1101010010110101101001011011011010010101001001001010101001001001' + end + + it "should not be valid" do + @code.data = 'abc' + refute @code.valid? + end + + end + + describe "Extended encoding" do + + before do + @data = '<abc>' + @code = Code39.new(@data, true) + end + + it "should return true on extended?" do + assert @code.extended? + end + + it "should have the expected characters" do + @code.characters.must_equal %w(% G + A + B + C % I) + end + + it "should have the expected encoded_characters" do + @code.encoded_characters.must_equal %w(101001001001 101010011011 100101001001 110101001011 100101001001 101101001011 100101001001 110110100101 101001001001 101101001101) + end + + it "should have the expected data_encoding" do + @code.data_encoding.must_equal '101001001001010101001101101001010010010110101001011010010100100101011010010110100101001001011011010010101010010010010101101001101' + end + + it "should have the expected encoding" do + @code.encoding.must_equal '10010110110101010010010010101010011011010010100100101101010010110100101001001'+ + '010110100101101001010010010110110100101010100100100101011010011010100101101101' + end + + it "should take a second parameter on initialize indicating it is extended" do + assert Code39.new('abc', true).extended? + refute Code39.new('ABC', false).extended? + refute Code39.new('ABC').extended? + end + + it "should be valid" do + assert @code.valid? + end + + it "should not be valid" do + @code.data = "abc\200123" + refute @code.valid? + end + + it "should return all characters in sequence without checksum on to_s" do + @code.to_s.must_equal @data + end + + end + + describe "Variable widths" do + + before do + @data = 'ABC$%' + @code = Code39.new(@data) + @code.narrow_width = 2 + @code.wide_width = 5 + end + + it "should have the expected encoded_characters" do + @code.encoded_characters.must_equal %w(111110011001100000110011111 110011111001100000110011111 111110011111001100000110011 110000011000001100000110011 110011000001100000110000011) + end + + it "should have the expected data_encoding" do + # A SB SC S$ S% + @code.data_encoding.must_equal '1111100110011000001100111110110011111001100000110011111011111001111100110000011001101100000110000011000001100110110011000001100000110000011' + + @code.spacing = 3 + # A S B S C S $ S % + @code.data_encoding.must_equal '111110011001100000110011111000110011111001100000110011111000111110011111001100000110011000110000011000001100000110011000110011000001100000110000011' + end + + end + +end + + diff --git a/test/code_93_test.rb b/test/code_93_test.rb new file mode 100644 index 0000000..d59203e --- /dev/null +++ b/test/code_93_test.rb @@ -0,0 +1,142 @@ +require 'test_helper' + +class Code93Test < Barby::TestCase + + before do + @data = 'TEST93' + @code = Code93.new(@data) + end + + it "should return the same data we put in" do + @code.data.must_equal @data + end + + it "should have the expected characters" do + @code.characters.must_equal @data.split(//) + end + + it "should have the expected start_encoding" do + @code.start_encoding.must_equal '101011110' + end + + it "should have the expected stop_encoding" do + # STOP TERM + @code.stop_encoding.must_equal '1010111101' + end + + it "should have the expected encoded characters" do + # T E S T 9 3 + @code.encoded_characters.must_equal %w(110100110 110010010 110101100 110100110 100001010 101000010) + end + + it "should have the expected data_encoding" do + # T E S T 9 3 + @code.data_encoding.must_equal "110100110110010010110101100110100110100001010101000010" + end + + it "should have the expected data_encoding_with_checksums" do + # T E S T 9 3 + (C) 6 (K) + @code.data_encoding_with_checksums.must_equal "110100110110010010110101100110100110100001010101000010101110110100100010" + end + + it "should have the expected encoding" do + # START T E S T 9 3 + (C) 6 (K) STOP TERM + @code.encoding.must_equal "1010111101101001101100100101101011001101001101000010101010000101011101101001000101010111101" + end + + it "should have the expected checksum_values" do + @code.checksum_values.must_equal [29, 14, 28, 29, 9, 3].reverse #! + end + + it "should have the expected c_checksum" do + @code.c_checksum.must_equal 41 #calculate this first! + end + + it "should have the expected c_checksum_character" do + @code.c_checksum_character.must_equal '+' + end + + it "should have the expected c_checksum_encoding" do + @code.c_checksum_encoding.must_equal '101110110' + end + + it "should have the expected checksum_values_with_c_checksum" do + @code.checksum_values_with_c_checksum.must_equal [29, 14, 28, 29, 9, 3, 41].reverse #! + end + + it "should have the expected k_checksum" do + @code.k_checksum.must_equal 6 #calculate this first! + end + + it "should have the expected k_checksum_character" do + @code.k_checksum_character.must_equal '6' + end + + it "should have the expected k_checksum_encoding" do + @code.k_checksum_encoding.must_equal '100100010' + end + + it "should have the expected checksums" do + @code.checksums.must_equal [41, 6] + end + + it "should have the expected checksum_characters" do + @code.checksum_characters.must_equal ['+', '6'] + end + + it "should have the expected checksum_encodings" do + @code.checksum_encodings.must_equal %w(101110110 100100010) + end + + it "should have the expected checksum_encoding" do + @code.checksum_encoding.must_equal '101110110100100010' + end + + it "should be valid" do + assert @code.valid? + end + + it "should not be valid when not in extended mode" do + @code.data = 'not extended' + end + + it "should return data with no checksums on to_s" do + @code.to_s.must_equal 'TEST93' + end + + describe "Extended mode" do + + before do + @data = "Extended!" + @code = Code93.new(@data) + end + + it "should be extended" do + assert @code.extended? + end + + it "should convert extended characters to special shift characters" do + @code.characters.must_equal ["E", "\304", "X", "\304", "T", "\304", "E", "\304", "N", "\304", "D", "\304", "E", "\304", "D", "\303", "A"] + end + + it "should have the expected data_encoding" do + @code.data_encoding.must_equal '110010010100110010101100110100110010110100110100110010110010010'+ + '100110010101000110100110010110010100100110010110010010100110010110010100111010110110101000' + end + + it "should have the expected c_checksum" do + @code.c_checksum.must_equal 9 + end + + it "should have the expected k_checksum" do + @code.k_checksum.must_equal 46 + end + + it "should return the original data on to_s with no checksums" do + @code.to_s.must_equal 'Extended!' + end + + end + +end + diff --git a/spec/data_matrix_spec.rb b/test/data_matrix_test.rb similarity index 72% rename from spec/data_matrix_spec.rb rename to test/data_matrix_test.rb index 5fac45c..6e971b7 100644 --- a/spec/data_matrix_spec.rb +++ b/test/data_matrix_test.rb @@ -1,31 +1,30 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') +require 'test_helper' require 'barby/barcode/data_matrix' +class DataMatrixTest < Barby::TestCase -describe Barby::DataMatrix do - - before :each do + before do @data = "humbaba" @code = Barby::DataMatrix.new(@data) end it "should have the expected encoding" do - @code.encoding.should == ["1010101010101010", "1011111000011111", "1110111000010100", + @code.encoding.must_equal ["1010101010101010", "1011111000011111", "1110111000010100", "1110100100000111", "1101111010101000", "1101111011110011", "1111111100000100", "1100101111110001", "1001000010001010", "1101010110111011", "1000000100011110", "1001010010000011", "1101100111011110", "1110111010000101", "1110010110001010", "1111111111111111"] end it "should return data on to_s" do - @code.to_s.should == @data + @code.to_s.must_equal @data end it "should be able to change its data" do prev_encoding = @code.encoding @code.data = "after eight" - @code.encoding.should_not == prev_encoding + @code.encoding.wont_equal prev_encoding end end diff --git a/test/ean13_test.rb b/test/ean13_test.rb new file mode 100644 index 0000000..a079f58 --- /dev/null +++ b/test/ean13_test.rb @@ -0,0 +1,168 @@ +require 'test_helper' + +class EAN13Test < Barby::TestCase + + describe 'validations' do + + before do + @valid = EAN13.new('123456789012') + end + + it "should be valid with 12 digits" do + assert @valid.valid? + end + + it "should not be valid with non-digit characters" do + @valid.data = "The shit apple doesn't fall far from the shit tree" + refute @valid.valid? + end + + it "should not be valid with less than 12 digits" do + @valid.data = "12345678901" + refute @valid.valid? + end + + it "should not be valid with more than 12 digits" do + @valid.data = "1234567890123" + refute @valid.valid? + end + + it "should raise an exception when data is invalid" do + lambda{ EAN13.new('123') }.must_raise(ArgumentError) + end + + end + + describe 'data' do + + before do + @data = '007567816412' + @code = EAN13.new(@data) + end + + it "should have the same data as was passed to it" do + @code.data.must_equal @data + end + + it "should have the expected characters" do + @code.characters.must_equal @data.split(//) + end + + it "should have the expected numbers" do + @code.numbers.must_equal @data.split(//).map{|s| s.to_i } + end + + it "should have the expected odd_and_even_numbers" do + @code.odd_and_even_numbers.must_equal [[2,4,1,7,5,0], [1,6,8,6,7,0]] + end + + it "should have the expected left_numbers" do + #0=second number in number system code + @code.left_numbers.must_equal [0,7,5,6,7,8] + end + + it "should have the expected right_numbers" do + @code.right_numbers.must_equal [1,6,4,1,2,5]#5=checksum + end + + it "should have the expected numbers_with_checksum" do + @code.numbers_with_checksum.must_equal @data.split(//).map{|s| s.to_i } + [5] + end + + it "should have the expected data_with_checksum" do + @code.data_with_checksum.must_equal @data+'5' + end + + it "should return all digits and the checksum on to_s" do + @code.to_s.must_equal '0075678164125' + end + + end + + describe 'checksum' do + + before do + @code = EAN13.new('007567816412') + end + + it "should have the expected weighted_sum" do + @code.weighted_sum.must_equal 85 + @code.data = '007567816413' + @code.weighted_sum.must_equal 88 + end + + it "should have the correct checksum" do + @code.checksum.must_equal 5 + @code.data = '007567816413' + @code.checksum.must_equal 2 + end + + it "should have the correct checksum_encoding" do + @code.checksum_encoding.must_equal '1001110' + end + + end + + describe 'encoding' do + + before do + @code = EAN13.new('750103131130') + end + + it "should have the expected checksum" do + @code.checksum.must_equal 9 + end + + it "should have the expected checksum_encoding" do + @code.checksum_encoding.must_equal '1110100' + end + + it "should have the expected left_parity_map" do + @code.left_parity_map.must_equal [:odd, :even, :odd, :even, :odd, :even] + end + + it "should have the expected left_encodings" do + @code.left_encodings.must_equal %w(0110001 0100111 0011001 0100111 0111101 0110011) + end + + it "should have the expected right_encodings" do + @code.right_encodings.must_equal %w(1000010 1100110 1100110 1000010 1110010 1110100) + end + + it "should have the expected left_encoding" do + @code.left_encoding.must_equal '011000101001110011001010011101111010110011' + end + + it "should have the expected right_encoding" do + @code.right_encoding.must_equal '100001011001101100110100001011100101110100' + end + + it "should have the expected encoding" do + #Start Left Center Right Stop + @code.encoding.must_equal '101' + '011000101001110011001010011101111010110011' + '01010' + '100001011001101100110100001011100101110100' + '101' + end + + end + + describe 'static data' do + + before :each do + @code = EAN13.new('123456789012') + end + + it "should have the expected start_encoding" do + @code.start_encoding.must_equal '101' + end + + it "should have the expected stop_encoding" do + @code.stop_encoding.must_equal '101' + end + + it "should have the expected center_encoding" do + @code.center_encoding.must_equal '01010' + end + + end + +end + diff --git a/test/ean8_test.rb b/test/ean8_test.rb new file mode 100644 index 0000000..88bd1d3 --- /dev/null +++ b/test/ean8_test.rb @@ -0,0 +1,99 @@ +require 'test_helper' + +class EAN8Test < Barby::TestCase + + describe 'validations' do + + before do + @valid = EAN8.new('1234567') + end + + it "should be valid with 7 digits" do + assert @valid.valid? + end + + it "should not be valid with less than 7 digits" do + @valid.data = '123456' + refute @valid.valid? + end + + it "should not be valid with more than 7 digits" do + @valid.data = '12345678' + refute @valid.valid? + end + + it "should not be valid with non-digits" do + @valid.data = 'abcdefg' + refute @valid.valid? + end + + end + + describe 'checksum' do + + before :each do + @code = EAN8.new('5512345') + end + + it "should have the expected weighted_sum" do + @code.weighted_sum.must_equal 53 + end + + it "should have the expected checksum" do + @code.checksum.must_equal 7 + end + + end + + describe 'data' do + + before :each do + @data = '5512345' + @code = EAN8.new(@data) + end + + it "should have the expected data" do + @code.data.must_equal @data + end + + it "should have the expected odd_and_even_numbers" do + @code.odd_and_even_numbers.must_equal [[5,3,1,5],[4,2,5]] + end + + it "should have the expected left_numbers" do + #EAN-8 includes the first character in the left-hand encoding, unlike EAN-13 + @code.left_numbers.must_equal [5,5,1,2] + end + + it "should have the expected right_numbers" do + @code.right_numbers.must_equal [3,4,5,7] + end + + it "should return the data with checksum on to_s" do + @code.to_s.must_equal '55123457' + end + + end + + describe 'encoding' do + + before :each do + @code = EAN8.new('5512345') + end + + it "should have the expected left_parity_map" do + @code.left_parity_map.must_equal [:odd, :odd, :odd, :odd] + end + + it "should have the expected left_encoding" do + @code.left_encoding.must_equal '0110001011000100110010010011' + end + + it "should have the expected right_encoding" do + @code.right_encoding.must_equal '1000010101110010011101000100' + end + + end + +end + diff --git a/spec/gs1_128_spec.rb b/test/gs1_128_test.rb similarity index 50% rename from spec/gs1_128_spec.rb rename to test/gs1_128_test.rb index 388cbdc..1aee0b4 100644 --- a/spec/gs1_128_spec.rb +++ b/test/gs1_128_test.rb @@ -1,68 +1,66 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/gs1_128' -include Barby +require 'test_helper' -describe GS1128 do +class GS1128Test < Barby::TestCase - before :each do + before do @code = GS1128.new('071230', 'C', '11') end it "should inherit Code128" do - GS1128.superclass.should == Code128 + GS1128.superclass.must_equal Code128 end it "should have an application_identifier attribute" do - @code.should respond_to(:application_identifier) - @code.should respond_to(:application_identifier=) + @code.must_respond_to(:application_identifier) + @code.must_respond_to(:application_identifier=) end it "should have the given application identifier" do - @code.application_identifier.should == '11' + @code.application_identifier.must_equal '11' end it "should have an application_identifier_encoding" do - @code.should respond_to(:application_identifier_encoding) + @code.must_respond_to(:application_identifier_encoding) end it "should have the expected application_identifier_number" do - @code.application_identifier_number.should == 11 + @code.application_identifier_number.must_equal 11 end it "should have the expected application identifier encoding" do - @code.application_identifier_encoding.should == '11000100100'#Code C number 11 + @code.application_identifier_encoding.must_equal '11000100100'#Code C number 11 end it "should have data with FNC1 and AI" do - @code.data.should == "\30111071230" + @code.data.must_equal "\30111071230" end it "should have partial_data without FNC1 or AI" do - @code.partial_data.should == '071230' + @code.partial_data.must_equal '071230' end it "should have characters that include FNC1 and AI" do - @code.characters.should == %W(\301 11 07 12 30) + @code.characters.must_equal %W(\301 11 07 12 30) end it "should have data_encoding that includes FNC1 and the AI" do - @code.data_encoding.should == '1111010111011000100100100110001001011001110011011011000' + @code.data_encoding.must_equal '1111010111011000100100100110001001011001110011011011000' end it "should have the expected checksum" do - @code.checksum.should == 36 + @code.checksum.must_equal 36 end it "should have the expected checksum encoding" do @code.checksum_encoding == '10110001000' end it "should have the expected encoding" do - @code.encoding.should == '110100111001111010111011000100100100110001001011001110011011011000101100010001100011101011' + @code.encoding.must_equal '110100111001111010111011000100100100110001001011001110011011011000101100010001100011101011' end it "should return full data excluding change codes, including AI on to_s" do - @code.to_s.should == '(11) 071230' + @code.to_s.must_equal '(11) 071230' end end diff --git a/spec/cairo_outputter_spec.rb b/test/outputter/cairo_outputter_test.rb similarity index 58% rename from spec/cairo_outputter_spec.rb rename to test/outputter/cairo_outputter_test.rb index 5f77f78..a5ef82d 100644 --- a/spec/cairo_outputter_spec.rb +++ b/test/outputter/cairo_outputter_test.rb @@ -1,124 +1,125 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/outputter' -require 'barby/outputter/cairo_outputter' +require 'test_helper' -describe Barby::CairoOutputter do +class CairoOutputterTest < Barby::TestCase + def ps_available? Cairo.const_defined?(:PSSurface) end def eps_available? - ps_available? and Cairo::PSSurface.respond_to?(:eps=) + ps_available? and Cairo::PSSurface.method_defined?(:eps=) end def pdf_available? Cairo.const_defined?(:PDFSurface) end def svg_available? Cairo.const_defined?(:SVGSurface) end - before :each do + before do + load_outputter('cairo') @barcode = Barby::Barcode.new def @barcode.encoding; '101100111000'; end @outputter = Barby::CairoOutputter.new(@barcode) @outputters = Barby::Barcode.outputters @surface = Cairo::ImageSurface.new(100, 100) @context = Cairo::Context.new(@surface) end it "should have defined the render_to_cairo_context method" do - @outputters.should include(:render_to_cairo_context) + @outputters.must_include(:render_to_cairo_context) end it "should have defined the to_png method" do - @outputters.should include(:to_png) + @outputters.must_include(:to_png) end it "should have defined the to_ps and to_eps method if available" do if ps_available? - @outputters.should include(:to_ps) + @outputters.must_include(:to_ps) if eps_available? - @outputters.should include(:to_eps) + @outputters.must_include(:to_eps) else - @outputters.should_not include(:to_eps) + @outputters.wont_include(:to_eps) end else - @outputters.should_not include(:to_ps) - @outputters.should_not include(:to_eps) + @outputters.wont_include(:to_ps) + @outputters.wont_include(:to_eps) end end it "should have defined the to_pdf method if available" do if pdf_available? - @outputters.should include(:to_pdf) + @outputters.must_include(:to_pdf) else - @outputters.should_not include(:to_pdf) + @outputters.wont_include(:to_pdf) end end it "should have defined the to_svg method if available" do if svg_available? - @outputters.should include(:to_svg) + @outputters.must_include(:to_svg) else - @outputters.should_not include(:to_svg) + @outputters.wont_include(:to_svg) end end it "should return the cairo context object it was given in render_to_cairo_context" do - @barcode.render_to_cairo_context(@context).object_id.should == @context.object_id + @barcode.render_to_cairo_context(@context).object_id.must_equal @context.object_id end it "should return PNG image by the to_png method" do - @barcode.to_png.should match(/\A\x89PNG/) + @barcode.to_png.must_match(/\A\x89PNG/) end it "should return PS document by the to_ps method" do if ps_available? - @barcode.to_ps.should match(/\A%!PS-Adobe-[\d.]/) + @barcode.to_ps.must_match(/\A%!PS-Adobe-[\d.]/) end end it "should return EPS document by the to_eps method" do if eps_available? - @barcode.to_eps.should match(/\A%!PS-Adobe-[\d.]+ EPSF-[\d.]+/) + @barcode.to_eps.must_match(/\A%!PS-Adobe-[\d.]+ EPSF-[\d.]+/) end end it "should return PDF document by the to_pdf method" do if pdf_available? - @barcode.to_pdf.should match(/\A%PDF-[\d.]+/) + @barcode.to_pdf.must_match(/\A%PDF-[\d.]+/) end end it "should return SVG document by the to_svg method" do if svg_available? - @barcode.to_svg.should match(/<\/svg>\s*\Z/m) + @barcode.to_svg.must_match(/<\/svg>\s*\Z/m) end end it "should have x, y, width, height, full_width, full_height, xdim and margin attributes" do - @outputter.should respond_to(:x) - @outputter.should respond_to(:y) - @outputter.should respond_to(:width) - @outputter.should respond_to(:height) - @outputter.should respond_to(:full_width) - @outputter.should respond_to(:full_height) - @outputter.should respond_to(:xdim) - @outputter.should respond_to(:margin) + @outputter.must_respond_to(:x) + @outputter.must_respond_to(:y) + @outputter.must_respond_to(:width) + @outputter.must_respond_to(:height) + @outputter.must_respond_to(:full_width) + @outputter.must_respond_to(:full_height) + @outputter.must_respond_to(:xdim) + @outputter.must_respond_to(:margin) end it "should not change attributes when given an options hash to render" do %w(x y height xdim).each do |m| @outputter.send("#{m}=", 10) - @outputter.send(m).should == 10 + @outputter.send(m).must_equal 10 end @outputter.render_to_cairo_context(@context, :x => 20, :y => 20, :height => 20, :xdim => 20) - %w(x y height xdim).each{|m| @outputter.send(m).should == 10 } + %w(x y height xdim).each{|m| @outputter.send(m).must_equal 10 } end + end diff --git a/test/outputter/pdfwriter_outputter_test.rb b/test/outputter/pdfwriter_outputter_test.rb new file mode 100644 index 0000000..7e0737e --- /dev/null +++ b/test/outputter/pdfwriter_outputter_test.rb @@ -0,0 +1,33 @@ +require 'test_helper' +require 'pdf/writer' + +class PDFWriterOutputterTest < Barby::TestCase + + before do + load_outputter('pdfwriter') + @barcode = Barcode.new + def @barcode.encoding; '101100111000'; end + @outputter = PDFWriterOutputter.new(@barcode) + @pdf = PDF::Writer.new + end + + it "should have registered annotate_pdf" do + Barcode.outputters.must_include(:annotate_pdf) + end + + it "should have defined the annotate_pdf method" do + @outputter.must_respond_to(:annotate_pdf) + end + + it "should return the pdf object it was given in annotate_pdf" do + @barcode.annotate_pdf(@pdf).object_id.must_equal @pdf.object_id + end + + it "should have x, y, height and xdim attributes" do + @outputter.must_respond_to(:x) + @outputter.must_respond_to(:y) + @outputter.must_respond_to(:height) + @outputter.must_respond_to(:xdim) + end + +end diff --git a/test/outputter/png_outputter_test.rb b/test/outputter/png_outputter_test.rb new file mode 100644 index 0000000..d4cc918 --- /dev/null +++ b/test/outputter/png_outputter_test.rb @@ -0,0 +1,49 @@ +require 'test_helper' + +class PngTestBarcode < Barby::Barcode + def initialize(data) + @data = data + end + def encoding + @data + end +end + +class PngOutputterTest < Barby::TestCase + + before do + load_outputter('png') + @barcode = PngTestBarcode.new('10110011100011110000') + @outputter = PngOutputter.new(@barcode) + end + + it "should register to_png and to_image" do + Barcode.outputters.must_include(:to_png) + Barcode.outputters.must_include(:to_image) + end + + it "should return a ChunkyPNG::Datastream on to_datastream" do + @barcode.to_datastream.must_be_instance_of(ChunkyPNG::Datastream) + end + + it "should return a string on to_png" do + @barcode.to_png.must_be_instance_of(String) + end + + it "should return a ChunkyPNG::Image on to_canvas" do + @barcode.to_image.must_be_instance_of(ChunkyPNG::Image) + end + + it "should have a width equal to Xdim * barcode_string.length" do + @outputter.width.must_equal @outputter.barcode.encoding.length * @outputter.xdim + end + + it "should have a full_width which is the sum of width + (margin*2)" do + @outputter.full_width.must_equal @outputter.width + (@outputter.margin*2) + end + + it "should have a full_height which is the sum of height + (margin*2)" do + @outputter.full_height.must_equal @outputter.height + (@outputter.margin*2) + end + +end diff --git a/spec/prawn_outputter_spec.rb b/test/outputter/prawn_outputter_test.rb similarity index 51% rename from spec/prawn_outputter_spec.rb rename to test/outputter/prawn_outputter_test.rb index 3d4fd80..785200e 100644 --- a/spec/prawn_outputter_spec.rb +++ b/test/outputter/prawn_outputter_test.rb @@ -1,80 +1,79 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/outputter/prawn_outputter' -include Barby +require 'test_helper' -describe PrawnOutputter do +class PrawnOutputterTest < Barby::TestCase - before :each do + before do + load_outputter('prawn') @barcode = Barcode.new def @barcode.encoding; '10110011100011110000'; end @outputter = PrawnOutputter.new(@barcode) end it "should register to_pdf and annotate_pdf" do - Barcode.outputters.should include(:to_pdf) - Barcode.outputters.should include(:annotate_pdf) + Barcode.outputters.must_include(:to_pdf) + Barcode.outputters.must_include(:annotate_pdf) end it "should have a to_pdf method" do - @outputter.should respond_to(:to_pdf) + @outputter.must_respond_to(:to_pdf) end it "should return a PDF document in a string on to_pdf" do - @barcode.to_pdf.should be_an_instance_of(String) + @barcode.to_pdf.must_be_instance_of(String) end it "should return the same Prawn::Document on annotate_pdf" do doc = Prawn::Document.new - @barcode.annotate_pdf(doc).object_id.should == doc.object_id + @barcode.annotate_pdf(doc).object_id.must_equal doc.object_id end it "should default x and y to margin value" do @outputter.margin = 123 - @outputter.x.should == 123 - @outputter.y.should == 123 + @outputter.x.must_equal 123 + @outputter.y.must_equal 123 end it "should default ydim to xdim value" do @outputter.xdim = 321 - @outputter.ydim.should == 321 + @outputter.ydim.must_equal 321 end it "should be able to calculate width required" do - @outputter.width.should == @barcode.encoding.length + @outputter.width.must_equal @barcode.encoding.length @outputter.xdim = 2 - @outputter.width.should == @barcode.encoding.length * 2 - @outputter.full_width.should == @barcode.encoding.length * 2 + @outputter.width.must_equal @barcode.encoding.length * 2 + @outputter.full_width.must_equal @barcode.encoding.length * 2 @outputter.margin = 5 - @outputter.full_width.should == (@barcode.encoding.length * 2) + 10 + @outputter.full_width.must_equal((@barcode.encoding.length * 2) + 10) #2D barcode = Barcode2D.new def barcode.encoding; ['111', '000', '111'] end outputter = PrawnOutputter.new(barcode) - outputter.width.should == 3 + outputter.width.must_equal 3 outputter.xdim = 2 outputter.margin = 5 - outputter.width.should == 6 - outputter.full_width.should == 16 + outputter.width.must_equal 6 + outputter.full_width.must_equal 16 end it "should be able to calculate height required" do - @outputter.full_height.should == @outputter.height + @outputter.full_height.must_equal @outputter.height @outputter.margin = 5 - @outputter.full_height.should == @outputter.height + 10 + @outputter.full_height.must_equal @outputter.height + 10 #2D barcode = Barcode2D.new def barcode.encoding; ['111', '000', '111'] end outputter = PrawnOutputter.new(barcode) - outputter.height.should == 3 + outputter.height.must_equal 3 outputter.xdim = 2 #ydim defaults to xdim outputter.margin = 5 - outputter.height.should == 6 - outputter.full_height.should == 16 + outputter.height.must_equal 6 + outputter.full_height.must_equal 16 outputter.ydim = 3 #ydim overrides xdim when set - outputter.height.should == 9 - outputter.full_height.should == 19 + outputter.height.must_equal 9 + outputter.full_height.must_equal 19 end end diff --git a/test/outputter/rmagick_outputter_test.rb b/test/outputter/rmagick_outputter_test.rb new file mode 100644 index 0000000..8424af5 --- /dev/null +++ b/test/outputter/rmagick_outputter_test.rb @@ -0,0 +1,83 @@ +require 'test_helper' + +class RmagickTestBarcode < Barby::Barcode + def initialize(data) + @data = data + end + def encoding + @data + end +end + +class RmagickOutputterTest < Barby::TestCase + + before do + load_outputter('rmagick') + @barcode = RmagickTestBarcode.new('10110011100011110000') + @outputter = RmagickOutputter.new(@barcode) + end + + it "should register to_png, to_gif, to_jpg, to_image" do + Barcode.outputters.must_include(:to_png) + Barcode.outputters.must_include(:to_gif) + Barcode.outputters.must_include(:to_jpg) + Barcode.outputters.must_include(:to_image) + end + + it "should have defined to_png, to_gif, to_jpg, to_image" do + @outputter.must_respond_to(:to_png) + @outputter.must_respond_to(:to_gif) + @outputter.must_respond_to(:to_jpg) + @outputter.must_respond_to(:to_image) + end + + it "should return a string on to_png and to_gif" do + @outputter.to_png.must_be_instance_of(String) + @outputter.to_gif.must_be_instance_of(String) + end + + it "should return a Magick::Image instance on to_image" do + @outputter.to_image.must_be_instance_of(Magick::Image) + end + + it "should have a width equal to the length of the barcode encoding string * x dimension" do + @outputter.xdim.must_equal 1#Default + @outputter.width.must_equal @outputter.barcode.encoding.length + @outputter.xdim = 2 + @outputter.width.must_equal @outputter.barcode.encoding.length * 2 + end + + it "should have a full_width equal to the width + left and right margins" do + @outputter.xdim.must_equal 1 + @outputter.margin.must_equal 10 + @outputter.full_width.must_equal (@outputter.width + 10 + 10) + end + + it "should have a default height of 100" do + @outputter.height.must_equal 100 + @outputter.height = 200 + @outputter.height.must_equal 200 + end + + it "should have a full_height equal to the height + top and bottom margins" do + @outputter.full_height.must_equal @outputter.height + (@outputter.margin * 2) + end + + describe "#to_image" do + + before do + @barcode = RmagickTestBarcode.new('10110011100011110000') + @outputter = RmagickOutputter.new(@barcode) + @image = @outputter.to_image + end + + it "should have a width and height equal to the outputter's full_width and full_height" do + @image.columns.must_equal @outputter.full_width + @image.rows.must_equal @outputter.full_height + end + + end + +end + + diff --git a/spec/svg_outputter_spec.rb b/test/outputter/svg_outputter_test.rb similarity index 50% rename from spec/svg_outputter_spec.rb rename to test/outputter/svg_outputter_test.rb index 6a45f19..3740960 100644 --- a/spec/svg_outputter_spec.rb +++ b/test/outputter/svg_outputter_test.rb @@ -1,89 +1,89 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/outputter/svg_outputter' -include Barby +require 'test_helper' -class TestBarcode < Barcode +class SvgBarcode < Barby::Barcode attr_accessor :data, :two_d def initialize(data, two_d=false) self.data, self.two_d = data, two_d end def encoding data end def two_dimensional? two_d end def to_s data end end - -describe SvgOutputter do - - before :each do - @barcode = TestBarcode.new('10110011100011110000') +class SvgOutputterTest < Barby::TestCase + + before do + load_outputter('svg') + @barcode = SvgBarcode.new('10110011100011110000') @outputter = SvgOutputter.new(@barcode) end it 'should register to_svg, bars_to_rects, and bars_to_path' do - Barcode.outputters.should include(:to_svg, :bars_to_rects, :bars_to_path) + Barcode.outputters.must_include :to_svg + Barcode.outputters.must_include :bars_to_rects + Barcode.outputters.must_include :bars_to_path end it 'should return a string on to_svg' do - @barcode.to_svg.should be_an_instance_of(String) + @barcode.to_svg.must_be_instance_of String end it 'should return a string on bars_to_rects' do - @barcode.bars_to_rects.should be_an_instance_of(String) + @barcode.bars_to_rects.must_be_instance_of String end it 'should return a string on bars_to_path' do - @barcode.bars_to_path.should be_an_instance_of(String) + @barcode.bars_to_path.must_be_instance_of String end - + it 'should produce one rect for each bar' do - @barcode.bars_to_rects.scan(/<rect/).size.should == @outputter.send(:boolean_groups).select{|bg|bg[0]}.size + @barcode.bars_to_rects.scan(/<rect/).size.must_equal @outputter.send(:boolean_groups).select{|bg|bg[0]}.size end it 'should produce one path stroke for each bar module' do - @barcode.bars_to_path.scan(/(M\d+\s+\d+)\s*(V\d+)/).size.should == @outputter.send(:booleans).select{|bg|bg}.size + @barcode.bars_to_path.scan(/(M\d+\s+\d+)\s*(V\d+)/).size.must_equal @outputter.send(:booleans).select{|bg|bg}.size end - + it 'should return default values for attributes' do - @outputter.margin.should be_an_instance_of(Fixnum) + @outputter.margin.must_be_instance_of Fixnum end it 'should use defaults to populate higher level attributes' do - @outputter.xmargin.should == @outputter.margin + @outputter.xmargin.must_equal @outputter.margin end it 'should return nil for overridden attributes' do @outputter.xmargin = 1 - @outputter.margin.should == nil + @outputter.margin.must_equal nil end it 'should still use defaults for unspecified attributes' do @outputter.xmargin = 1 - @outputter.ymargin.should == @outputter.send(:_margin) + @outputter.ymargin.must_equal @outputter.send(:_margin) end it 'should have a width equal to Xdim * barcode_string.length' do - @outputter.width.should == @outputter.barcode.encoding.length * @outputter.xdim + @outputter.width.must_equal @outputter.barcode.encoding.length * @outputter.xdim end - + it 'should have a full_width which is by default the sum of width + (margin*2)' do - @outputter.full_width.should == @outputter.width + (@outputter.margin*2) + @outputter.full_width.must_equal @outputter.width + (@outputter.margin*2) end it 'should have a full_width which is the sum of width + xmargin + ymargin' do - @outputter.full_width.should == @outputter.width + @outputter.xmargin + @outputter.ymargin + @outputter.full_width.must_equal @outputter.width + @outputter.xmargin + @outputter.ymargin end it 'should use Barcode#to_s for title' do - @outputter.title.should == @barcode.data + @outputter.title.must_equal @barcode.data def @barcode.to_s; "the eastern star"; end - @outputter.title.should == "the eastern star" + @outputter.title.must_equal "the eastern star" end - + end diff --git a/test/outputter_test.rb b/test/outputter_test.rb new file mode 100644 index 0000000..8c36f91 --- /dev/null +++ b/test/outputter_test.rb @@ -0,0 +1,134 @@ +require 'test_helper' + +class OutputterTest < Barby::TestCase + + before do + @outputter = Class.new(Outputter) + end + + it "should be able to register an output method for barcodes" do + @outputter.register :foo + Barcode.outputters.must_include(:foo) + @outputter.register :bar, :baz + Barcode.outputters.must_include(:bar) + Barcode.outputters.must_include(:baz) + @outputter.register :quux => :my_quux + Barcode.outputters.must_include(:quux) + end + + describe "Outputter instances" do + + before do + @barcode = Barcode.new + class << @barcode; attr_accessor :encoding; end + @barcode.encoding = '101100111000' + @outputter = Outputter.new(@barcode) + end + + it "should have a method 'booleans' which converts the barcode encoding to an array of true,false values" do + @outputter.send(:booleans).length.must_equal @barcode.encoding.length + t, f = true, false + @outputter.send(:booleans).must_equal [t,f,t,t,f,f,t,t,t,f,f,f] + end + + it "should convert 2D encodings with 'booleans'" do + barcode = Barcode2D.new + def barcode.encoding; ['101100','110010']; end + outputter = Outputter.new(barcode) + outputter.send(:booleans).length.must_equal barcode.encoding.length + t, f = true, false + outputter.send(:booleans).must_equal [[t,f,t,t,f,f], [t,t,f,f,t,f]] + end + + it "should have an 'encoding' attribute" do + @outputter.send(:encoding).must_equal @barcode.encoding + end + + it "should cache encoding" do + @outputter.send(:encoding).must_equal @barcode.encoding + previous_encoding = @barcode.encoding + @barcode.encoding = '101010' + @outputter.send(:encoding).must_equal previous_encoding + @outputter.send(:encoding, true).must_equal @barcode.encoding + end + + it "should have a boolean_groups attribute which collects continuous bars and spaces" do + t, f = true, false + # 1 0 11 00 111 000 + @outputter.send(:boolean_groups).must_equal [[t,1],[f,1],[t,2],[f,2],[t,3],[f,3]] + + barcode = Barcode2D.new + def barcode.encoding; ['1100', '111000']; end + outputter = Outputter.new(barcode) + outputter.send(:boolean_groups).must_equal [[[t,2],[f,2]],[[t,3],[f,3]]] + end + + it "should have a with_options method which sets the instance's attributes temporarily while the block gets yielded" do + class << @outputter; attr_accessor :foo, :bar; end + @outputter.foo, @outputter.bar = 'humbaba', 'scorpion man' + @outputter.send(:with_options, :foo => 'horse', :bar => 'donkey') do + @outputter.foo.must_equal 'horse' + @outputter.bar.must_equal 'donkey' + end + @outputter.foo.must_equal 'humbaba' + @outputter.bar.must_equal 'scorpion man' + end + + it "should return the block value on with_options" do + @outputter.send(:with_options, {}){ 'donkey' }.must_equal 'donkey' + end + + it "should have a two_dimensional? method which returns true if the barcode is 2d" do + refute Outputter.new(Barcode1D.new).send(:two_dimensional?) + assert Outputter.new(Barcode2D.new).send(:two_dimensional?) + end + + it "should not require the barcode object to respond to two_dimensional?" do + barcode = Object.new + def barcode.encoding; "101100111000"; end + outputter = Outputter.new(barcode) + assert outputter.send(:booleans) + assert outputter.send(:boolean_groups) + end + + end + + describe "Barcode instances" do + + before do + @outputter = Class.new(Outputter) + @outputter.register :foo + @outputter.register :bar => :my_bar + @outputter.class_eval{ def foo; 'foo'; end; def my_bar; 'bar'; end } + @barcode = Barcode.new + end + + it "should respond to registered output methods" do + @barcode.foo.must_equal 'foo' + @barcode.bar.must_equal 'bar' + end + + it "should send arguments to registered method on outputter class" do + @outputter.class_eval{ def foo(*a); a; end; def my_bar(*a); a; end } + @barcode.foo(1,2,3).must_equal [1,2,3] + @barcode.bar('humbaba').must_equal ['humbaba'] + end + + it "should pass block to registered methods" do + @outputter.class_eval{ def foo(*a, &b); b.call(*a); end } + @barcode.foo(1,2,3){|*a| a }.must_equal [1,2,3] + end + + it "should be able to get an instance of a specific outputter" do + @barcode.outputter_for(:foo).must_be_instance_of(@outputter) + end + + it "should be able to get a specific outputter class" do + @barcode.outputter_class_for(:foo).must_equal @outputter + end + + end + +end + + diff --git a/spec/pdf_417_spec.rb b/test/pdf_417_test.rb similarity index 85% rename from spec/pdf_417_spec.rb rename to test/pdf_417_test.rb index cfbe1ec..86a9569 100644 --- a/spec/pdf_417_spec.rb +++ b/test/pdf_417_test.rb @@ -1,43 +1,42 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -include Barby +require 'test_helper' -if defined?(JRUBY_VERSION) -require 'barby/barcode/pdf_417' -describe Pdf417 do +class Pdf417 < Barby::TestCase + + require 'barby/barcode/pdf_417' + it "should produce a nice code" do enc = Pdf417.new('Ereshkigal').encoding - enc.should == [ + enc.must_equal [ "111111111101010100101111010110011110100111010110001110100011101101011100100001111111101000110100100", "111111111101010100101111010110000100100110100101110000101011111110101001111001111111101000110100100", "111111111101010100101101010111111000100100011100110011111010101100001111100001111111101000110100100", "111111111101010100101111101101111110110100010100011101111011010111110111111001111111101000110100100", "111111111101010100101101011110000010100110010101110010100011101101110001110001111111101000110100100", "111111111101010100101111101101110000110101101100000011110011110110111110111001111111101000110100100", "111111111101010100101101001111001111100110001101001100100010100111101110100001111111101000110100100", "111111111101010100101111110110010111100111100100101000110010101111111001111001111111101000110100100", "111111111101010100101010011101111100100101111110001110111011111101001110110001111111101000110100100", "111111111101010100101010001111011100100100111110111110111010100101100011100001111111101000110100100", "111111111101010100101101001111000010100110001101110000101011101100111001110001111111101000110100100", "111111111101010100101101000110011111100101111111011101100011111110100011100101111111101000110100100", "111111111101010100101010000101010000100100011100001100101010100100110000111001111111101000110100100", "111111111101010100101111010100100001100100010100111100101011110110001001100001111111101000110100100", "111111111101010100101111010100011110110110011111101001100010100100001001111101111111101000110100100" ] - - enc.length.should == 15 - enc[0].length.should == 99 + enc.length.must_equal 15 + enc[0].length.must_equal 99 end it "should produce a 19x135 code with default aspect_ratio" do enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3).encoding - enc.length.should == 19 - enc[0].length.should == 135 + enc.length.must_equal 19 + enc[0].length.must_equal 135 end it "should produce a 29x117 code with 0.7 aspect_ratio" do enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3, :aspect_ratio => 0.7).encoding - enc.length.should == 29 - enc[0].length.should == 117 + enc.length.must_equal 29 + enc[0].length.must_equal 117 end -end -end \ No newline at end of file + +end if defined?(JRUBY_VERSION) diff --git a/test/qr_code_test.rb b/test/qr_code_test.rb new file mode 100644 index 0000000..bb89a4a --- /dev/null +++ b/test/qr_code_test.rb @@ -0,0 +1,77 @@ +require 'test_helper' + +class QrCodeTest < Barby::TestCase + + before do + @data = 'Ereshkigal' + @code = QrCode.new(@data) + end + + it "should have the expected data" do + @code.data.must_equal @data + end + + it "should have the expected encoding" do + # Should be an array of strings, where each string represents a "line" + @code.encoding.must_equal(rqrcode(@code).modules.map do |line| + line.inject(''){|s,m| s << (m ? '1' : '0') } + end) + + end + + it "should be able to change its data and output a different encoding" do + @code.data = 'hades' + @code.data.must_equal 'hades' + @code.encoding.must_equal(rqrcode(@code).modules.map do |line| + line.inject(''){|s,m| s << (m ? '1' : '0') } + end) + end + + it "should have a 'level' accessor" do + @code.must_respond_to :level + @code.must_respond_to :level= + end + + it "should set size according to size of data" do + QrCode.new('1'*15, :level => :l).size.must_equal 1 + QrCode.new('1'*15, :level => :m).size.must_equal 2 + QrCode.new('1'*15, :level => :q).size.must_equal 2 + QrCode.new('1'*15, :level => :h).size.must_equal 3 + + QrCode.new('1'*30, :level => :l).size.must_equal 2 + QrCode.new('1'*30, :level => :m).size.must_equal 3 + QrCode.new('1'*30, :level => :q).size.must_equal 3 + QrCode.new('1'*30, :level => :h).size.must_equal 4 + + QrCode.new('1'*270, :level => :l).size.must_equal 10 + end + + it "should allow size to be set manually" do + code = QrCode.new('1'*15, :level => :l, :size => 2) + code.size.must_equal 2 + code.encoding.must_equal(rqrcode(code).modules.map do |line| + line.inject(''){|s,m| s << (m ? '1' : '0') } + end) + end + + it "should raise ArgumentError when data too large" do + assert QrCode.new('1'*2953, :level => :l) + lambda{ QrCode.new('1'*2954, :level => :l) }.must_raise ArgumentError + end + + it "should return the original data on to_s" do + @code.to_s.must_equal 'Ereshkigal' + end + + it "should include at most 20 characters on to_s" do + QrCode.new('123456789012345678901234567890').to_s.must_equal '12345678901234567890' + end + + + private + + def rqrcode(code) + RQRCode::QRCode.new(code.data, :level => code.level, :size => code.size) + end + +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..d2b36d6 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,21 @@ +require 'rubygems' +require 'bundler' +Bundler.setup +require 'barby' +require 'minitest/spec' +require 'minitest/autorun' + +module Barby + class TestCase < MiniTest::Spec + + include Barby + + private + + # So we can register outputter during an full test suite run. + def load_outputter(outputter) + @loaded_outputter ||= load "barby/outputter/#{outputter}_outputter.rb" + end + + end +end diff --git a/test/upc_supplemental_test.rb b/test/upc_supplemental_test.rb new file mode 100644 index 0000000..cb209ef --- /dev/null +++ b/test/upc_supplemental_test.rb @@ -0,0 +1,108 @@ +require 'test_helper' + +class UpcSupplementalTest < Barby::TestCase + + it 'should be valid with 2 or 5 digits' do + assert UPCSupplemental.new('12345').valid? + assert UPCSupplemental.new('12').valid? + end + + it 'should not be valid with any number of digits other than 2 or 5' do + refute UPCSupplemental.new('1234').valid? + refute UPCSupplemental.new('123').valid? + refute UPCSupplemental.new('1').valid? + refute UPCSupplemental.new('123456').valid? + refute UPCSupplemental.new('123456789012').valid? + end + + it 'should not be valid with non-digit characters' do + refute UPCSupplemental.new('abcde').valid? + refute UPCSupplemental.new('ABC').valid? + refute UPCSupplemental.new('1234e').valid? + refute UPCSupplemental.new('!2345').valid? + refute UPCSupplemental.new('ab').valid? + refute UPCSupplemental.new('1b').valid? + refute UPCSupplemental.new('a1').valid? + end + + describe 'checksum for 5 digits' do + + it 'should have the expected odd_digits' do + UPCSupplemental.new('51234').odd_digits.must_equal [4,2,5] + UPCSupplemental.new('54321').odd_digits.must_equal [1,3,5] + UPCSupplemental.new('99990').odd_digits.must_equal [0,9,9] + end + + it 'should have the expected even_digits' do + UPCSupplemental.new('51234').even_digits.must_equal [3,1] + UPCSupplemental.new('54321').even_digits.must_equal [2,4] + UPCSupplemental.new('99990').even_digits.must_equal [9,9] + end + + it 'should have the expected odd and even sums' do + UPCSupplemental.new('51234').odd_sum.must_equal 33 + UPCSupplemental.new('54321').odd_sum.must_equal 27 + UPCSupplemental.new('99990').odd_sum.must_equal 54 + + UPCSupplemental.new('51234').even_sum.must_equal 36 + UPCSupplemental.new('54321').even_sum.must_equal 54 + UPCSupplemental.new('99990').even_sum.must_equal 162 + end + + it 'should have the expected checksum' do + UPCSupplemental.new('51234').checksum.must_equal 9 + UPCSupplemental.new('54321').checksum.must_equal 1 + UPCSupplemental.new('99990').checksum.must_equal 6 + end + + end + + describe 'checksum for 2 digits' do + + it 'should have the expected checksum' do + UPCSupplemental.new('51').checksum.must_equal 3 + UPCSupplemental.new('21').checksum.must_equal 1 + UPCSupplemental.new('99').checksum.must_equal 3 + end + + end + + describe 'encoding' do + + before do + @data = '51234' + @code = UPCSupplemental.new(@data) + end + + it 'should have the expected encoding' do + # START 5 1 2 3 4 + UPCSupplemental.new('51234').encoding.must_equal '1011 0110001 01 0011001 01 0011011 01 0111101 01 0011101'.tr(' ', '') + # 9 9 9 9 0 + UPCSupplemental.new('99990').encoding.must_equal '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') + # START 5 1 + UPCSupplemental.new('51').encoding.must_equal '1011 0111001 01 0110011'.tr(' ', '') + # 2 2 + UPCSupplemental.new('22').encoding.must_equal '1011 0011011 01 0010011'.tr(' ', '') + end + + it 'should be able to change its data' do + prev_encoding = @code.encoding + @code.data = '99990' + @code.encoding.wont_equal prev_encoding + # 9 9 9 9 0 + @code.encoding.must_equal '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') + prev_encoding = @code.encoding + @code.data = '22' + @code.encoding.wont_equal prev_encoding + # 2 2 + @code.encoding.must_equal '1011 0011011 01 0010011'.tr(' ', '') + end + + end + +end + + + + +
toretore/barby
fc6b9107ca5b0c00b03de8e7423e5ba19829cc48
Remove vendored rqrcode and add a Gemfile for development. Require for Jruby spec does not keep entire suite from running.
diff --git a/.gitignore b/.gitignore index 1377554..90ea9af 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ *.swp +Gemfile.lock \ No newline at end of file diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..d8988dc --- /dev/null +++ b/Gemfile @@ -0,0 +1,20 @@ + +source :rubygems + +gemspec + +group :development do + gem 'rake', '0.8.7' +end + +group :test do + gem 'rspec', '2.5.0' +end + +group :outputters do + gem 'cairo', '1.10.0' + gem 'semacode', '0.7.4' + gem 'pdf-writer', '1.1.8' + gem 'prawn', '0.11.1' + gem 'rmagick', '2.13.1' +end diff --git a/barby.gemspec b/barby.gemspec index 67c96bd..bbaa635 100644 --- a/barby.gemspec +++ b/barby.gemspec @@ -1,22 +1,24 @@ $:.push File.expand_path("../lib", __FILE__) require "barby/version" Gem::Specification.new do |s| s.name = "barby" s.version = Barby::VERSION::STRING s.platform = Gem::Platform::RUBY s.summary = "The Ruby barcode generator" s.email = "toredarell@gmail.com" s.homepage = "http://toretore.github.com/barby" s.description = "Barby creates barcodes." s.authors = ['Tore Darell'] s.rubyforge_project = "barby" s.has_rdoc = true s.extra_rdoc_files = ["README"] s.files = Dir['CHANGELOG', 'README', 'LICENSE', 'lib/**/*', 'vendor/**/*', 'bin/*'] s.executables = ['barby'] s.require_paths = ["lib"] + + s.add_dependency 'rqrcode', '~> 0.3.3' end diff --git a/spec/pdf_417_spec.rb b/spec/pdf_417_spec.rb index 9e1e4c7..cfbe1ec 100644 --- a/spec/pdf_417_spec.rb +++ b/spec/pdf_417_spec.rb @@ -1,43 +1,43 @@ require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/barcode/pdf_417' include Barby if defined?(JRUBY_VERSION) +require 'barby/barcode/pdf_417' describe Pdf417 do it "should produce a nice code" do enc = Pdf417.new('Ereshkigal').encoding enc.should == [ "111111111101010100101111010110011110100111010110001110100011101101011100100001111111101000110100100", "111111111101010100101111010110000100100110100101110000101011111110101001111001111111101000110100100", "111111111101010100101101010111111000100100011100110011111010101100001111100001111111101000110100100", "111111111101010100101111101101111110110100010100011101111011010111110111111001111111101000110100100", "111111111101010100101101011110000010100110010101110010100011101101110001110001111111101000110100100", "111111111101010100101111101101110000110101101100000011110011110110111110111001111111101000110100100", "111111111101010100101101001111001111100110001101001100100010100111101110100001111111101000110100100", "111111111101010100101111110110010111100111100100101000110010101111111001111001111111101000110100100", "111111111101010100101010011101111100100101111110001110111011111101001110110001111111101000110100100", "111111111101010100101010001111011100100100111110111110111010100101100011100001111111101000110100100", "111111111101010100101101001111000010100110001101110000101011101100111001110001111111101000110100100", "111111111101010100101101000110011111100101111111011101100011111110100011100101111111101000110100100", "111111111101010100101010000101010000100100011100001100101010100100110000111001111111101000110100100", "111111111101010100101111010100100001100100010100111100101011110110001001100001111111101000110100100", "111111111101010100101111010100011110110110011111101001100010100100001001111101111111101000110100100" ] enc.length.should == 15 enc[0].length.should == 99 end it "should produce a 19x135 code with default aspect_ratio" do enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3).encoding enc.length.should == 19 enc[0].length.should == 135 end it "should produce a 29x117 code with 0.7 aspect_ratio" do enc = Pdf417.new('qwertyuiopasdfghjklzxcvbnm'*3, :aspect_ratio => 0.7).encoding enc.length.should == 29 enc[0].length.should == 117 end end end \ No newline at end of file diff --git a/vendor/rqrcode/CHANGELOG b/vendor/rqrcode/CHANGELOG deleted file mode 100644 index 0ded7b9..0000000 --- a/vendor/rqrcode/CHANGELOG +++ /dev/null @@ -1,34 +0,0 @@ -*0.3.3* (Feb 1st, 2011) - -* check to see if the level is valid -* fix for 'rszf' bug by [Rob la Lau https://github.com/ohreally] - -*0.3.2* (Mar 15th, 2009) - -* Ruby 1.9 fixes by [Tore Darell http://tore.darell.no] [Chris Mowforth http://blog.99th.st] - -*0.3.1* (Nov 24th, 2008) - -* expanded RS block table to QRcode version 40 [Vladislav Gorodetskiy] - -*0.3.0* (Feb 28th, 2008) - -* added more documentation -* changed to_console to to_s (what was I thinking) -* add more tests - -*0.2.1* (Feb 24th, 2008) - -* small changes to rakefile and readme -* small change to to_console method -* make console_count method private (use modules.size instead) -* slowy updating rdocs - -*0.2.0* (Feb 23rd, 2008) - -* Split files up [DR] -* added rdoc comment ... more to do there - -*0.1.0* (Feb 22rd, 2008) - -* Initial Release [DR] diff --git a/vendor/rqrcode/COPYING b/vendor/rqrcode/COPYING deleted file mode 100644 index d763213..0000000 --- a/vendor/rqrcode/COPYING +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2008 Duncan Robertson - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/vendor/rqrcode/README b/vendor/rqrcode/README deleted file mode 100644 index 6825951..0000000 --- a/vendor/rqrcode/README +++ /dev/null @@ -1,96 +0,0 @@ -== rQRCode, Encode QRCodes - -rQRCode is a library for encoding QR Codes in Ruby. It has a simple interface with all the standard qrcode options. It was adapted from the Javascript library by Kazuhiko Arase. - -== An Overview - -Let's clear up some rQRCode stuff. - - # rQRCode is a *standalone library*. It requires no other libraries. Just Ruby! - # It is an encoding library. You can't decode QR codes with it. - # The interface is simple and assumes you just want to encode a string into a QR code - # QR code is trademarked by Denso Wave inc - -== Resources - -wikipedia:: http://en.wikipedia.org/wiki/QR_Code -Denso-Wave website:: http://www.denso-wave.com/qrcode/index-e.html -kaywa:: http://qrcode.kaywa.com - - -== Installing - -You may get the latest stable version from Rubyforge. - - $ gem install rqrcode - -You can also get the source from http://github.com/whomwah/rqrcode/tree/master - - $ git clone git://github.com/whomwah/rqrcode.git - - -=== Loading rQRCode Itself - -You have installed the gem already, yeah? - - require 'rubygems' - require 'rqrcode' - -=== Simple QRCode generation to screen - - qr = RQRCode::QRCode.new( 'my string to generate', :size => 4, :level => :h ) - puts qr.to_s - # - # Prints: - # xxxxxxx x x x x x xx xxxxxxx - # x x xxx xxxxxx xxx x x - # x xxx x xxxxx x xx x xxx x - # ... etc - -=== Simple QRCode generation to view (RubyOnRails) - -<b>Controller:</b> - @qr = RQRCode::QRCode.new( 'my string to generate', :size => 4, :level => :h ) - -<b>View: (minimal styling added)</b> - <style type="text/css"> - table { - border-width: 0; - border-style: none; - border-color: #0000ff; - border-collapse: collapse; - } - td { - border-width: 0; - border-style: none; - border-color: #0000ff; - border-collapse: collapse; - padding: 0; - margin: 0; - width: 10px; - height: 10px; - } - td.black { background-color: #000; } - td.white { background-color: #fff; } - </style> - - <table> - <% @qr.modules.each_index do |x| %> - <tr> - <% @qr.modules.each_index do |y| %> - <% if @qr.is_dark(x,y) %> - <td class="black"/> - <% else %> - <td class="white"/> - <% end %> - <% end %> - </tr> - <% end %> - </table> - -== Contact - -Author:: Duncan Robertson -Email:: duncan@whomwah.com -Home Page:: http://whomwah.com -License:: MIT Licence (http://www.opensource.org/licenses/mit-license.html) diff --git a/vendor/rqrcode/Rakefile b/vendor/rqrcode/Rakefile deleted file mode 100644 index 5473645..0000000 --- a/vendor/rqrcode/Rakefile +++ /dev/null @@ -1,63 +0,0 @@ -require 'rubygems' -require 'rake' -require 'rake/clean' -require 'rake/gempackagetask' -require 'rake/rdoctask' -require 'rake/testtask' - -NAME = "rqrcode" -VERS = "0.3.3" -CLEAN.include ['pkg', 'rdoc'] - -spec = Gem::Specification.new do |s| - s.name = NAME - s.version = VERS - s.author = "Duncan Robertson" - s.email = "duncan@whomwah.com" - s.homepage = "http://whomwah.github.com/rqrcode/" - s.platform = Gem::Platform::RUBY - s.summary = "A library to encode QR Codes" - s.rubyforge_project = NAME - s.description = <<EOF -rQRCode is a library for encoding QR Codes. The simple -interface allows you to create QR Code data structures -ready to be displayed in the way you choose. -EOF - s.files = FileList["lib/**/*", "test/*"].exclude("rdoc").to_a - s.require_path = "lib" - s.has_rdoc = true - s.extra_rdoc_files = ["README", "CHANGELOG", "COPYING"] - s.test_file = "test/runtest.rb" -end - -task :build_package => [:repackage] -Rake::GemPackageTask.new(spec) do |pkg| - #pkg.need_zip = true - #pkg.need_tar = true - pkg.gem_spec = spec -end - -desc "Default: run unit tests." -task :default => :test - -desc "Run all the tests" -Rake::TestTask.new(:test) do |t| - t.libs << "lib" - t.pattern = "test/runtest.rb" - t.verbose = true -end - -desc "Generate documentation for the library" -Rake::RDocTask.new("rdoc") { |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = "rQRCode Documentation" - rdoc.template = "~/bin/jamis.rb" - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.main = "README" - rdoc.rdoc_files.include("README", "CHANGELOG", "COPYING", 'lib/**/*.rb') -} - -desc "rdoc to rubyforge" -task :rubyforge => [:rdoc] do - sh %{/usr/bin/scp -r -p rdoc/* rubyforge:/var/www/gforge-projects/rqrcode} -end diff --git a/vendor/rqrcode/lib/rqrcode.rb b/vendor/rqrcode/lib/rqrcode.rb deleted file mode 100644 index 0907dfb..0000000 --- a/vendor/rqrcode/lib/rqrcode.rb +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env ruby - -#-- -# Copyright 2008 by Duncan Robertson (duncan@whomwah.com). -# All rights reserved. - -# Permission is granted for use, copying, modification, distribution, -# and distribution of modified versions of this work as long as the -# above copyright notice is included. -#++ - -require "rqrcode/core_ext" -require "rqrcode/qrcode" diff --git a/vendor/rqrcode/lib/rqrcode/core_ext.rb b/vendor/rqrcode/lib/rqrcode/core_ext.rb deleted file mode 100644 index df77bf9..0000000 --- a/vendor/rqrcode/lib/rqrcode/core_ext.rb +++ /dev/null @@ -1,5 +0,0 @@ -Dir[File.dirname(__FILE__) + "/core_ext/*.rb"].sort.each do |path| - filename = File.basename(path) - require "rqrcode/core_ext/#{filename}" -end - diff --git a/vendor/rqrcode/lib/rqrcode/core_ext/array.rb b/vendor/rqrcode/lib/rqrcode/core_ext/array.rb deleted file mode 100644 index 84ac796..0000000 --- a/vendor/rqrcode/lib/rqrcode/core_ext/array.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rqrcode/core_ext/array/behavior' - -class Array #:nodoc: - include CoreExtensions::Array::Behavior -end diff --git a/vendor/rqrcode/lib/rqrcode/core_ext/array/behavior.rb b/vendor/rqrcode/lib/rqrcode/core_ext/array/behavior.rb deleted file mode 100644 index d8f008a..0000000 --- a/vendor/rqrcode/lib/rqrcode/core_ext/array/behavior.rb +++ /dev/null @@ -1,9 +0,0 @@ -module CoreExtensions #:nodoc: - module Array #:nodoc: - module Behavior - def extract_options! - last.is_a?(::Hash) ? pop : {} - end - end - end -end diff --git a/vendor/rqrcode/lib/rqrcode/core_ext/integer.rb b/vendor/rqrcode/lib/rqrcode/core_ext/integer.rb deleted file mode 100644 index 1b12f1c..0000000 --- a/vendor/rqrcode/lib/rqrcode/core_ext/integer.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rqrcode/core_ext/integer/bitwise' - -class Integer #:nodoc: - include CoreExtensions::Integer::Bitwise -end diff --git a/vendor/rqrcode/lib/rqrcode/core_ext/integer/bitwise.rb b/vendor/rqrcode/lib/rqrcode/core_ext/integer/bitwise.rb deleted file mode 100644 index 249e11b..0000000 --- a/vendor/rqrcode/lib/rqrcode/core_ext/integer/bitwise.rb +++ /dev/null @@ -1,11 +0,0 @@ -module CoreExtensions #:nodoc: - module Integer #:nodoc: - module Bitwise - def rszf(count) - # zero fill right shift - (self >> count) & ((2 ** ((self.size * 8) - count))-1) - end - end - end -end - diff --git a/vendor/rqrcode/lib/rqrcode/qrcode.rb b/vendor/rqrcode/lib/rqrcode/qrcode.rb deleted file mode 100644 index 4f291b4..0000000 --- a/vendor/rqrcode/lib/rqrcode/qrcode.rb +++ /dev/null @@ -1,4 +0,0 @@ -Dir[File.dirname(__FILE__) + "/qrcode/*.rb"].sort.each do |path| - filename = File.basename(path) - require "rqrcode/qrcode/#{filename}" -end diff --git a/vendor/rqrcode/lib/rqrcode/qrcode/qr_8bit_byte.rb b/vendor/rqrcode/lib/rqrcode/qrcode/qr_8bit_byte.rb deleted file mode 100644 index 46af884..0000000 --- a/vendor/rqrcode/lib/rqrcode/qrcode/qr_8bit_byte.rb +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env ruby - -#-- -# Copyright 2004 by Duncan Robertson (duncan@whomwah.com). -# All rights reserved. - -# Permission is granted for use, copying, modification, distribution, -# and distribution of modified versions of this work as long as the -# above copyright notice is included. -#++ - -module RQRCode - - class QR8bitByte - attr_reader :mode - - def initialize( data ) - @mode = QRMODE[:mode_8bit_byte] - @data = data; - end - - - def get_length - @data.size - end - - - def write( buffer ) - ( 0...@data.size ).each do |i| - c = @data[i] - c = c.ord if c.respond_to?(:ord)#String#[] returns single-char string in 1.9, .ord gets ASCII pos - buffer.put( c, 8 ) - end - end - end - -end diff --git a/vendor/rqrcode/lib/rqrcode/qrcode/qr_bit_buffer.rb b/vendor/rqrcode/lib/rqrcode/qrcode/qr_bit_buffer.rb deleted file mode 100644 index dc5480b..0000000 --- a/vendor/rqrcode/lib/rqrcode/qrcode/qr_bit_buffer.rb +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env ruby - -#-- -# Copyright 2004 by Duncan Robertson (duncan@whomwah.com). -# All rights reserved. - -# Permission is granted for use, copying, modification, distribution, -# and distribution of modified versions of this work as long as the -# above copyright notice is included. -#++ - -module RQRCode - - class QRBitBuffer - attr_reader :buffer - - def initialize - @buffer = [] - @length = 0 - end - - - def get( index ) - buf_index = (index / 8).floor - (( (@buffer[buf_index]).rszf(7 - index % 8)) & 1) == 1 - end - - - def put( num, length ) - ( 0...length ).each do |i| - put_bit((((num).rszf(length - i - 1)) & 1) == 1) - end - end - - - def get_length_in_bits - @length - end - - - def put_bit( bit ) - buf_index = ( @length / 8 ).floor - if @buffer.size <= buf_index - @buffer << 0 - end - - if bit - @buffer[buf_index] |= ((0x80).rszf(@length % 8)) - end - - @length += 1 - end - - end - -end diff --git a/vendor/rqrcode/lib/rqrcode/qrcode/qr_code.rb b/vendor/rqrcode/lib/rqrcode/qrcode/qr_code.rb deleted file mode 100644 index 9f2b716..0000000 --- a/vendor/rqrcode/lib/rqrcode/qrcode/qr_code.rb +++ /dev/null @@ -1,423 +0,0 @@ -#!/usr/bin/env ruby - -#-- -# Copyright 2008 by Duncan Robertson (duncan@whomwah.com). -# All rights reserved. - -# Permission is granted for use, copying, modification, distribution, -# and distribution of modified versions of this work as long as the -# above copyright notice is included. -#++ - -module RQRCode #:nodoc: - - QRMODE = { - :mode_number => 1 << 0, - :mode_alpha_numk => 1 << 1, - :mode_8bit_byte => 1 << 2, - :mode_kanji => 1 << 3 - } - - QRERRORCORRECTLEVEL = { - :l => 1, - :m => 0, - :q => 3, - :h => 2 - } - - QRMASKPATTERN = { - :pattern000 => 0, - :pattern001 => 1, - :pattern010 => 2, - :pattern011 => 3, - :pattern100 => 4, - :pattern101 => 5, - :pattern110 => 6, - :pattern111 => 7 - } - - # StandardErrors - - class QRCodeArgumentError < ArgumentError; end - class QRCodeRunTimeError < RuntimeError; end - - # == Creation - # - # QRCode objects expect only one required constructor parameter - # and an optional hash of any other. Here's a few examples: - # - # qr = RQRCode::QRCode.new('hello world') - # qr = RQRCode::QRCode.new('hello world', :size => 1, :level => :m ) - # - - class QRCode - attr_reader :modules, :module_count - - PAD0 = 0xEC - PAD1 = 0x11 - - # Expects a string to be parsed in, other args are optional - # - # # string - the string you wish to encode - # # size - the size of the qrcode (default 4) - # # level - the error correction level, can be: - # * Level :l 7% of code can be restored - # * Level :m 15% of code can be restored - # * Level :q 25% of code can be restored - # * Level :h 30% of code can be restored (default :h) - # - # qr = RQRCode::QRCode.new('hello world', :size => 1, :level => :m ) - # - - def initialize( *args ) - raise QRCodeArgumentError unless args.first.kind_of?( String ) - - @data = args.shift - options = args.extract_options! - level = options[:level] || :h - - raise QRCodeArgumentError unless %w(l m q h).include?(level.to_s) - - @error_correct_level = QRERRORCORRECTLEVEL[ level.to_sym ] - @type_number = options[:size] || 4 - @module_count = @type_number * 4 + 17 - @modules = Array.new( @module_count ) - @data_list = QR8bitByte.new( @data ) - @data_cache = nil - - self.make - end - - # <tt>is_dark</tt> is called with a +col+ and +row+ parameter. This will - # return true or false based on whether that coordinate exists in the - # matrix returned. It would normally be called while iterating through - # <tt>modules</tt>. A simple example would be: - # - # instance.is_dark( 10, 10 ) => true - # - - def is_dark( row, col ) - if row < 0 || @module_count <= row || col < 0 || @module_count <= col - raise QRCodeRunTimeError, "#{row},#{col}" - end - @modules[row][col] - end - - # This is a public method that returns the QR Code you have - # generated as a string. It will not be able to be read - # in this format by a QR Code reader, but will give you an - # idea if the final outout. It takes two optional args - # +:true+ and +:false+ which are there for you to choose - # how the output looks. Here's an example of it's use: - # - # instance.to_s => - # xxxxxxx x x x x x xx xxxxxxx - # x x xxx xxxxxx xxx x x - # x xxx x xxxxx x xx x xxx x - # - # instance._to_s( :true => 'E', :false => 'Q') => - # EEEEEEEQEQQEQEQQQEQEQQEEQQEEEEEEE - # EQQQQQEQQEEEQQEEEEEEQEEEQQEQQQQQE - # EQEEEQEQQEEEEEQEQQQQQQQEEQEQEEEQE - # - - def to_s( *args ) - options = args.extract_options! - row = options[:true] || 'x' - col = options[:false] || ' ' - - res = [] - - @modules.each_index do |c| - tmp = [] - @modules.each_index do |r| - if is_dark(c,r) - tmp << row - else - tmp << col - end - end - res << tmp.join - end - res.join("\n") - end - - protected - - def make #:nodoc: - make_impl( false, get_best_mask_pattern ) - end - - private - - - def make_impl( test, mask_pattern ) #:nodoc: - - ( 0...@module_count ).each do |row| - @modules[row] = Array.new( @module_count ) - end - - setup_position_probe_pattern( 0, 0 ) - setup_position_probe_pattern( @module_count - 7, 0 ) - setup_position_probe_pattern( 0, @module_count - 7 ) - setup_position_adjust_pattern - setup_timing_pattern - setup_type_info( test, mask_pattern ) - setup_type_number( test ) if @type_number >= 7 - - if @data_cache.nil? - @data_cache = QRCode.create_data( - @type_number, @error_correct_level, @data_list - ) - end - - map_data( @data_cache, mask_pattern ) - end - - - def setup_position_probe_pattern( row, col ) #:nodoc: - ( -1..7 ).each do |r| - next if ( row + r ) <= -1 || @module_count <= ( row + r ) - ( -1..7 ).each do |c| - next if ( col + c ) <= -1 || @module_count <= ( col + c ) - if 0 <= r && r <= 6 && ( c == 0 || c == 6 ) || 0 <= c && c <= 6 && ( r == 0 || r == 6 ) || 2 <= r && r <= 4 && 2 <= c && c <= 4 - @modules[row + r][col + c] = true; - else - @modules[row + r][col + c] = false; - end - end - end - end - - - def get_best_mask_pattern #:nodoc: - min_lost_point = 0 - pattern = 0 - - ( 0...8 ).each do |i| - make_impl( true, i ) - lost_point = QRUtil.get_lost_point( self ) - - if i == 0 || min_lost_point > lost_point - min_lost_point = lost_point - pattern = i - end - end - pattern - end - - - def setup_timing_pattern #:nodoc: - ( 8...@module_count - 8 ).each do |i| - @modules[i][6] = @modules[6][i] = i % 2 == 0 - end - end - - - def setup_position_adjust_pattern #:nodoc: - pos = QRUtil.get_pattern_position(@type_number) - - ( 0...pos.size ).each do |i| - ( 0...pos.size ).each do |j| - row = pos[i] - col = pos[j] - - next unless @modules[row][col].nil? - - ( -2..2 ).each do |r| - ( -2..2 ).each do |c| - if r == -2 || r == 2 || c == -2 || c == 2 || ( r == 0 && c == 0 ) - @modules[row + r][col + c] = true - else - @modules[row + r][col + c] = false - end - end - end - end - end - end - - - def setup_type_number( test ) #:nodoc: - bits = QRUtil.get_bch_type_number( @type_number ) - - ( 0...18 ).each do |i| - mod = ( !test && ( (bits >> i) & 1) == 1 ) - @modules[ (i / 3).floor ][ i % 3 + @module_count - 8 - 3 ] = mod - @modules[ i % 3 + @module_count - 8 - 3 ][ (i / 3).floor ] = mod - end - end - - - def setup_type_info( test, mask_pattern ) #:nodoc: - data = (@error_correct_level << 3 | mask_pattern) - bits = QRUtil.get_bch_type_info( data ) - - ( 0...15 ).each do |i| - mod = (!test && ( (bits >> i) & 1) == 1) - - # vertical - if i < 6 - @modules[i][8] = mod - elsif i < 8 - @modules[ i + 1 ][8] = mod - else - @modules[ @module_count - 15 + i ][8] = mod - end - - # horizontal - if i < 8 - @modules[8][ @module_count - i - 1 ] = mod - elsif i < 9 - @modules[8][ 15 - i - 1 + 1 ] = mod - else - @modules[8][ 15 - i - 1 ] = mod - end - end - - # fixed module - @modules[ @module_count - 8 ][8] = !test - end - - - def map_data( data, mask_pattern ) #:nodoc: - inc = -1 - row = @module_count - 1 - bit_index = 7 - byte_index = 0 - - ( @module_count - 1 ).step( 1, -2 ) do |col| - col = col - 1 if col <= 6 - - while true do - ( 0...2 ).each do |c| - - if @modules[row][ col - c ].nil? - dark = false - if byte_index < data.size && !data[byte_index].nil? - dark = (( (data[byte_index]).rszf( bit_index ) & 1) == 1 ) - end - mask = QRUtil.get_mask( mask_pattern, row, col - c ) - dark = !dark if mask - @modules[row][ col - c ] = dark - bit_index -= 1 - - if bit_index == -1 - byte_index += 1 - bit_index = 7 - end - end - end - - row += inc - - if row < 0 || @module_count <= row - row -= inc - inc = -inc - break - end - end - end - end - - def QRCode.create_data( type_number, error_correct_level, data_list ) #:nodoc: - rs_blocks = QRRSBlock.get_rs_blocks( type_number, error_correct_level ) - buffer = QRBitBuffer.new - - data = data_list - buffer.put( data.mode, 4 ) - buffer.put( - data.get_length, QRUtil.get_length_in_bits( data.mode, type_number ) - ) - data.write( buffer ) - - total_data_count = 0 - ( 0...rs_blocks.size ).each do |i| - total_data_count = total_data_count + rs_blocks[i].data_count - end - - if buffer.get_length_in_bits > total_data_count * 8 - raise QRCodeRunTimeError, - "code length overflow. (#{buffer.get_length_in_bits}>#{total_data_count})" - end - - if buffer.get_length_in_bits + 4 <= total_data_count * 8 - buffer.put( 0, 4 ) - end - - while buffer.get_length_in_bits % 8 != 0 - buffer.put_bit( false ) - end - - while true - break if buffer.get_length_in_bits >= total_data_count * 8 - buffer.put( QRCode::PAD0, 8 ) - break if buffer.get_length_in_bits >= total_data_count * 8 - buffer.put( QRCode::PAD1, 8 ) - end - - QRCode.create_bytes( buffer, rs_blocks ) - end - - - def QRCode.create_bytes( buffer, rs_blocks ) #:nodoc: - offset = 0 - max_dc_count = 0 - max_ec_count = 0 - dcdata = Array.new( rs_blocks.size ) - ecdata = Array.new( rs_blocks.size ) - - ( 0...rs_blocks.size ).each do |r| - dc_count = rs_blocks[r].data_count - ec_count = rs_blocks[r].total_count - dc_count - max_dc_count = [ max_dc_count, dc_count ].max - max_ec_count = [ max_ec_count, ec_count ].max - dcdata[r] = Array.new( dc_count ) - - ( 0...dcdata[r].size ).each do |i| - dcdata[r][i] = 0xff & buffer.buffer[ i + offset ] - end - - offset = offset + dc_count - rs_poly = QRUtil.get_error_correct_polynomial( ec_count ) - raw_poly = QRPolynomial.new( dcdata[r], rs_poly.get_length - 1 ) - mod_poly = raw_poly.mod( rs_poly ) - ecdata[r] = Array.new( rs_poly.get_length - 1 ) - ( 0...ecdata[r].size ).each do |i| - mod_index = i + mod_poly.get_length - ecdata[r].size - ecdata[r][i] = mod_index >= 0 ? mod_poly.get( mod_index ) : 0 - end - end - - total_code_count = 0 - ( 0...rs_blocks.size ).each do |i| - total_code_count = total_code_count + rs_blocks[i].total_count - end - - data = Array.new( total_code_count ) - index = 0 - - ( 0...max_dc_count ).each do |i| - ( 0...rs_blocks.size ).each do |r| - if i < dcdata[r].size - index += 1 - data[index-1] = dcdata[r][i] - end - end - end - - ( 0...max_ec_count ).each do |i| - ( 0...rs_blocks.size ).each do |r| - if i < ecdata[r].size - index += 1 - data[index-1] = ecdata[r][i] - end - end - end - - data - end - - end - -end diff --git a/vendor/rqrcode/lib/rqrcode/qrcode/qr_math.rb b/vendor/rqrcode/lib/rqrcode/qrcode/qr_math.rb deleted file mode 100644 index a812387..0000000 --- a/vendor/rqrcode/lib/rqrcode/qrcode/qr_math.rb +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env ruby - -#-- -# Copyright 2004 by Duncan Robertson (duncan@whomwah.com). -# All rights reserved. - -# Permission is granted for use, copying, modification, distribution, -# and distribution of modified versions of this work as long as the -# above copyright notice is included. -#++ - -module RQRCode #:nodoc: - - class QRMath - - module_eval { - exp_table = Array.new(256) - log_table = Array.new(256) - - ( 0...8 ).each do |i| - exp_table[i] = 1 << i - end - - ( 8...256 ).each do |i| - exp_table[i] = exp_table[i - 4] \ - ^ exp_table[i - 5] \ - ^ exp_table[i - 6] \ - ^ exp_table[i - 8] - end - - ( 0...255 ).each do |i| - log_table[exp_table[i] ] = i - end - - EXP_TABLE = exp_table - LOG_TABLE = log_table - } - - class << self - - def glog(n) - raise QRCodeRunTimeError, "glog(#{n})" if ( n < 1 ) - LOG_TABLE[n] - end - - - def gexp(n) - while n < 0 - n = n + 255 - end - - while n >= 256 - n = n - 255 - end - - EXP_TABLE[n] - end - - end - - end - -end diff --git a/vendor/rqrcode/lib/rqrcode/qrcode/qr_polynomial.rb b/vendor/rqrcode/lib/rqrcode/qrcode/qr_polynomial.rb deleted file mode 100644 index d47a748..0000000 --- a/vendor/rqrcode/lib/rqrcode/qrcode/qr_polynomial.rb +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env ruby - -#-- -# Copyright 2004 by Duncan Robertson (duncan@whomwah.com). -# All rights reserved. - -# Permission is granted for use, copying, modification, distribution, -# and distribution of modified versions of this work as long as the -# above copyright notice is included. -#++ - -module RQRCode #:nodoc: - - class QRPolynomial - - def initialize( num, shift ) - raise QRCodeRunTimeError, "#{num.size}/#{shift}" if num.empty? - offset = 0 - - while offset < num.size && num[offset] == 0 - offset = offset + 1 - end - - @num = Array.new( num.size - offset + shift ) - - ( 0...num.size - offset ).each do |i| - @num[i] = num[i + offset] - end - end - - - def get( index ) - @num[index] - end - - - def get_length - @num.size - end - - - def multiply( e ) - num = Array.new( get_length + e.get_length - 1 ) - - ( 0...get_length ).each do |i| - ( 0...e.get_length ).each do |j| - tmp = num[i + j].nil? ? 0 : num[i + j] - num[i + j] = tmp ^ QRMath.gexp(QRMath.glog( get(i) ) + QRMath.glog(e.get(j))) - end - end - - return QRPolynomial.new( num, 0 ) - end - - - def mod( e ) - if get_length - e.get_length < 0 - return self - end - - ratio = QRMath.glog(get(0)) - QRMath.glog(e.get(0)) - num = Array.new(get_length) - - ( 0...get_length ).each do |i| - num[i] = get(i) - end - - ( 0...e.get_length ).each do |i| - tmp = num[i].nil? ? 0 : num[i] - num[i] = tmp ^ QRMath.gexp(QRMath.glog(e.get(i)) + ratio) - end - - return QRPolynomial.new( num, 0 ).mod(e) - end - - end - -end diff --git a/vendor/rqrcode/lib/rqrcode/qrcode/qr_rs_block.rb b/vendor/rqrcode/lib/rqrcode/qrcode/qr_rs_block.rb deleted file mode 100644 index 28cd7d8..0000000 --- a/vendor/rqrcode/lib/rqrcode/qrcode/qr_rs_block.rb +++ /dev/null @@ -1,313 +0,0 @@ -#!/usr/bin/env ruby - -#-- -# Copyright 2004 by Duncan Robertson (duncan@whomwah.com). -# All rights reserved. - -# Permission is granted for use, copying, modification, distribution, -# and distribution of modified versions of this work as long as the -# above copyright notice is included. -#++ - -module RQRCode #:nodoc: - - class QRRSBlock - attr_reader :data_count, :total_count - - def initialize( total_count, data_count ) - @total_count = total_count - @data_count = data_count - end - -RQRCode::QRRSBlock::RS_BLOCK_TABLE = [ - - # L - # M - # Q - # H - - # 1 - [1, 26, 19], - [1, 26, 16], - [1, 26, 13], - [1, 26, 9], - - # 2 - [1, 44, 34], - [1, 44, 28], - [1, 44, 22], - [1, 44, 16], - - # 3 - [1, 70, 55], - [1, 70, 44], - [2, 35, 17], - [2, 35, 13], - - # 4 - [1, 100, 80], - [2, 50, 32], - [2, 50, 24], - [4, 25, 9], - - # 5 - [1, 134, 108], - [2, 67, 43], - [2, 33, 15, 2, 34, 16], - [2, 33, 11, 2, 34, 12], - - # 6 - [2, 86, 68], - [4, 43, 27], - [4, 43, 19], - [4, 43, 15], - - # 7 - [2, 98, 78], - [4, 49, 31], - [2, 32, 14, 4, 33, 15], - [4, 39, 13, 1, 40, 14], - - # 8 - [2, 121, 97], - [2, 60, 38, 2, 61, 39], - [4, 40, 18, 2, 41, 19], - [4, 40, 14, 2, 41, 15], - - # 9 - [2, 146, 116], - [3, 58, 36, 2, 59, 37], - [4, 36, 16, 4, 37, 17], - [4, 36, 12, 4, 37, 13], - - # 10 - [2, 86, 68, 2, 87, 69], - [4, 69, 43, 1, 70, 44], - [6, 43, 19, 2, 44, 20], - [6, 43, 15, 2, 44, 16], - - # 11 - [4, 101, 81], - [1, 80, 50, 4, 81, 51], - [4, 50, 22, 4, 51, 23], - [3, 36, 12, 8, 37, 13], - - # 12 - [2, 116, 92, 2, 117, 93], - [6, 58, 36, 2, 59, 37], - [4, 46, 20, 6, 47, 21], - [7, 42, 14, 4, 43, 15], - - # 13 - [4, 133, 107], - [8, 59, 37, 1, 60, 38], - [8, 44, 20, 4, 45, 21], - [12, 33, 11, 4, 34, 12], - - # 14 - [3, 145, 115, 1, 146, 116], - [4, 64, 40, 5, 65, 41], - [11, 36, 16, 5, 37, 17], - [11, 36, 12, 5, 37, 13], - - # 15 - [5, 109, 87, 1, 110, 88], - [5, 65, 41, 5, 66, 42], - [5, 54, 24, 7, 55, 25], - [11, 36, 12], - - # 16 - [5, 122, 98, 1, 123, 99], - [7, 73, 45, 3, 74, 46], - [15, 43, 19, 2, 44, 20], - [3, 45, 15, 13, 46, 16], - - # 17 - [1, 135, 107, 5, 136, 108], - [10, 74, 46, 1, 75, 47], - [1, 50, 22, 15, 51, 23], - [2, 42, 14, 17, 43, 15], - - # 18 - [5, 150, 120, 1, 151, 121], - [9, 69, 43, 4, 70, 44], - [17, 50, 22, 1, 51, 23], - [2, 42, 14, 19, 43, 15], - - # 19 - [3, 141, 113, 4, 142, 114], - [3, 70, 44, 11, 71, 45], - [17, 47, 21, 4, 48, 22], - [9, 39, 13, 16, 40, 14], - - # 20 - [3, 135, 107, 5, 136, 108], - [3, 67, 41, 13, 68, 42], - [15, 54, 24, 5, 55, 25], - [15, 43, 15, 10, 44, 16], - - # 21 - [4, 144, 116, 4, 145, 117], - [17, 68, 42], - [17, 50, 22, 6, 51, 23], - [19, 46, 16, 6, 47, 17], - - # 22 - [2, 139, 111, 7, 140, 112], - [17, 74, 46], - [7, 54, 24, 16, 55, 25], - [34, 37, 13], - - # 23 - [4, 151, 121, 5, 152, 122], - [4, 75, 47, 14, 76, 48], - [11, 54, 24, 14, 55, 25], - [16, 45, 15, 14, 46, 16], - - # 24 - [6, 147, 117, 4, 148, 118], - [6, 73, 45, 14, 74, 46], - [11, 54, 24, 16, 55, 25], - [30, 46, 16, 2, 47, 17], - - # 25 - [8, 132, 106, 4, 133, 107], - [8, 75, 47, 13, 76, 48], - [7, 54, 24, 22, 55, 25], - [22, 45, 15, 13, 46, 16], - - # 26 - [10, 142, 114, 2, 143, 115], - [19, 74, 46, 4, 75, 47], - [28, 50, 22, 6, 51, 23], - [33, 46, 16, 4, 47, 17], - - # 27 - [8, 152, 122, 4, 153, 123], - [22, 73, 45, 3, 74, 46], - [8, 53, 23, 26, 54, 24], - [12, 45, 15, 28, 46, 16], - - # 28 - [3, 147, 117, 10, 148, 118], - [3, 73, 45, 23, 74, 46], - [4, 54, 24, 31, 55, 25], - [11, 45, 15, 31, 46, 16], - - # 29 - [7, 146, 116, 7, 147, 117], - [21, 73, 45, 7, 74, 46], - [1, 53, 23, 37, 54, 24], - [19, 45, 15, 26, 46, 16], - - # 30 - [5, 145, 115, 10, 146, 116], - [19, 75, 47, 10, 76, 48], - [15, 54, 24, 25, 55, 25], - [23, 45, 15, 25, 46, 16], - - # 31 - [13, 145, 115, 3, 146, 116], - [2, 74, 46, 29, 75, 47], - [42, 54, 24, 1, 55, 25], - [23, 45, 15, 28, 46, 16], - - # 32 - [17, 145, 115], - [10, 74, 46, 23, 75, 47], - [10, 54, 24, 35, 55, 25], - [19, 45, 15, 35, 46, 16], - - # 33 - [17, 145, 115, 1, 146, 116], - [14, 74, 46, 21, 75, 47], - [29, 54, 24, 19, 55, 25], - [11, 45, 15, 46, 46, 16], - - # 34 - [13, 145, 115, 6, 146, 116], - [14, 74, 46, 23, 75, 47], - [44, 54, 24, 7, 55, 25], - [59, 46, 16, 1, 47, 17], - - # 35 - [12, 151, 121, 7, 152, 122], - [12, 75, 47, 26, 76, 48], - [39, 54, 24, 14, 55, 25], - [22, 45, 15, 41, 46, 16], - - # 36 - [6, 151, 121, 14, 152, 122], - [6, 75, 47, 34, 76, 48], - [46, 54, 24, 10, 55, 25], - [2, 45, 15, 64, 46, 16], - - # 37 - [17, 152, 122, 4, 153, 123], - [29, 74, 46, 14, 75, 47], - [49, 54, 24, 10, 55, 25], - [24, 45, 15, 46, 46, 16], - - # 38 - [4, 152, 122, 18, 153, 123], - [13, 74, 46, 32, 75, 47], - [48, 54, 24, 14, 55, 25], - [42, 45, 15, 32, 46, 16], - - # 39 - [20, 147, 117, 4, 148, 118], - [40, 75, 47, 7, 76, 48], - [43, 54, 24, 22, 55, 25], - [10, 45, 15, 67, 46, 16], - - # 40 - [19, 148, 118, 6, 149, 119], - [18, 75, 47, 31, 76, 48], - [34, 54, 24, 34, 55, 25], - [20, 45, 15, 61, 46, 16] - - ] - - def QRRSBlock.get_rs_blocks( type_no, error_correct_level ) - rs_block = QRRSBlock.get_rs_block_table( type_no, error_correct_level ) - - if rs_block.nil? - raise QRCodeRunTimeError, - "bad rsblock @ typeno: #{type_no}/error_correct_level:#{error_correct_level}" - end - - length = rs_block.size / 3 - list = [] - - ( 0...length ).each do |i| - count = rs_block[i * 3 + 0] - total_count = rs_block[i * 3 + 1] - data_count = rs_block[i * 3 + 2] - - ( 0...count ).each do |j| - list << QRRSBlock.new( total_count, data_count ) - end - end - - list - end - - - def QRRSBlock.get_rs_block_table( type_number, error_correct_level ) - case error_correct_level - when QRERRORCORRECTLEVEL[:l] - QRRSBlock::RS_BLOCK_TABLE[(type_number - 1) * 4 + 0] - when QRERRORCORRECTLEVEL[:m] - QRRSBlock::RS_BLOCK_TABLE[(type_number - 1) * 4 + 1] - when QRERRORCORRECTLEVEL[:q] - QRRSBlock::RS_BLOCK_TABLE[(type_number - 1) * 4 + 2] - when QRERRORCORRECTLEVEL[:h] - QRRSBlock::RS_BLOCK_TABLE[(type_number - 1) * 4 + 3] - else - nil - end - end - - end - -end diff --git a/vendor/rqrcode/lib/rqrcode/qrcode/qr_util.rb b/vendor/rqrcode/lib/rqrcode/qrcode/qr_util.rb deleted file mode 100644 index 17dc61e..0000000 --- a/vendor/rqrcode/lib/rqrcode/qrcode/qr_util.rb +++ /dev/null @@ -1,254 +0,0 @@ -#!/usr/bin/env ruby - -#-- -# Copyright 2004 by Duncan Robertson (duncan@whomwah.com). -# All rights reserved. - -# Permission is granted for use, copying, modification, distribution, -# and distribution of modified versions of this work as long as the -# above copyright notice is included. -#++ - -module RQRCode #:nodoc: - - class QRUtil - - PATTERN_POSITION_TABLE = [ - - [], - [6, 18], - [6, 22], - [6, 26], - [6, 30], - [6, 34], - [6, 22, 38], - [6, 24, 42], - [6, 26, 46], - [6, 28, 50], - [6, 30, 54], - [6, 32, 58], - [6, 34, 62], - [6, 26, 46, 66], - [6, 26, 48, 70], - [6, 26, 50, 74], - [6, 30, 54, 78], - [6, 30, 56, 82], - [6, 30, 58, 86], - [6, 34, 62, 90], - [6, 28, 50, 72, 94], - [6, 26, 50, 74, 98], - [6, 30, 54, 78, 102], - [6, 28, 54, 80, 106], - [6, 32, 58, 84, 110], - [6, 30, 58, 86, 114], - [6, 34, 62, 90, 118], - [6, 26, 50, 74, 98, 122], - [6, 30, 54, 78, 102, 126], - [6, 26, 52, 78, 104, 130], - [6, 30, 56, 82, 108, 134], - [6, 34, 60, 86, 112, 138], - [6, 30, 58, 86, 114, 142], - [6, 34, 62, 90, 118, 146], - [6, 30, 54, 78, 102, 126, 150], - [6, 24, 50, 76, 102, 128, 154], - [6, 28, 54, 80, 106, 132, 158], - [6, 32, 58, 84, 110, 136, 162], - [6, 26, 54, 82, 110, 138, 166], - [6, 30, 58, 86, 114, 142, 170] - ] - - G15 = 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0 - G18 = 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0 - G15_MASK = 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1 - - - def QRUtil.get_bch_type_info( data ) - d = data << 10 - while QRUtil.get_bch_digit(d) - QRUtil.get_bch_digit(G15) >= 0 - d ^= (G15 << (QRUtil.get_bch_digit(d) - QRUtil.get_bch_digit(G15))) - end - (( data << 10 ) | d) ^ G15_MASK - end - - - def QRUtil.get_bch_type_number( data ) - d = data << 12 - while QRUtil.get_bch_digit(d) - QRUtil.get_bch_digit(G18) >= 0 - d ^= (G18 << (QRUtil.get_bch_digit(d) - QRUtil.get_bch_digit(G18))) - end - ( data << 12 ) | d - end - - - def QRUtil.get_bch_digit( data ) - digit = 0 - - while data != 0 - digit = digit + 1 - data = (data).rszf(1) - end - - digit - end - - - def QRUtil.get_pattern_position( type_number ) - PATTERN_POSITION_TABLE[ type_number - 1 ] - end - - - def QRUtil.get_mask( mask_pattern, i, j ) - case mask_pattern - when QRMASKPATTERN[:pattern000] - (i + j) % 2 == 0 - when QRMASKPATTERN[:pattern001] - i % 2 == 0 - when QRMASKPATTERN[:pattern010] - j % 3 == 0 - when QRMASKPATTERN[:pattern011] - (i + j) % 3 == 0 - when QRMASKPATTERN[:pattern100] - ((i / 2).floor + (j / 3).floor ) % 2 == 0 - when QRMASKPATTERN[:pattern101] - (i * j) % 2 + (i * j) % 3 == 0 - when QRMASKPATTERN[:pattern110] - ( (i * j) % 2 + (i * j) % 3) % 2 == 0 - when QRMASKPATTERN[:pattern111] - ( (i * j) % 3 + (i + j) % 2) % 2 == 0 - else - raise QRCodeRunTimeError, "bad mask_pattern: #{mask_pattern}" - end - end - - - def QRUtil.get_error_correct_polynomial( error_correct_length ) - a = QRPolynomial.new( [1], 0 ) - - ( 0...error_correct_length ).each do |i| - a = a.multiply( QRPolynomial.new( [1, QRMath.gexp(i)], 0 ) ) - end - - a - end - - - def QRUtil.get_length_in_bits( mode, type ) - if 1 <= type && type < 10 - - # 1 - 9 - case mode - when QRMODE[:mode_number] then 10 - when QRMODE[:mode_alpha_num] then 9 - when QRMODE[:mode_8bit_byte] then 8 - when QRMODE[:mode_kanji] then 8 - else - raise QRCodeRunTimeError, "mode: #{mode}" - end - - elsif type < 27 - - # 10 -26 - case mode - when QRMODE[:mode_number] then 12 - when QRMODE[:mode_alpha_num] then 11 - when QRMODE[:mode_8bit_byte] then 16 - when QRMODE[:mode_kanji] then 10 - else - raise QRCodeRunTimeError, "mode: #{mode}" - end - - elsif type < 41 - - # 27 - 40 - case mode - when QRMODE[:mode_number] then 14 - when QRMODE[:mode_alpha_num] then 13 - when QRMODE[:mode_8bit_byte] then 16 - when QRMODE[:mode_kanji] then 12 - else - raise QRCodeRunTimeError, "mode: #{mode}" - end - - else - raise QRCodeRunTimeError, "type: #{type}" - end - end - - - def QRUtil.get_lost_point( qr_code ) - module_count = qr_code.module_count - lost_point = 0 - - # level1 - ( 0...module_count ).each do |row| - ( 0...module_count ).each do |col| - same_count = 0 - dark = qr_code.is_dark( row, col ) - - ( -1..1 ).each do |r| - next if row + r < 0 || module_count <= row + r - - ( -1..1 ).each do |c| - next if col + c < 0 || module_count <= col + c - next if r == 0 && c == 0 - if dark == qr_code.is_dark( row + r, col + c ) - same_count += 1 - end - end - end - - if same_count > 5 - lost_point += (3 + same_count - 5) - end - end - end - - # level 2 - ( 0...( module_count - 1 ) ).each do |row| - ( 0...( module_count - 1 ) ).each do |col| - count = 0 - count = count + 1 if qr_code.is_dark( row, col ) - count = count + 1 if qr_code.is_dark( row + 1, col ) - count = count + 1 if qr_code.is_dark( row, col + 1 ) - count = count + 1 if qr_code.is_dark( row + 1, col + 1 ) - lost_point = lost_point + 3 if (count == 0 || count == 4) - end - end - - # level 3 - ( 0...module_count ).each do |row| - ( 0...( module_count - 6 ) ).each do |col| - if qr_code.is_dark( row, col ) && !qr_code.is_dark( row, col + 1 ) && qr_code.is_dark( row, col + 2 ) && qr_code.is_dark( row, col + 3 ) && qr_code.is_dark( row, col + 4 ) && !qr_code.is_dark( row, col + 5 ) && qr_code.is_dark( row, col + 6 ) - lost_point = lost_point + 40 - end - end - end - - ( 0...module_count ).each do |col| - ( 0...( module_count - 6 ) ).each do |row| - if qr_code.is_dark(row, col) && !qr_code.is_dark(row + 1, col) && qr_code.is_dark(row + 2, col) && qr_code.is_dark(row + 3, col) && qr_code.is_dark(row + 4, col) && !qr_code.is_dark(row + 5, col) && qr_code.is_dark(row + 6, col) - lost_point = lost_point + 40 - end - end - end - - # level 4 - dark_count = 0 - - ( 0...module_count ).each do |col| - ( 0...module_count ).each do |row| - if qr_code.is_dark(row, col) - dark_count = dark_count + 1 - end - end - end - - ratio = (100 * dark_count / module_count / module_count - 50).abs / 5 - lost_point = lost_point * 10 - - lost_point - end - - end - -end diff --git a/vendor/rqrcode/test/runtest.rb b/vendor/rqrcode/test/runtest.rb deleted file mode 100644 index 2d40d11..0000000 --- a/vendor/rqrcode/test/runtest.rb +++ /dev/null @@ -1,98 +0,0 @@ -require "test/unit" -require "lib/rqrcode" - -class QRCodeTest < Test::Unit::TestCase - require "test/test_data" - - def test_no_data_given - assert_raise(RQRCode::QRCodeArgumentError) { - RQRCode::QRCode.new( :size => 1, :level => :h ) - RQRCode::QRCode.new( :size => 1 ) - RQRCode::QRCode.new - } - assert_raise(RQRCode::QRCodeRunTimeError) { - qr = RQRCode::QRCode.new('duncan') - qr.is_dark(0,999999) - } - end - - def test_H_ - qr = RQRCode::QRCode.new( 'duncan', :size => 1 ) - - assert_equal qr.modules.size, 21 - assert_equal qr.modules, MATRIX_1_H - - qr = RQRCode::QRCode.new( 'duncan', :size => 1 ) - assert_equal qr.modules, MATRIX_1_H - qr = RQRCode::QRCode.new( 'duncan', :size => 1, :level => :l ) - assert_equal qr.modules, MATRIX_1_L - qr = RQRCode::QRCode.new( 'duncan', :size => 1, :level => :m ) - assert_equal qr.modules, MATRIX_1_M - qr = RQRCode::QRCode.new( 'duncan', :size => 1, :level => :q ) - assert_equal qr.modules, MATRIX_1_Q - end - - def test_3_H_ - qr = RQRCode::QRCode.new( 'duncan', :size => 3 ) - - assert_equal qr.modules.size, 29 - assert_equal qr.modules, MATRIX_3_H - end - - def test_5_H_ - qr = RQRCode::QRCode.new( 'duncan', :size => 5 ) - - assert_equal qr.modules.size, 37 - assert_equal qr.modules, MATRIX_5_H - end - - def test_10_H_ - qr = RQRCode::QRCode.new( 'duncan', :size => 10 ) - - assert_equal qr.modules.size, 57 - assert_equal qr.modules, MATRIX_10_H - end - - def test_4_H_ - qr = RQRCode::QRCode.new('www.bbc.co.uk/programmes/b0090blw', - :level => :l ) - assert_equal qr.modules, MATRIX_4_L - qr = RQRCode::QRCode.new('www.bbc.co.uk/programmes/b0090blw', - :level => :m ) - assert_equal qr.modules, MATRIX_4_M - qr = RQRCode::QRCode.new('www.bbc.co.uk/programmes/b0090blw', - :level => :q ) - assert_equal qr.modules, MATRIX_4_Q - - qr = RQRCode::QRCode.new('www.bbc.co.uk/programmes/b0090blw') - assert_equal qr.modules.size, 33 - assert_equal qr.modules, MATRIX_4_H - end - - def test_to_s - qr = RQRCode::QRCode.new( 'duncan', :size => 1 ) - assert_equal qr.to_s[0..21], "xxxxxxx xx x xxxxxxx\n" - assert_equal qr.to_s( :true => 'q', :false => 'n' )[0..21], - "qqqqqqqnqqnqnnqqqqqqq\n" - assert_equal qr.to_s( :true => '@' )[0..21], "@@@@@@@ @@ @ @@@@@@@\n" - end - - def test_rszf_error_not_thrown - assert RQRCode::QRCode.new('2 1058 657682') - assert RQRCode::QRCode.new("40952", :size => 1, :level => :h) - assert RQRCode::QRCode.new("40932", :size => 1, :level => :h) - end - - def test_levels - assert RQRCode::QRCode.new("duncan", :level => :l) - assert RQRCode::QRCode.new("duncan", :level => :m) - assert RQRCode::QRCode.new("duncan", :level => :q) - assert RQRCode::QRCode.new("duncan", :level => :h) - assert_raise(RQRCode::QRCodeArgumentError) { - %w(a b c d e f g i j k n o p r s t u v w x y z).each do |ltr| - RQRCode::QRCode.new( "duncan", :level => ltr.to_sym ) - end - } - end - -end diff --git a/vendor/rqrcode/test/test_data.rb b/vendor/rqrcode/test/test_data.rb deleted file mode 100644 index 7dbd3d9..0000000 --- a/vendor/rqrcode/test/test_data.rb +++ /dev/null @@ -1,21 +0,0 @@ -MATRIX_1_H = [[true, true, true, true, true, true, true, false, true, true, false, true, false, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, false, true, false, false, true, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, true, false, false, false, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, false, false, false, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, false, false, false, true, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, false, true, true, true, false, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, true, false, true, true, true, false, false, false, false, false, false, false, false], [false, false, false, false, false, true, true, false, false, true, false, true, false, false, true, false, true, false, true, false, true], [true, true, true, true, true, false, false, true, false, false, true, false, false, true, true, false, true, true, true, true, false], [false, true, false, false, true, true, true, false, true, false, true, true, true, true, false, false, true, true, true, true, false], [false, true, false, false, true, false, false, false, true, false, false, false, true, false, true, false, true, true, true, false, false], [false, true, true, false, false, true, true, false, true, true, false, false, false, false, false, false, false, true, false, false, true], [false, false, false, false, false, false, false, false, true, true, false, false, false, true, false, false, false, true, false, false, true], [true, true, true, true, true, true, true, false, false, true, false, false, true, false, true, true, false, false, false, true, false], [true, false, false, false, false, false, true, false, true, true, true, false, false, true, false, false, false, true, true, false, false], [true, false, true, true, true, false, true, false, false, false, false, false, false, false, true, false, true, false, false, true, false], [true, false, true, true, true, false, true, false, false, false, true, false, false, true, true, false, true, false, true, false, false], [true, false, true, true, true, false, true, false, false, true, false, false, false, true, false, false, true, false, false, true, true], [true, false, false, false, false, false, true, false, false, true, false, false, true, false, true, true, false, true, true, false, false], [true, true, true, true, true, true, true, false, false, true, false, true, false, false, false, true, false, false, false, true, false]] - -MATRIX_3_H = [[true, true, true, true, true, true, true, false, false, true, true, true, true, false, true, true, false, true, true, false, true, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, false, false, false, false, true, false, false, true, false, false, true, true, true, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, false, true, true, true, true, false, false, false, false, true, false, false, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, true, false, true, false, true, false, false, false, false, false, true, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, false, true, true, false, true, true, true, true, true, false, false, true, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, false, true, false, false, false, true, false, true, true, false, false, true, true, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, true, false, true, false, false, false, true, true, true, true, true, false, true, false, false, false, false, false, false, false, false], [false, false, true, true, false, false, true, true, true, false, true, false, false, true, false, true, false, false, false, true, true, true, true, false, true, false, false, false, false], [true, false, true, false, false, true, false, true, false, true, true, false, false, false, true, true, false, false, false, false, false, false, false, false, true, false, false, false, true], [true, false, true, true, false, true, true, false, false, true, true, true, true, true, false, false, true, false, true, false, false, true, true, false, false, true, true, true, false], [false, false, false, false, true, true, false, false, false, true, true, true, true, true, false, false, false, false, false, true, false, false, false, false, false, true, false, false, true], [false, false, true, true, true, true, true, false, false, false, false, true, true, true, false, false, true, true, false, false, false, true, false, false, false, true, false, false, false], [false, true, true, true, true, false, false, true, true, false, true, true, false, true, true, false, true, false, false, false, false, false, false, false, false, true, true, false, false], [false, true, true, true, true, false, true, false, true, false, true, true, false, false, true, true, true, true, false, false, false, true, false, true, false, false, false, true, false], [true, false, true, true, true, true, false, true, true, true, false, false, false, true, true, false, false, true, false, true, true, true, true, false, true, true, false, true, true], [false, true, true, true, false, false, true, false, true, true, false, false, false, false, false, false, false, true, false, true, true, true, true, true, false, false, false, true, true], [false, true, true, true, false, true, false, false, true, false, false, true, false, true, false, true, true, true, false, true, true, false, true, true, true, false, true, false, false], [true, false, false, true, false, true, true, false, false, false, false, true, false, false, false, false, true, true, true, true, false, false, true, false, false, false, true, false, false], [false, false, true, true, true, true, false, false, false, true, true, false, true, false, true, true, true, true, true, true, false, false, true, false, true, true, false, false, true], [false, true, false, false, true, false, true, true, false, true, false, true, false, true, false, true, false, true, false, false, true, true, true, true, true, true, false, true, true], [false, false, false, false, false, false, false, false, true, true, false, true, true, true, true, true, false, true, true, true, true, false, false, false, true, true, true, false, false], [true, true, true, true, true, true, true, false, true, false, false, true, false, false, false, false, true, true, true, false, true, false, true, false, true, false, false, false, false], [true, false, false, false, false, false, true, false, false, true, false, false, true, false, true, false, false, true, false, true, true, false, false, false, true, false, false, true, true], [true, false, true, true, true, false, true, false, false, true, false, false, true, true, false, true, false, false, true, false, true, true, true, true, true, false, true, true, false], [true, false, true, true, true, false, true, false, true, false, false, false, true, false, false, false, false, false, true, true, true, true, true, true, true, false, true, false, false], [true, false, true, true, true, false, true, false, true, false, true, true, true, false, true, true, false, true, false, true, false, false, true, true, false, false, false, false, true], [true, false, false, false, false, false, true, false, false, false, false, false, false, true, false, true, true, true, true, true, false, true, false, true, false, false, false, true, false], [true, true, true, true, true, true, true, false, false, false, true, true, true, false, false, true, false, false, true, false, true, true, false, true, false, true, true, true, false]] - -MATRIX_5_H = [[true, true, true, true, true, true, true, false, false, true, false, true, false, false, false, false, true, false, false, false, true, false, false, false, true, false, false, true, true, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, false, false, true, true, true, false, true, true, true, true, false, false, false, false, true, false, false, false, false, false, true, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, true, true, false, false, true, false, true, true, false, true, true, true, true, false, false, true, true, false, false, true, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, true, false, true, false, true, false, true, false, true, true, false, false, true, true, true, false, false, false, false, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, true, true, true, false, true, false, false, false, false, true, true, true, false, true, true, true, true, true, true, true, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, false, true, true, false, true, true, false, true, true, false, true, true, true, false, false, true, true, true, true, true, true, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, false, true, true, false, true, false, false, false, false, false, true, true, false, true, true, false, true, false, true, true, true, false, false, false, false, false, false, false, false], [false, false, false, true, true, false, true, true, false, true, false, true, false, false, true, true, false, true, false, true, false, false, true, true, true, true, true, false, false, false, false, false, false, true, true, false, false], [false, false, false, true, false, true, false, false, false, false, true, true, true, true, false, true, false, true, false, false, true, false, false, false, true, false, true, false, true, false, true, true, false, false, true, true, true], [false, false, false, true, false, false, true, false, true, true, false, false, false, false, true, false, true, true, false, false, true, false, true, false, true, false, true, true, true, true, true, false, false, false, false, true, true], [true, true, true, false, true, false, false, true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, false, false, false, false, true, false, true, false, false, true, true, false, true, false, true], [true, false, true, true, false, false, true, true, false, true, true, true, true, false, true, true, false, true, true, false, false, true, false, true, true, true, true, true, false, false, true, true, true, false, true, true, true], [true, false, false, true, true, false, false, false, true, false, false, false, true, false, true, true, true, true, false, false, false, false, true, false, true, false, false, false, false, false, false, false, false, true, false, false, true], [true, true, true, true, true, true, true, true, false, true, true, true, false, false, true, false, false, false, false, false, false, true, true, true, true, false, true, true, false, true, false, true, true, true, true, true, false], [true, true, false, false, true, true, false, true, false, true, true, false, false, true, true, true, true, false, true, false, false, false, false, true, false, true, true, false, true, false, false, true, false, true, true, false, false], [false, true, true, false, true, false, true, false, true, true, false, false, true, false, false, true, true, true, true, true, true, true, true, true, true, false, false, true, false, false, false, true, true, false, true, false, false], [true, false, false, true, true, true, false, false, false, true, true, false, false, false, false, true, true, false, false, false, false, true, true, false, false, false, false, false, false, true, true, false, false, false, true, true, false], [false, true, false, false, true, false, true, true, false, false, true, true, true, true, true, true, false, false, true, false, false, false, false, false, false, true, true, false, true, true, true, false, true, false, true, false, true], [true, true, true, false, true, true, false, false, true, true, true, true, true, true, true, true, false, true, true, false, false, false, false, false, false, true, false, true, true, true, true, true, true, false, false, false, false], [false, false, false, false, false, true, true, true, false, false, true, true, true, true, true, false, true, true, true, true, false, true, true, true, true, true, false, false, true, false, true, true, true, false, true, true, true], [true, true, true, false, true, true, false, false, true, true, true, true, false, false, false, false, false, true, true, false, true, true, false, false, true, false, false, false, true, true, true, true, true, true, false, false, true], [false, false, true, false, false, false, true, false, false, true, true, true, true, false, true, true, false, true, true, true, false, false, true, false, true, false, true, true, false, true, true, false, false, true, true, false, false], [true, false, true, false, true, false, false, true, false, true, true, false, true, false, false, true, true, false, false, true, true, false, true, true, true, false, true, true, false, false, true, true, true, true, false, true, false], [false, false, false, true, false, true, true, true, false, false, false, false, false, true, false, true, false, false, true, true, true, true, true, false, false, true, true, false, true, true, true, false, true, true, true, false, false], [true, false, true, true, false, true, false, false, true, false, false, false, false, true, false, false, true, true, true, true, false, true, true, false, true, false, false, false, true, true, true, true, true, true, true, false, true], [true, true, true, true, false, false, true, false, true, false, true, false, false, true, false, false, false, true, false, true, false, false, true, false, false, false, true, false, true, false, true, false, false, true, false, true, false], [true, false, false, false, false, false, false, false, true, true, false, false, true, true, false, false, true, true, true, false, false, false, false, false, true, true, true, true, false, true, true, false, true, true, false, false, false], [true, false, true, true, false, false, true, true, false, false, true, false, false, false, true, false, true, false, true, true, false, true, true, true, false, false, false, false, true, true, true, true, true, true, false, false, false], [false, false, false, false, false, false, false, false, true, false, true, false, false, false, true, false, false, false, true, true, false, false, false, true, true, false, false, false, true, false, false, false, true, true, true, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, false, false, true, false, false, false, false, false, false, false, true, true, false, true, true, true, true, false, true, false, true, false, true, true, true], [true, false, false, false, false, false, true, false, false, true, true, false, false, true, false, false, false, true, true, true, true, true, false, false, true, true, false, true, true, false, false, false, true, true, false, true, true], [true, false, true, true, true, false, true, false, true, false, false, true, false, true, true, false, false, true, true, true, true, false, true, false, true, true, false, false, true, true, true, true, true, true, false, false, true], [true, false, true, true, true, false, true, false, true, true, true, true, true, true, false, false, false, true, true, true, false, false, true, false, false, true, false, false, false, true, true, true, true, true, false, false, true], [true, false, true, true, true, false, true, false, false, true, true, true, true, false, true, false, false, false, false, true, false, true, false, false, true, true, false, false, true, true, false, false, true, true, true, true, true], [true, false, false, false, false, false, true, false, false, true, false, true, true, false, false, true, true, true, false, false, false, true, false, false, false, true, false, true, true, true, true, true, false, true, false, true, true], [true, true, true, true, true, true, true, false, false, true, true, false, false, false, true, false, true, false, true, true, false, false, false, false, true, true, false, true, true, false, true, true, true, true, true, false, true]] - -MATRIX_10_H = [[true, true, true, true, true, true, true, false, false, true, false, true, true, true, true, false, false, true, false, true, true, false, true, true, false, false, true, true, false, false, false, true, true, false, true, true, false, false, false, false, false, true, false, false, true, true, true, true, false, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, false, true, true, true, false, true, false, false, true, false, false, true, false, true, false, false, true, false, false, true, false, true, true, true, true, true, true, true, true, true, true, false, false, true, false, true, false, true, false, true, false, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, false, false, true, true, true, false, false, false, true, true, true, false, false, false, false, false, true, false, false, false, true, false, true, true, false, false, true, true, true, false, true, false, true, false, false, false, false, false, true, true, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, false, false, false, true, false, false, true, true, true, false, false, false, false, true, false, false, false, true, false, true, true, true, true, true, false, false, true, false, false, true, false, true, true, true, false, false, true, false, true, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, false, false, false, false, false, false, false, false, false, true, false, false, false, true, false, true, false, true, true, true, true, true, true, true, false, true, false, true, true, false, false, true, true, false, true, true, false, false, true, false, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, false, true, true, true, true, true, false, true, true, true, true, true, false, false, false, false, true, true, true, false, false, false, true, true, true, false, false, false, true, true, false, true, false, true, false, true, false, true, true, false, false, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, true, false, false, false, true, false, false, true, true, false, false, false, false, true, true, false, false, false, true, false, false, false, true, false, false, false, false, true, false, true, false, true, false, false, true, false, true, false, false, true, false, false, false, false, false, false, false, false, false], [false, false, true, true, false, false, true, true, true, false, false, true, false, false, false, true, false, true, false, true, false, true, false, true, false, false, true, true, true, true, true, true, true, false, true, true, false, true, true, false, true, false, true, false, true, true, true, false, false, true, true, false, true, false, false, false, false], [false, true, true, false, false, false, false, true, false, false, false, false, false, true, true, false, true, false, false, false, true, false, true, false, true, true, true, false, true, true, false, true, true, true, false, true, false, true, true, false, false, true, false, false, true, true, false, true, false, true, true, true, true, true, false, true, false], [true, true, false, false, false, true, true, true, false, false, false, false, true, true, false, true, true, false, false, true, true, true, false, true, true, false, false, false, true, true, false, true, true, true, false, true, true, false, true, false, false, true, false, true, false, true, false, true, true, false, true, true, true, true, true, false, true], [true, true, true, true, false, false, false, false, false, false, false, true, false, false, false, true, false, true, false, true, true, false, false, false, true, false, false, false, true, true, false, true, true, false, false, false, true, true, false, false, true, false, false, true, false, false, true, true, true, true, false, false, false, true, true, false, false], [false, true, true, true, true, false, true, true, true, false, false, false, true, false, false, true, true, true, false, false, false, false, true, true, true, false, false, false, true, true, false, true, false, true, false, false, false, true, false, false, true, true, true, true, true, false, false, true, true, true, false, false, false, false, true, false, false], [true, true, true, true, false, true, false, false, true, false, false, false, false, false, false, false, true, true, true, false, false, false, true, false, true, true, true, true, true, true, true, true, false, true, true, false, true, false, true, false, true, true, false, false, false, true, false, true, false, false, true, true, false, true, false, false, true], [false, true, true, true, true, true, true, false, false, true, false, true, true, true, false, false, false, true, true, true, false, false, false, true, true, true, true, false, false, false, true, true, true, true, false, false, true, false, false, true, false, true, false, false, true, false, false, true, false, false, false, true, true, true, false, false, true], [false, true, false, false, true, false, false, false, false, true, false, true, false, false, true, true, false, false, false, false, true, true, false, false, false, false, false, false, true, true, true, false, false, true, false, false, true, true, true, false, false, true, false, true, false, true, false, false, true, true, true, true, false, false, true, false, true], [false, false, true, true, true, true, true, false, true, true, false, false, false, false, false, false, true, true, true, false, true, true, true, false, false, true, true, true, false, true, true, true, false, false, false, false, false, false, false, false, false, true, true, false, true, true, false, true, false, false, false, true, true, false, false, true, false], [true, false, false, false, true, false, false, false, false, false, false, false, true, false, false, false, false, true, true, true, true, false, false, true, true, false, true, false, false, false, false, false, true, false, true, true, true, false, true, true, true, true, true, false, false, false, true, true, true, false, true, false, false, true, true, false, false], [true, true, true, false, false, true, true, true, true, true, false, true, false, false, false, true, true, true, true, true, false, true, true, true, false, false, true, true, false, true, false, true, true, false, false, false, false, false, false, true, false, false, true, false, false, false, false, false, false, false, false, false, true, false, false, false, false], [false, true, false, true, true, true, false, true, true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, false, true, false, false, false, true, false, true, true, true, false, true, false, false, true, false, false, true, true, true, false, true, false, true, false, false, false, true, true, true], [false, false, true, false, false, true, true, false, true, true, true, false, false, true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, true, false, true, false, true, false, true, false, true, false, false, true, false, true, false, false, true, false, false, true, false, false, false, true, false, false, false, true, false], [true, false, false, false, false, false, false, false, false, true, false, true, true, true, false, false, false, false, false, false, true, true, true, false, false, true, false, true, false, false, true, true, true, false, true, true, false, false, false, true, true, false, true, false, true, false, true, false, true, false, false, true, true, true, false, false, false], [false, true, false, true, true, false, true, true, true, true, true, false, true, false, true, true, true, false, true, false, true, false, false, true, false, false, false, false, true, false, true, true, false, true, true, true, true, true, true, true, true, false, false, true, false, false, false, false, false, true, true, true, true, true, true, false, true], [false, true, false, true, false, false, false, true, false, false, true, true, true, false, false, false, false, false, true, true, true, false, true, false, false, true, false, true, false, false, true, false, true, false, true, false, false, false, true, true, true, false, false, false, false, false, true, false, false, false, true, true, true, true, true, true, false], [true, false, false, false, true, true, true, false, false, false, false, true, false, false, true, false, false, false, false, true, false, false, true, false, true, true, false, false, false, true, true, true, true, true, false, true, true, false, true, true, false, true, true, false, false, false, false, false, true, false, true, true, false, false, true, false, false], [true, false, true, false, true, false, false, true, true, false, true, false, false, true, true, false, false, false, true, false, true, false, false, false, true, true, true, false, true, false, true, true, false, false, false, false, true, true, false, true, false, true, false, true, true, false, false, false, true, true, false, true, false, false, false, true, true], [false, false, true, true, true, true, true, true, true, false, true, true, false, true, false, false, true, true, false, true, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, false, true, true, false, false, true, true, false, true, false, true, true, false, true, true, true, true, true, false, true, true, false], [true, true, true, false, true, false, false, false, true, true, true, true, true, true, true, true, false, true, true, true, true, true, false, false, false, true, true, false, false, false, true, false, true, false, true, false, false, false, false, false, false, true, false, false, false, false, true, true, true, false, false, false, true, true, true, true, false], [false, true, false, false, true, false, true, false, true, true, false, false, false, false, true, true, false, false, true, false, false, true, true, false, false, true, true, false, true, false, true, false, false, false, false, true, false, true, true, false, false, true, true, true, false, false, true, false, true, false, true, false, true, true, true, false, true], [false, true, false, true, true, false, false, false, true, false, true, false, false, false, true, true, true, false, true, false, false, false, false, false, true, true, true, false, false, false, true, true, true, false, true, false, true, true, false, true, true, true, true, true, true, true, false, true, true, false, false, false, true, true, true, false, false], [true, true, true, false, true, true, true, true, true, true, false, true, false, false, false, false, true, false, false, false, true, false, true, false, true, true, true, true, true, true, true, true, false, true, true, false, false, true, false, true, false, false, true, true, true, true, false, false, true, true, true, true, true, false, false, false, false], [false, false, true, true, true, false, false, true, false, false, true, false, true, false, false, false, true, true, true, true, true, true, false, true, false, false, false, false, false, false, false, true, false, true, true, true, false, true, false, false, false, true, false, true, true, false, false, false, true, false, true, false, false, false, true, true, true], [false, true, false, false, true, false, true, false, false, false, true, true, false, true, false, true, true, true, true, true, true, true, false, false, false, true, true, false, false, true, false, false, true, false, true, false, false, true, true, true, false, true, false, true, false, true, true, false, true, true, false, false, true, false, false, true, false], [false, false, true, false, true, false, false, false, true, true, false, false, true, true, true, true, false, false, false, true, false, false, true, true, false, true, true, false, false, false, true, true, true, true, false, false, true, true, true, true, true, false, true, true, false, true, false, true, true, true, false, false, true, false, true, false, false], [false, true, true, false, true, true, true, false, false, false, false, false, true, false, true, false, false, true, true, false, false, false, true, true, false, true, true, false, false, false, true, false, false, false, true, false, true, false, true, true, true, false, false, false, true, true, false, true, false, false, true, false, true, false, false, true, false], [false, false, false, true, true, false, false, false, true, false, false, true, true, false, true, false, true, false, true, false, false, false, true, false, true, false, true, false, false, false, true, true, true, false, true, false, false, true, false, true, true, true, true, true, false, true, false, false, true, false, false, true, false, false, false, true, true], [true, true, true, true, true, false, true, true, true, true, false, true, true, false, false, false, false, true, false, false, true, false, true, true, true, false, false, false, true, false, true, false, true, true, false, false, true, true, false, true, false, false, false, true, true, true, true, true, true, false, false, false, false, true, true, true, true], [false, false, true, false, true, false, false, false, false, false, false, false, true, true, false, true, false, true, true, true, false, false, true, true, true, true, true, true, false, true, false, false, false, false, false, true, false, false, true, true, false, false, true, false, false, true, true, false, true, true, true, false, false, false, true, true, true], [false, false, true, true, false, true, true, false, false, true, false, false, false, true, false, true, false, false, false, true, true, true, false, false, false, false, true, false, false, false, true, false, false, false, true, true, true, false, false, false, true, false, false, false, true, false, true, true, false, true, false, true, true, false, true, true, false], [false, false, false, false, true, true, false, true, true, false, false, false, false, false, true, true, true, false, false, true, true, false, false, false, true, false, false, true, false, true, true, true, true, true, true, true, false, false, false, true, false, false, true, true, false, false, true, false, false, true, false, true, false, true, false, true, false], [true, false, false, false, false, true, true, true, false, false, false, false, true, false, true, true, false, true, false, false, false, true, true, true, true, true, true, false, true, false, false, true, false, true, true, false, false, true, true, true, true, false, false, false, true, false, true, false, false, true, false, false, false, true, false, false, true], [true, true, false, false, false, false, false, true, true, true, false, true, true, false, true, false, true, true, true, false, true, true, false, true, true, false, false, true, false, false, false, false, true, true, true, false, true, true, false, false, false, false, false, false, false, true, false, true, true, true, true, true, false, false, false, true, false], [true, true, true, false, true, false, true, true, false, true, false, false, true, false, false, true, false, false, false, false, false, true, true, true, false, false, false, true, true, true, false, false, true, true, true, false, true, true, false, false, true, true, true, false, false, true, false, true, false, true, false, true, true, true, true, true, true], [true, false, true, true, false, true, false, true, false, true, false, false, false, true, false, true, true, true, true, true, false, false, false, true, true, true, false, true, true, true, true, false, true, false, true, false, true, true, false, true, false, false, true, true, true, true, true, true, false, false, false, true, true, true, false, false, false], [true, true, true, true, false, false, true, true, true, false, false, true, false, true, false, false, false, true, true, true, true, true, false, false, false, false, true, true, false, false, false, true, true, false, true, false, false, true, true, false, true, false, true, true, false, false, false, false, true, true, false, true, true, true, false, false, true], [false, false, true, false, true, true, false, false, true, true, true, true, false, true, true, true, false, true, true, true, true, true, true, true, true, true, false, true, false, false, true, true, false, true, false, false, true, true, true, false, false, true, false, true, false, true, false, false, true, true, false, true, false, true, false, true, false], [true, false, true, false, false, true, true, true, true, false, false, true, false, false, true, true, false, true, false, false, false, false, false, false, false, false, true, false, true, true, true, true, false, false, true, true, true, false, true, false, false, true, false, false, true, false, false, true, false, false, true, true, false, true, true, false, true], [true, true, true, true, true, false, false, true, false, false, true, false, true, false, false, true, false, false, true, false, true, false, false, true, false, true, false, true, true, true, false, false, true, false, false, true, true, false, true, false, true, false, false, true, false, true, false, false, true, false, false, false, true, true, true, false, false], [false, false, false, false, false, false, true, true, false, false, true, true, false, true, true, true, true, true, false, false, true, false, false, false, true, false, true, true, true, true, true, false, true, false, true, true, true, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, false], [false, false, false, false, false, false, false, false, true, true, false, false, true, true, true, false, false, true, true, true, false, false, true, false, false, true, true, false, false, false, true, true, false, true, false, true, true, true, false, false, true, true, false, false, false, true, true, true, true, false, false, false, true, true, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, false, true, false, true, true, false, true, true, false, false, true, true, false, true, true, false, true, false, true, false, true, false, false, false, false, true, false, true, false, true, false, false, true, false, true, true, true, false, true, false, true, true, false, false, true], [true, false, false, false, false, false, true, false, false, false, false, true, true, true, false, false, true, false, false, true, true, true, true, true, true, true, true, false, false, false, true, true, true, true, true, true, false, true, false, false, false, true, false, true, false, true, false, true, true, false, false, false, true, false, true, false, true], [true, false, true, true, true, false, true, false, false, false, true, false, false, true, false, true, false, false, true, false, false, true, false, false, false, false, true, true, true, true, true, false, false, false, false, true, false, false, true, false, false, true, true, false, true, true, false, false, true, true, true, true, true, false, false, true, false], [true, false, true, true, true, false, true, false, true, false, false, true, true, false, false, true, false, true, false, false, true, false, false, false, true, false, false, true, false, true, false, false, true, false, true, false, false, true, false, true, true, true, true, false, false, false, true, true, false, false, true, true, false, false, false, true, false], [true, false, true, true, true, false, true, false, true, true, false, false, true, true, false, true, true, false, true, false, true, false, false, false, false, true, true, true, false, false, true, true, true, true, true, false, false, false, false, true, false, false, true, false, false, false, false, false, true, false, true, false, false, true, true, false, false], [true, false, false, false, false, false, true, false, false, false, false, true, true, false, false, false, true, true, true, true, false, false, false, true, false, false, false, false, true, false, true, false, false, false, true, false, true, false, true, false, false, false, true, false, true, true, true, false, false, true, false, false, false, true, false, false, true], [true, true, true, true, true, true, true, false, false, true, false, false, true, false, false, false, false, true, true, false, true, false, true, false, false, true, true, true, true, false, true, false, false, true, false, true, false, true, true, true, false, false, true, false, true, false, false, false, false, true, false, true, true, true, false, false, false]] - -MATRIX_4_H = [[true, true, true, true, true, true, true, false, false, true, true, false, false, false, false, false, false, false, false, true, false, true, false, true, false, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, false, false, false, true, true, true, true, false, false, false, false, true, true, false, false, true, false, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, false, false, false, true, false, false, true, true, false, true, false, false, true, false, true, true, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, false, true, false, true, false, true, false, false, true, false, true, true, false, true, false, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, true, true, false, true, false, false, false, false, false, true, true, true, false, true, false, true, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true, true, true, false, true, true, true, false, false, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, true, false, false, true, true, true, false, false, false, true, true, true, false, false, true, true, true, false, false, false, false, false, false, false, false], [false, false, true, true, false, false, true, true, true, true, false, false, false, false, true, true, true, false, false, false, false, true, true, true, true, true, true, false, true, false, false, false, false], [false, true, true, true, false, false, false, true, false, false, false, false, false, false, true, false, true, false, true, true, false, true, false, true, false, false, true, true, false, true, true, false, true], [true, false, true, false, false, true, true, false, false, true, true, false, false, true, true, false, false, true, false, false, true, true, true, true, true, true, true, true, true, false, true, true, true], [false, false, true, true, false, true, false, true, true, true, true, true, false, true, true, true, true, false, true, false, false, false, false, false, true, false, false, true, true, true, false, false, true], [true, false, false, false, false, false, true, false, true, false, true, false, true, true, false, false, false, false, true, false, false, true, false, false, false, true, false, false, true, true, false, false, false], [false, false, false, true, true, true, false, true, false, true, false, false, false, true, false, false, true, true, false, false, true, false, false, false, true, false, false, false, false, true, false, true, false], [false, false, false, false, true, false, true, true, false, false, true, true, true, true, true, false, false, true, false, true, false, true, true, false, true, false, true, true, true, false, false, false, false], [true, true, true, true, true, true, false, false, false, true, false, false, false, false, false, true, false, false, true, false, true, true, true, true, false, true, false, true, true, false, true, true, false], [true, false, false, true, false, false, true, false, false, true, false, true, true, false, true, false, true, false, false, true, false, true, false, false, false, true, true, false, true, false, true, false, true], [false, true, false, false, true, false, false, false, false, true, true, false, false, false, true, false, true, true, true, true, false, false, true, true, true, true, true, true, true, true, false, false, true], [false, true, false, false, false, true, true, true, false, false, false, false, false, true, true, true, false, true, true, true, true, false, false, false, true, false, false, false, false, true, false, false, false], [true, false, true, true, true, true, false, false, true, false, false, false, false, true, true, false, false, false, false, true, false, false, false, false, false, false, true, false, false, false, false, false, false], [false, false, true, false, true, false, true, true, true, false, false, true, true, false, true, false, false, false, true, true, true, true, false, false, false, false, false, true, false, true, true, true, false], [true, true, false, false, true, false, false, false, false, true, true, true, false, true, false, true, false, true, false, true, false, false, false, true, false, false, true, false, false, true, false, false, true], [false, false, true, true, false, false, true, false, true, false, false, true, false, true, false, true, false, true, true, true, false, true, true, true, false, true, false, false, true, false, true, true, true], [false, true, false, false, true, true, false, false, false, false, true, true, true, false, true, false, true, false, true, true, true, false, false, true, false, true, true, true, false, false, false, false, true], [true, false, false, true, false, true, true, false, false, false, false, true, false, false, false, false, false, true, true, true, false, false, true, false, true, true, true, true, true, false, false, true, true], [false, false, false, false, false, false, false, false, true, false, true, true, false, false, false, true, true, true, false, false, true, true, false, true, true, false, false, false, true, true, false, false, false], [true, true, true, true, true, true, true, false, true, true, true, false, false, true, true, false, true, true, true, false, true, true, false, true, true, false, true, false, true, false, true, false, false], [true, false, false, false, false, false, true, false, false, false, true, true, false, false, false, true, true, true, false, false, false, false, false, true, true, false, false, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, true, true, true, true, true, false, true, true, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, false], [true, false, true, true, true, false, true, false, true, true, false, false, true, true, true, false, true, false, true, false, false, false, true, true, false, false, false, true, false, false, false, true, true], [true, false, true, true, true, false, true, false, true, true, true, true, false, false, true, true, true, false, false, true, false, true, true, true, false, false, true, false, false, false, true, false, false], [true, false, false, false, false, false, true, false, false, false, false, false, true, false, false, true, false, false, true, false, false, true, false, true, true, false, false, true, true, true, false, false, true], [true, true, true, true, true, true, true, false, false, true, true, false, false, true, false, false, false, true, true, true, false, true, false, false, false, false, true, true, true, true, true, false, false]] - -MATRIX_1_L = [[true, true, true, true, true, true, true, false, false, true, true, true, true, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, false, true, false, true, false, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, false, true, false, false, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, true, true, true, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, false, true, true, true, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, false, false, true, false, true, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, false, true, true, true, true, false, false, false, false, false, false, false, false], [true, true, false, false, false, true, true, true, false, true, false, false, true, false, false, false, true, true, false, false, false], [false, true, true, false, true, true, false, true, true, true, true, false, true, false, true, false, true, true, true, true, false], [true, false, false, false, false, false, true, false, true, false, false, true, false, true, false, false, true, true, true, true, false], [false, false, false, false, false, true, false, true, false, false, false, false, false, false, false, false, true, true, true, false, false], [true, true, false, true, false, true, true, false, true, false, true, false, false, false, true, false, false, true, false, false, true], [false, false, false, false, false, false, false, false, true, false, true, true, true, true, true, false, false, true, false, false, true], [true, true, true, true, true, true, true, false, true, true, false, false, true, false, true, true, false, false, false, true, false], [true, false, false, false, false, false, true, false, true, true, true, true, true, true, false, false, false, true, true, false, false], [true, false, true, true, true, false, true, false, false, true, false, false, true, false, false, false, true, false, false, true, false], [true, false, true, true, true, false, true, false, false, false, true, false, true, false, false, false, true, false, true, false, false], [true, false, true, true, true, false, true, false, false, true, true, false, false, false, true, false, true, false, false, true, true], [true, false, false, false, false, false, true, false, true, false, true, false, false, false, false, true, false, true, true, false, false], [true, true, true, true, true, true, true, false, true, false, false, true, false, true, false, true, false, false, false, true, false]] - -MATRIX_1_M = [[true, true, true, true, true, true, true, false, true, false, true, false, false, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, false, true, true, false, true, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, true, false, false, true, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, false, true, false, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, true, false, false, true, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, true, false, true, false, false, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, false, true, false, true, false, false, false, false, false, false, false, false, false], [true, false, true, false, false, false, true, true, false, true, false, true, true, false, false, true, false, false, true, false, true], [false, false, true, true, true, true, false, true, true, true, false, false, false, false, false, false, false, true, false, true, true], [true, false, true, true, false, false, true, true, false, false, true, false, false, false, true, false, false, false, true, false, true], [false, false, true, true, true, true, false, true, true, true, true, false, true, false, false, false, true, true, false, false, false], [false, false, false, true, false, false, true, false, true, true, false, false, false, false, true, false, false, true, false, false, true], [false, false, false, false, false, false, false, false, true, true, false, true, false, true, true, false, false, true, true, false, true], [true, true, true, true, true, true, true, false, true, true, true, true, true, true, false, true, true, true, false, false, true], [true, false, false, false, false, false, true, false, false, false, true, true, false, true, true, false, true, true, false, false, true], [true, false, true, true, true, false, true, false, false, true, false, true, true, true, true, false, false, true, false, false, true], [true, false, true, true, true, false, true, false, false, false, false, false, false, false, false, false, true, false, false, false, false], [true, false, true, true, true, false, true, false, true, true, true, false, false, false, true, false, true, false, false, true, true], [true, false, false, false, false, false, true, false, false, false, false, false, true, false, false, true, false, true, false, false, false], [true, true, true, true, true, true, true, false, true, true, false, false, false, false, true, true, true, true, false, false, true]] - -MATRIX_1_Q = [[true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, true, false, true, false, false, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, false, false, true, false, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, true, false, true, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, false, false, false, true, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, false, true, true, true, true, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false], [false, true, false, false, false, false, true, true, true, true, false, false, true, true, false, false, false, false, false, true, true], [false, true, true, true, false, false, false, false, false, true, true, true, true, false, true, false, true, true, true, true, false], [false, false, false, false, false, true, true, true, true, false, false, true, false, true, false, false, true, true, true, true, false], [true, false, false, true, true, true, false, false, false, true, false, true, false, false, false, false, true, true, true, false, false], [false, false, false, false, false, true, true, true, false, false, false, false, false, false, true, false, false, true, false, false, true], [false, false, false, false, false, false, false, false, true, false, true, true, false, true, true, false, false, true, false, false, true], [true, true, true, true, true, true, true, false, true, true, true, false, true, false, true, true, false, false, false, true, false], [true, false, false, false, false, false, true, false, false, false, false, true, true, true, false, false, false, true, true, false, false], [true, false, true, true, true, false, true, false, false, true, false, false, true, false, false, false, true, false, false, true, false], [true, false, true, true, true, false, true, false, false, true, false, false, true, false, false, false, true, false, true, false, false], [true, false, true, true, true, false, true, false, false, true, true, false, false, false, true, false, true, false, false, true, true], [true, false, false, false, false, false, true, false, true, true, false, false, false, false, false, true, false, true, true, false, false], [true, true, true, true, true, true, true, false, false, true, false, true, false, true, false, true, false, false, false, true, false]] - -MATRIX_4_L = [[true, true, true, true, true, true, true, false, true, true, true, false, true, false, false, false, false, true, false, true, true, false, true, true, true, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, true, true, true, false, false, false, false, false, true, true, false, true, false, false, false, false, true, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, true, false, true, true, false, true, false, true, true, false, false, false, false, true, true, true, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, true, false, true, false, false, true, true, true, true, true, false, false, false, true, true, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, false, false, false, false, false, true, true, false, true, false, true, true, false, true, true, true, true, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, true, false, false, true, true, true, true, true, false, false, true, false, true, false, false, false, true, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, false, true, false, false, true, false, true, false, false, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false], [true, true, false, false, true, true, true, false, false, false, false, true, false, true, true, true, true, false, true, false, false, true, false, false, true, false, false, true, false, true, true, true, true], [true, false, true, true, true, true, false, true, false, true, true, false, true, false, false, false, false, true, false, true, true, false, true, true, false, false, false, true, false, false, true, true, false], [false, true, true, true, false, false, true, true, true, false, false, true, true, true, true, true, false, false, true, false, true, true, true, true, true, false, false, true, true, true, true, true, false], [true, true, true, true, true, true, false, true, true, false, true, true, false, true, false, true, true, false, false, false, false, true, true, false, true, false, true, true, true, false, false, false, true], [false, true, false, true, true, true, true, true, true, false, true, false, true, true, false, false, false, false, false, true, true, true, true, true, true, false, true, true, true, false, false, false, false], [false, true, false, true, false, false, false, false, true, true, false, false, false, true, true, false, true, false, true, true, false, false, false, true, true, true, false, true, false, false, true, true, false], [false, true, true, false, true, true, true, true, false, false, false, false, false, false, false, false, true, true, false, true, false, false, true, true, true, true, true, false, false, true, true, false, false], [true, true, false, false, true, false, false, false, true, true, true, false, true, false, true, false, false, true, true, true, true, true, true, false, false, true, true, false, false, false, false, true, true], [false, false, false, true, false, true, true, false, true, true, true, true, false, true, true, true, true, false, true, false, false, true, true, false, false, false, true, false, true, false, false, false, true], [false, true, true, true, true, true, false, true, false, true, true, false, true, false, false, false, false, true, false, true, true, true, false, true, false, true, false, false, false, false, true, false, false], [true, false, false, true, false, true, true, false, true, false, true, true, true, true, true, true, false, false, true, false, true, true, false, true, true, true, false, false, false, false, true, true, false], [false, true, false, true, false, true, false, false, true, false, false, true, false, true, false, true, true, false, false, false, false, true, true, true, true, true, true, true, false, true, false, true, true], [true, false, false, false, false, true, true, false, false, true, true, false, true, true, false, false, false, false, false, true, true, true, true, false, true, false, true, false, true, false, false, false, true], [true, false, false, true, true, false, false, true, true, false, false, false, false, true, true, false, true, false, true, true, false, false, true, true, false, false, false, true, false, true, false, false, false], [false, false, false, false, false, true, true, true, true, false, true, false, false, false, false, false, true, true, false, true, false, false, false, true, true, false, false, false, true, true, true, true, false], [false, false, false, true, true, true, false, true, true, false, false, false, true, false, true, false, false, true, true, true, true, true, false, true, true, false, true, false, true, false, false, true, true], [true, true, false, true, false, true, true, false, false, false, true, true, false, true, true, true, true, false, true, false, false, false, false, true, true, true, true, true, true, false, false, false, true], [false, false, false, false, false, false, false, false, true, false, true, false, true, false, false, false, false, true, false, true, true, true, false, false, true, false, false, false, true, false, true, false, false], [true, true, true, true, true, true, true, false, false, false, true, true, true, true, true, true, false, false, true, false, true, false, false, false, true, false, true, false, true, false, true, true, false], [true, false, false, false, false, false, true, false, true, true, true, true, false, true, false, true, true, false, false, false, false, false, true, false, true, false, false, false, true, false, false, true, false], [true, false, true, true, true, false, true, false, true, false, false, false, true, true, false, false, false, false, false, true, true, false, true, false, true, true, true, true, true, false, false, true, true], [true, false, true, true, true, false, true, false, false, true, false, false, false, true, true, false, true, false, true, true, false, false, false, true, true, false, true, true, true, true, false, true, false], [true, false, true, true, true, false, true, false, false, true, true, false, false, false, false, false, true, true, false, true, false, true, true, false, true, false, true, false, true, false, true, false, false], [true, false, false, false, false, false, true, false, true, false, false, false, true, false, true, false, false, true, true, true, true, true, false, true, true, false, false, true, false, true, false, false, false], [true, true, true, true, true, true, true, false, true, false, false, true, false, true, true, true, true, false, true, false, false, false, false, true, true, false, true, true, true, false, false, false, true]] - -MATRIX_4_M = [[true, true, true, true, true, true, true, false, true, true, false, true, false, true, false, true, false, false, true, false, false, false, false, true, true, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, false, true, false, false, true, true, true, false, true, false, true, true, false, false, false, false, false, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, false, true, true, false, false, false, true, true, true, true, true, false, true, true, false, false, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, true, true, false, false, false, false, false, true, true, false, true, false, true, true, false, false, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, false, false, false, true, true, false, false, true, true, false, true, false, true, true, false, false, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, true, true, false, false, true, true, true, true, false, false, false, false, true, true, true, true, true, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, true, false, true, false, false, false, false, false, false, true, true, true, true, true, false, false, true, false, false, false, false, false, false, false, false], [true, false, false, false, true, false, true, true, true, false, true, false, true, false, false, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, false, false, true], [true, true, false, true, false, false, false, true, false, true, true, false, true, false, true, true, false, true, true, false, false, true, true, true, false, true, false, false, false, true, true, true, true], [false, false, false, false, true, false, true, false, true, false, false, false, true, true, true, true, true, false, true, false, true, false, false, true, true, false, false, false, false, false, true, false, false], [true, false, true, true, true, true, false, true, true, false, true, true, true, true, false, true, true, false, false, false, false, false, true, true, true, true, false, true, true, false, false, true, true], [false, true, true, true, false, true, true, true, true, true, true, true, true, true, false, false, true, false, false, true, false, false, true, false, false, true, true, false, false, true, false, false, true], [true, false, true, true, false, true, false, true, true, false, false, false, true, true, true, false, false, false, true, true, true, false, false, false, true, false, true, true, true, true, false, false, false], [false, true, true, true, false, true, true, false, false, false, true, false, false, true, false, true, false, true, true, false, true, true, true, true, true, true, true, true, false, true, true, true, false], [true, true, false, false, true, false, false, false, false, false, true, true, true, true, false, true, true, true, true, false, false, true, true, true, false, false, true, false, false, false, true, true, true], [false, true, true, true, false, false, true, true, true, false, false, true, true, false, false, false, true, true, false, true, true, true, true, false, false, false, true, false, true, false, true, false, true], [false, false, true, true, true, false, false, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, true, false, true, false, true, false, true, true, false, false], [false, false, false, true, false, true, true, true, true, true, true, false, true, true, false, true, true, true, false, false, false, true, true, true, false, true, true, true, false, false, true, true, false], [true, true, false, true, false, false, false, true, false, true, false, false, true, true, true, true, true, true, true, true, false, true, false, false, true, false, true, true, true, true, false, false, false], [false, false, true, false, false, true, true, false, false, false, true, true, false, true, true, false, false, false, true, true, true, false, false, true, true, false, false, true, false, false, false, false, false], [true, true, true, true, false, false, false, false, true, true, true, true, true, false, true, false, true, false, false, true, false, false, true, false, false, true, true, false, false, false, true, false, false], [false, false, false, true, true, true, true, true, true, false, false, true, true, false, true, false, true, false, false, true, false, false, true, false, false, false, false, false, true, false, false, true, false], [false, false, false, false, false, true, false, false, false, true, true, true, false, false, true, false, false, true, true, true, true, true, true, false, true, true, true, true, true, true, false, true, false], [true, true, true, true, true, false, true, true, false, false, true, false, true, false, false, true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, true, true, false, false, false, true, false, true, false, true, true, false, false, true, false, false, true, false, false, false, true, true, false, true, false], [true, true, true, true, true, true, true, false, true, true, true, true, true, true, false, true, true, false, true, false, true, false, false, false, true, false, true, false, true, true, true, true, false], [true, false, false, false, false, false, true, false, false, false, true, true, true, false, false, false, true, false, false, true, true, false, true, true, true, false, false, false, true, false, false, false, true], [true, false, true, true, true, false, true, false, true, false, false, true, true, true, true, false, true, false, false, true, false, false, true, false, true, true, true, true, true, false, false, true, true], [true, false, true, true, true, false, true, false, false, false, true, true, true, true, true, false, false, true, true, true, true, true, false, true, false, false, true, false, true, true, false, true, false], [true, false, true, true, true, false, true, false, false, true, false, true, true, false, false, true, false, false, true, false, true, false, false, false, true, false, true, false, true, true, true, false, false], [true, false, false, false, false, false, true, false, false, true, true, false, false, false, false, true, true, true, true, false, false, true, false, false, false, false, false, true, false, false, true, false, false], [true, true, true, true, true, true, true, false, true, true, true, true, false, true, true, false, false, true, false, true, true, true, true, false, true, false, true, false, false, false, true, false, true]] - -MATRIX_4_Q = [[true, true, true, true, true, true, true, false, false, true, true, true, false, true, true, true, false, true, true, false, false, true, true, false, true, false, true, true, true, true, true, true, true], [true, false, false, false, false, false, true, false, true, false, false, true, false, false, false, true, true, false, true, true, false, false, false, false, false, false, true, false, false, false, false, false, true], [true, false, true, true, true, false, true, false, false, false, true, true, true, false, true, false, false, false, false, true, true, true, false, true, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, false, false, false, true, true, true, false, true, false, true, true, true, false, true, true, true, false, true, false, true, true, true, false, true], [true, false, true, true, true, false, true, false, true, false, true, true, false, false, true, true, false, false, false, false, false, false, true, true, false, false, true, false, true, true, true, false, true], [true, false, false, false, false, false, true, false, false, true, true, false, true, true, false, true, false, true, false, true, false, true, false, false, true, false, true, false, false, false, false, false, true], [true, true, true, true, true, true, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, false, true, true, true, true, true, true, true], [false, false, false, false, false, false, false, false, true, true, false, true, true, true, true, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false], [false, true, false, true, true, true, true, false, true, false, false, false, true, true, false, false, true, true, false, false, false, false, false, true, true, true, true, false, true, true, false, true, false], [false, false, false, true, true, true, false, false, true, true, false, false, true, false, false, true, false, true, true, true, false, true, false, true, false, false, false, false, true, true, true, false, false], [true, false, false, false, true, false, true, false, true, false, true, false, true, true, true, false, true, false, false, false, false, false, true, true, false, false, true, false, true, false, false, true, true], [false, false, false, true, true, false, false, false, false, true, false, false, true, false, true, false, false, false, true, false, false, true, true, true, false, false, true, false, true, false, true, true, true], [true, true, true, false, false, true, true, true, false, true, true, false, true, false, false, true, true, true, false, true, false, true, false, true, false, false, true, true, false, false, false, false, false], [true, false, false, false, true, false, false, false, true, false, false, true, true, false, false, true, false, false, true, true, true, false, false, false, true, true, false, true, false, false, true, false, false], [true, false, true, false, true, true, true, true, false, false, false, false, true, false, true, false, true, true, true, true, true, true, true, false, false, false, true, true, true, false, false, false, false], [true, false, true, true, false, false, false, false, false, true, true, true, true, false, false, false, true, false, false, false, true, false, true, false, true, false, false, false, true, false, true, true, false], [false, false, true, false, false, false, true, false, true, false, true, false, false, true, true, true, false, true, true, false, true, false, true, true, false, true, true, true, true, false, false, true, true], [true, true, false, false, true, false, false, true, false, true, true, false, false, true, false, true, false, true, false, true, true, false, false, false, false, false, true, true, true, false, true, false, true], [true, false, true, true, true, true, true, true, true, false, false, false, true, true, true, false, true, false, false, true, true, true, true, true, true, false, false, true, false, false, false, true, true], [true, false, false, false, true, true, false, false, true, true, false, true, false, false, false, true, true, true, true, false, true, false, true, true, false, true, true, false, false, false, true, false, false], [true, false, true, true, false, true, true, false, true, false, true, true, false, false, false, true, true, true, false, true, false, true, true, true, true, false, false, false, false, false, false, true, false], [true, false, true, false, true, true, false, false, false, true, false, false, false, true, false, false, true, false, true, false, false, false, false, false, false, true, false, false, true, false, true, true, false], [true, false, false, false, true, false, true, false, true, true, false, true, false, false, false, true, true, false, true, true, true, false, false, false, true, false, true, false, false, true, true, true, true], [true, false, false, false, false, false, false, false, true, false, false, false, false, true, true, false, false, true, true, true, true, false, true, false, false, true, true, false, false, true, true, true, false], [true, true, true, false, false, true, true, false, true, true, false, false, true, true, false, false, false, false, true, false, false, false, false, false, true, true, true, true, true, false, false, true, true], [false, false, false, false, false, false, false, false, true, true, false, false, true, false, true, true, true, false, false, false, false, true, false, false, true, false, false, false, true, true, false, false, false], [true, true, true, true, true, true, true, false, false, true, false, true, true, true, true, true, true, false, true, true, true, false, false, true, true, false, true, false, true, false, false, false, false], [true, false, false, false, false, false, true, false, true, true, false, true, true, true, false, false, true, false, false, true, false, true, true, false, true, false, false, false, true, true, true, true, true], [true, false, true, true, true, false, true, false, true, false, true, true, false, false, false, false, true, false, true, false, false, true, true, true, true, true, true, true, true, true, false, true, true], [true, false, true, true, true, false, true, false, true, true, false, false, true, true, true, false, true, false, true, false, false, true, true, false, false, true, false, false, false, true, true, false, true], [true, false, true, true, true, false, true, false, false, true, true, false, true, true, false, false, true, true, true, true, false, false, false, false, false, true, false, false, true, true, true, true, true], [true, false, false, false, false, false, true, false, true, true, false, false, true, false, false, true, false, true, false, true, true, false, true, false, true, false, true, false, true, false, true, true, true], [true, true, true, true, true, true, true, false, false, true, true, false, true, true, true, false, true, false, true, true, false, false, false, false, true, false, true, true, true, true, false, false, false]]
toretore/barby
34fd970ab719a0f6184f654ce4f6462ff169480a
Add documentation for Code39#initialize.
diff --git a/lib/barby/barcode/code_39.rb b/lib/barby/barcode/code_39.rb index 9006ece..5758533 100644 --- a/lib/barby/barcode/code_39.rb +++ b/lib/barby/barcode/code_39.rb @@ -1,233 +1,234 @@ require 'barby/barcode' module Barby class Code39 < Barcode1D WIDE = W = true NARROW = N = false ENCODINGS = { ' ' => [N,W,W,N,N,N,W,N,N], '$' => [N,W,N,W,N,W,N,N,N], '%' => [N,N,N,W,N,W,N,W,N], '+' => [N,W,N,N,N,W,N,W,N], '-' => [N,W,N,N,N,N,W,N,W], '.' => [W,W,N,N,N,N,W,N,N], '/' => [N,W,N,W,N,N,N,W,N], '0' => [N,N,N,W,W,N,W,N,N], '1' => [W,N,N,W,N,N,N,N,W], '2' => [N,N,W,W,N,N,N,N,W], '3' => [W,N,W,W,N,N,N,N,N], '4' => [N,N,N,W,W,N,N,N,W], '5' => [W,N,N,W,W,N,N,N,N], '6' => [N,N,W,W,W,N,N,N,N], '7' => [N,N,N,W,N,N,W,N,W], '8' => [W,N,N,W,N,N,W,N,N], '9' => [N,N,W,W,N,N,W,N,N], 'A' => [W,N,N,N,N,W,N,N,W], 'B' => [N,N,W,N,N,W,N,N,W], 'C' => [W,N,W,N,N,W,N,N,N], 'D' => [N,N,N,N,W,W,N,N,W], 'E' => [W,N,N,N,W,W,N,N,N], 'F' => [N,N,W,N,W,W,N,N,N], 'G' => [N,N,N,N,N,W,W,N,W], 'H' => [W,N,N,N,N,W,W,N,N], 'I' => [N,N,W,N,N,W,W,N,N], 'J' => [N,N,N,N,W,W,W,N,N], 'K' => [W,N,N,N,N,N,N,W,W], 'L' => [N,N,W,N,N,N,N,W,W], 'M' => [W,N,W,N,N,N,N,W,N], 'N' => [N,N,N,N,W,N,N,W,W], 'O' => [W,N,N,N,W,N,N,W,N], 'P' => [N,N,W,N,W,N,N,W,N], 'Q' => [N,N,N,N,N,N,W,W,W], 'R' => [W,N,N,N,N,N,W,W,N], 'S' => [N,N,W,N,N,N,W,W,N], 'T' => [N,N,N,N,W,N,W,W,N], 'U' => [W,W,N,N,N,N,N,N,W], 'V' => [N,W,W,N,N,N,N,N,W], 'W' => [W,W,W,N,N,N,N,N,N], 'X' => [N,W,N,N,W,N,N,N,W], 'Y' => [W,W,N,N,W,N,N,N,N], 'Z' => [N,W,W,N,W,N,N,N,N] } #In extended mode, each character is replaced with two characters from the "normal" encoding EXTENDED_ENCODINGS = { "\000" => '%U', " " => " ", "@" => "%V", "`" => "%W", "\001" => '$A', "!" => "/A", "A" => "A", "a" => "+A", "\002" => '$B', '"' => "/B", "B" => "B", "b" => "+B", "\003" => '$C', "#" => "/C", "C" => "C", "c" => "+C", "\004" => '$D', "$" => "/D", "D" => "D", "d" => "+D", "\005" => '$E', "%" => "/E", "E" => "E", "e" => "+E", "\006" => '$F', "&" => "/F", "F" => "F", "f" => "+F", "\007" => '$G', "'" => "/G", "G" => "G", "g" => "+G", "\010" => '$H', "(" => "/H", "H" => "H", "h" => "+H", "\011" => '$I', ")" => "/I", "I" => "I", "i" => "+I", "\012" => '$J', "*" => "/J", "J" => "J", "j" => "+J", "\013" => '$K', "+" => "/K", "K" => "K", "k" => "+K", "\014" => '$L', "," => "/L", "L" => "L", "l" => "+L", "\015" => '$M', "-" => "-", "M" => "M", "m" => "+M", "\016" => '$N', "." => ".", "N" => "N", "n" => "+N", "\017" => '$O', "/" => "/O", "O" => "O", "o" => "+O", "\020" => '$P', "0" => "0", "P" => "P", "p" => "+P", "\021" => '$Q', "1" => "1", "Q" => "Q", "q" => "+Q", "\022" => '$R', "2" => "2", "R" => "R", "r" => "+R", "\023" => '$S', "3" => "3", "S" => "S", "s" => "+S", "\024" => '$T', "4" => "4", "T" => "T", "t" => "+T", "\025" => '$U', "5" => "5", "U" => "U", "u" => "+U", "\026" => '$V', "6" => "6", "V" => "V", "v" => "+V", "\027" => '$W', "7" => "7", "W" => "W", "w" => "+W", "\030" => '$X', "8" => "8", "X" => "X", "x" => "+X", "\031" => '$Y', "9" => "9", "Y" => "Y", "y" => "+Y", "\032" => '$Z', ":" => "/Z", "Z" => "Z", "z" => "+Z", "\033" => '%A', ";" => "%F", "[" => "%K", "{" => "%P", "\034" => '%B', "<" => "%G", "\\" => "%L", "|" => "%Q", "\035" => '%C', "=" => "%H", "]" => "%M", "}" => "%R", "\036" => '%D', ">" => "%I", "^" => "%N", "~" => "%S", "\037" => '%E', "?" => "%J", "_" => "%O", "\177" => "%T" } CHECKSUM_VALUES = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'I' => 18, 'J' => 19, 'K' => 20, 'L' => 21, 'N' => 23, 'M' => 22, 'O' => 24, 'P' => 25, 'Q' => 26, 'R' => 27, 'S' => 28, 'T' => 29, 'U' => 30, 'V' => 31, 'W' => 32, 'X' => 33, 'Y' => 34, 'Z' => 35, '-' => 36, '.' => 37, ' ' => 38, '$' => 39, '/' => 40, '+' => 41, '%' => 42 } START_ENCODING = [N,W,N,N,W,N,W,N,N] # * STOP_ENCODING = [N,W,N,N,W,N,W,N,N] # * attr_accessor :data, :spacing, :narrow_width, :wide_width, :extended, :include_checksum - + # Do not surround "data" with the mandatory "*" as is this is done automically for you. + # So instead of passing "*123456*" as "data", just pass "123456". def initialize(data, extended=false) self.data = data self.extended = extended raise(ArgumentError, "data is not valid (extended=#{extended?})") unless valid? yield self if block_given? end #Returns the characters that were passed in, no matter it they're part of #the extended charset or if they're already encodable, "normal" characters def raw_characters data.split(//) end #Returns the encodable characters. If extended mode is enabled, each character will #first be replaced by two characters from the encodable charset def characters chars = raw_characters extended ? chars.map{|c| EXTENDED_ENCODINGS[c].split(//) }.flatten : chars end def characters_with_checksum characters + [checksum_character] end def encoded_characters characters.map{|c| encoding_for(c) } end def encoded_characters_with_checksum encoded_characters + [checksum_encoding] end #The data part of the encoding (no start+stop characters) def data_encoding encoded_characters.join(spacing_encoding) end def data_encoding_with_checksum encoded_characters_with_checksum.join(spacing_encoding) end def encoding return encoding_with_checksum if include_checksum? start_encoding+spacing_encoding+data_encoding+spacing_encoding+stop_encoding end def encoding_with_checksum start_encoding+spacing_encoding+data_encoding_with_checksum+spacing_encoding+stop_encoding end #Checksum is optional def checksum characters.inject(0) do |sum,char| sum + CHECKSUM_VALUES[char] end % 43 end def checksum_character CHECKSUM_VALUES.invert[checksum] end def checksum_encoding encoding_for(checksum_character) end #Set include_checksum to true to make +encoding+ include the checksum def include_checksum? include_checksum end #Takes an array of WIDE/NARROW values and returns the string representation for #those bars and spaces, using wide_width and narrow_width def encoding_for_bars(*bars_and_spaces) bar = false bars_and_spaces.flatten.map do |width| bar = !bar (bar ? '1' : '0') * (width == WIDE ? wide_width : narrow_width) end.join end #Returns the string representation for a single character def encoding_for(character) encoding_for_bars(ENCODINGS[character]) end #Spacing between the characters in xdims. Spacing will be inserted #between each character in the encoding def spacing @spacing ||= 1 end def spacing_encoding '0' * spacing end def narrow_width @narrow_width ||= 1 end def wide_width @wide_width ||= 2 end def extended? extended end def start_encoding encoding_for_bars(START_ENCODING) end def stop_encoding encoding_for_bars(STOP_ENCODING) end def valid? if extended? raw_characters.all?{|c| EXTENDED_ENCODINGS.include?(c) } else raw_characters.all?{|c| ENCODINGS.include?(c) } end end def to_s data end end end
toretore/barby
0ef054f6d8ac4ebc3e23362915848f2b73eb4b01
Add bin to gem
diff --git a/barby.gemspec b/barby.gemspec index 323b9d9..67c96bd 100644 --- a/barby.gemspec +++ b/barby.gemspec @@ -1,21 +1,22 @@ $:.push File.expand_path("../lib", __FILE__) require "barby/version" Gem::Specification.new do |s| s.name = "barby" s.version = Barby::VERSION::STRING s.platform = Gem::Platform::RUBY s.summary = "The Ruby barcode generator" s.email = "toredarell@gmail.com" s.homepage = "http://toretore.github.com/barby" s.description = "Barby creates barcodes." s.authors = ['Tore Darell'] s.rubyforge_project = "barby" - s.has_rdoc = true - s.extra_rdoc_files = ["README"] + s.has_rdoc = true + s.extra_rdoc_files = ["README"] - s.files = Dir['CHANGELOG', 'README', 'LICENSE', 'lib/**/*', 'vendor/**/*'] - s.require_paths = ["lib"] -end \ No newline at end of file + s.files = Dir['CHANGELOG', 'README', 'LICENSE', 'lib/**/*', 'vendor/**/*', 'bin/*'] + s.executables = ['barby'] + s.require_paths = ["lib"] +end
toretore/barby
567e3c578bdbd0f8ed3acccc7736b97c1f51a42b
Default to AsciiOutputter for bin/barby
diff --git a/bin/barby b/bin/barby index ce5168c..e61f762 100755 --- a/bin/barby +++ b/bin/barby @@ -1,41 +1,41 @@ #!/usr/bin/env ruby require 'optparse' require 'rubygems' -#$: << File.join(File.dirname(__FILE__), '..', 'lib') +$: << File.join(File.dirname(__FILE__), '..', 'lib') require 'barby' options = { - :outputter => 'Png', - :outputter_method => 'to_png', + :outputter => 'Ascii', + :outputter_method => 'to_ascii', :barcode => 'Code128B' } ARGV.options do |o| o.banner = " Usage: #{File.basename(__FILE__)} [OPTIONS] data" o.define_head ' Generates barcodes and prints the generated output to STDOUT' o.separator '' o.separator ' EXPERIMENTAL' o.separator '' o.on('-b', '--barcode=ClassName', String, 'Barcode type (Code128B)'){|v| options[:barcode] = v } o.on('-o', '--outputter=ClassName', String, 'Outputter (Png)'){|v| options[:outputter] = v } o.on('-m', '--method=method_name', String, 'Outputter method (to_png)'){|v| options[:outputter_method] = v } o.on_tail("-h", "--help", "Show this help message.") { puts o; exit } o.parse! end #p STDIN.read #exit require "barby/outputter/#{options[:outputter].gsub(/[A-Z]/){|c| '_'+c.downcase }[1..-1]}_outputter" barcode_class = Barby.const_get(options[:barcode]) barcode = barcode_class.new($*.empty? ? STDIN.read.chomp : $*) outputter_class = Barby.const_get("#{options[:outputter]}Outputter") outputter = outputter_class.new(barcode) print eval("outputter.#{options[:outputter_method]}(#{ENV['OPTIONS']})")
toretore/barby
ebcc927a6b5dfa2c305af2c5ab7623b70a307495
encoding: utf-8
diff --git a/spec/code_128_spec.rb b/spec/code_128_spec.rb index e5fcf55..d43b97d 100644 --- a/spec/code_128_spec.rb +++ b/spec/code_128_spec.rb @@ -1,355 +1,356 @@ +#encoding: UTF-8 require File.join(File.dirname(__FILE__), 'spec_helper') require 'barby/barcode/code_128' include Barby describe "Common features" do before :each do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the expected stop encoding (including termination bar 11)" do @code.send(:stop_encoding).should == '1100011101011' end it "should find the right class for a character A, B or C" do @code.send(:class_for, 'A').should == Code128A @code.send(:class_for, 'B').should == Code128B @code.send(:class_for, 'C').should == Code128C end it "should find the right change code for a class" do @code.send(:change_code_for_class, Code128A).should == Code128::CODEA @code.send(:change_code_for_class, Code128B).should == Code128::CODEB @code.send(:change_code_for_class, Code128C).should == Code128::CODEC end it "should not allow empty data" do lambda{ Code128B.new("") }.should raise_error(ArgumentError) end end describe "Common features for single encoding" do before :each do @data = 'ABC123' @code = Code128A.new(@data) end it "should have the same data as when initialized" do @code.data.should == @data end it "should be able to change its data" do @code.data = '123ABC' @code.data.should == '123ABC' @code.data.should_not == @data end it "should not have an extra" do @code.extra.should be_nil end it "should have empty extra encoding" do @code.extra_encoding.should == '' end it "should have the correct checksum" do @code.checksum.should == 66 end it "should return all data for to_s" do @code.to_s.should == @data end end describe "Common features for multiple encodings" do before :each do @data = "ABC123\306def\3074567" @code = Code128A.new(@data) end it "should be able to return full_data which includes the entire extra chain excluding charset change characters" do @code.full_data.should == "ABC123def4567" end it "should be able to return full_data_with_change_codes which includes the entire extra chain including charset change characters" do @code.full_data_with_change_codes.should == @data end it "should not matter if extras were added separately" do code = Code128B.new("ABC") code.extra = "\3071234" code.full_data.should == "ABC1234" code.full_data_with_change_codes.should == "ABC\3071234" code.extra.extra = "\306abc" code.full_data.should == "ABC1234abc" code.full_data_with_change_codes.should == "ABC\3071234\306abc" code.extra.extra.data = "abc\305DEF" code.full_data.should == "ABC1234abcDEF" code.full_data_with_change_codes.should == "ABC\3071234\306abc\305DEF" code.extra.extra.full_data.should == "abcDEF" code.extra.extra.full_data_with_change_codes.should == "abc\305DEF" code.extra.full_data.should == "1234abcDEF" code.extra.full_data_with_change_codes.should == "1234\306abc\305DEF" end it "should have a Code B extra" do @code.extra.should be_an_instance_of(Code128B) end it "should have a valid extra" do @code.extra.should be_valid end it "the extra should also have an extra of type C" do @code.extra.extra.should be_an_instance_of(Code128C) end it "the extra's extra should be valid" do @code.extra.extra.should be_valid end it "should not have more than two extras" do @code.extra.extra.extra.should be_nil end it "should split extra data from string on data assignment" do @code.data = "123\306abc" @code.data.should == '123' @code.extra.should be_an_instance_of(Code128B) @code.extra.data.should == 'abc' end it "should be be able to change its extra" do @code.extra = "\3071234" @code.extra.should be_an_instance_of(Code128C) @code.extra.data.should == '1234' end it "should split extra data from string on extra assignment" do @code.extra = "\306123\3074567" @code.extra.should be_an_instance_of(Code128B) @code.extra.data.should == '123' @code.extra.extra.should be_an_instance_of(Code128C) @code.extra.extra.data.should == '4567' end it "should not fail on newlines in extras" do code = Code128B.new("ABC\305\n") code.data.should == "ABC" code.extra.should be_an_instance_of(Code128A) code.extra.data.should == "\n" code.extra.extra = "\305\n\n\n\n\n\nVALID" code.extra.extra.data.should == "\n\n\n\n\n\nVALID" end it "should raise an exception when extra string doesn't start with the special code character" do lambda{ @code.extra = '123' }.should raise_error end it "should have the correct checksum" do @code.checksum.should == 84 end it "should have the expected encoding" do #STARTA A B C 1 2 3 @code.encoding.should == '11010000100101000110001000101100010001000110100111001101100111001011001011100'+ #CODEB d e f '10111101110100001001101011001000010110000100'+ #CODEC 45 67 '101110111101011101100010000101100'+ #CHECK=84 STOP '100111101001100011101011' end it "should return all data including extras, except change codes for to_s" do @code.to_s.should == "ABC123def4567" end end describe "128A" do before :each do @data = 'ABC123' @code = Code128A.new(@data) end it "should be valid when given valid data" do @code.should be_valid end it "should not be valid when given invalid data" do @code.data = 'abc123' @code.should_not be_valid end it "should have the expected characters" do @code.characters.should == %w(A B C 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.should == '11010000100' end it "should have the expected data encoding" do @code.data_encoding.should == '101000110001000101100010001000110100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.should == '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.should == '10010000110' end end describe "128B" do before :each do @data = 'abc123' @code = Code128B.new(@data) end it "should be valid when given valid data" do @code.should be_valid end it "should not be valid when given invalid data" do @code.data = 'abc£123' @code.should_not be_valid end it "should have the expected characters" do @code.characters.should == %w(a b c 1 2 3) end it "should have the expected start encoding" do @code.start_encoding.should == '11010010000' end it "should have the expected data encoding" do @code.data_encoding.should == '100101100001001000011010000101100100111001101100111001011001011100' end it "should have the expected encoding" do @code.encoding.should == '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.should == '11011101110' end end describe "128C" do before :each do @data = '123456' @code = Code128C.new(@data) end it "should be valid when given valid data" do @code.should be_valid end it "should not be valid when given invalid data" do @code.data = '123' @code.should_not be_valid @code.data = 'abc' @code.should_not be_valid end it "should have the expected characters" do @code.characters.should == %w(12 34 56) end it "should have the expected start encoding" do @code.start_encoding.should == '11010011100' end it "should have the expected data encoding" do @code.data_encoding.should == '101100111001000101100011100010110' end it "should have the expected encoding" do @code.encoding.should == '11010011100101100111001000101100011100010110100011011101100011101011' end it "should have the expected checksum encoding" do @code.checksum_encoding.should == '10001101110' end end describe "Function characters" do it "should retain the special symbols in the data accessor" do Code128A.new("\301ABC\301DEF").data.should == "\301ABC\301DEF" Code128B.new("\301ABC\302DEF").data.should == "\301ABC\302DEF" Code128C.new("\301123456").data.should == "\301123456" Code128C.new("12\30134\30156").data.should == "12\30134\30156" end it "should keep the special symbols as characters" do Code128A.new("\301ABC\301DEF").characters.should == %W(\301 A B C \301 D E F) Code128B.new("\301ABC\302DEF").characters.should == %W(\301 A B C \302 D E F) Code128C.new("\301123456").characters.should == %W(\301 12 34 56) Code128C.new("12\30134\30156").characters.should == %W(12 \301 34 \301 56) end it "should not allow FNC > 1 for Code C" do lambda{ Code128C.new("12\302") }.should raise_error lambda{ Code128C.new("\30312") }.should raise_error lambda{ Code128C.new("12\304") }.should raise_error end it "should be included in the encoding" do a = Code128A.new("\301AB") a.data_encoding.should == '111101011101010001100010001011000' a.encoding.should == '11010000100111101011101010001100010001011000101000011001100011101011' end end describe "Code128 with type" do it "should raise an exception when not given a type" do lambda{ Code128.new('abc') }.should raise_error(ArgumentError) end it "should raise an exception when given a non-existent type" do lambda{ Code128.new('abc', 'F') }.should raise_error(ArgumentError) end it "should give the right encoding for type A" do code = Code128.new('ABC123', 'A') code.encoding.should == '11010000100101000110001000101100010001000110100111001101100111001011001011100100100001101100011101011' end it "should give the right encoding for type B" do code = Code128.new('abc123', 'B') code.encoding.should == '11010010000100101100001001000011010000101100100111001101100111001011001011100110111011101100011101011' end it "should give the right encoding for type B" do code = Code128.new('123456', 'C') code.encoding.should == '11010011100101100111001000101100011100010110100011011101100011101011' end end
toretore/barby
e26900ce63b5fa95e8661f5f477d29f6b142670c
Rename ASCIIOutputter class to AsciiOutputter in line with the others
diff --git a/lib/barby/outputter/ascii_outputter.rb b/lib/barby/outputter/ascii_outputter.rb index 86df8ed..697769f 100644 --- a/lib/barby/outputter/ascii_outputter.rb +++ b/lib/barby/outputter/ascii_outputter.rb @@ -1,41 +1,41 @@ require 'barby/outputter' module Barby #Outputs an ASCII representation of the barcode. This is mostly useful for printing #the barcode directly to the terminal for testing. # #Registers to_ascii - class ASCIIOutputter < Outputter + class AsciiOutputter < Outputter register :to_ascii def to_ascii(opts={}) default_opts = {:height => 10, :xdim => 1, :bar => '#', :space => ' '} default_opts.update(:height => 1, :bar => ' X ', :space => ' ') if barcode.two_dimensional? opts = default_opts.merge(opts) if barcode.two_dimensional? booleans.map do |bools| line_to_ascii(bools, opts) end.join("\n") else line_to_ascii(booleans, opts) end end private def line_to_ascii(booleans, opts) Array.new( opts[:height], booleans.map{|b| (b ? opts[:bar] : opts[:space]) * opts[:xdim] }.join ).join("\n") end end end
toretore/barby
95015c98d54945a2e2d5fc103c968c13a27425c7
remove git for file listing
diff --git a/barby.gemspec b/barby.gemspec index eefe1de..323b9d9 100644 --- a/barby.gemspec +++ b/barby.gemspec @@ -1,23 +1,21 @@ $:.push File.expand_path("../lib", __FILE__) require "barby/version" Gem::Specification.new do |s| s.name = "barby" s.version = Barby::VERSION::STRING s.platform = Gem::Platform::RUBY s.summary = "The Ruby barcode generator" s.email = "toredarell@gmail.com" s.homepage = "http://toretore.github.com/barby" s.description = "Barby creates barcodes." s.authors = ['Tore Darell'] s.rubyforge_project = "barby" s.has_rdoc = true s.extra_rdoc_files = ["README"] - s.files = `git ls-files`.split("\n") - s.test_files = `git ls-files -- spec/*`.split("\n") - s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } + s.files = Dir['CHANGELOG', 'README', 'LICENSE', 'lib/**/*', 'vendor/**/*'] s.require_paths = ["lib"] end \ No newline at end of file
toretore/barby
5b2fa139324248e3ca15a15857562423a3ea621a
Extracted gemspec from Rakefile to make work with bundler
diff --git a/Rakefile b/Rakefile index cd891c8..9e3b3b5 100644 --- a/Rakefile +++ b/Rakefile @@ -1,42 +1,26 @@ require 'rake' require 'rake/gempackagetask' require 'fileutils' require 'rake' require 'spec/rake/spectask' include FileUtils -spec = Gem::Specification.new do |s| - s.name = "barby" - s.version = "0.4.2" - s.author = "Tore Darell" - s.email = "toredarell@gmail.com" - s.homepage = "http://toretore.github.com/barby" - s.platform = Gem::Platform::RUBY - s.summary = "The Ruby barcode generator" - s.description = "Barby creates barcodes." - s.rubyforge_project = "barby" - s.files = FileList["lib/**/*", "bin/*", "vendor/**/*"].to_a - s.require_path = "lib" - s.has_rdoc = true - s.extra_rdoc_files = ["README"] -end - Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = false end task :default => "pkg/#{spec.name}-#{spec.version}.gem" do puts "generated latest version" end desc "Run all examples" Spec::Rake::SpecTask.new('spec') do |t| t.libs << './lib' t.ruby_opts << '-rubygems' t.spec_files = FileList['spec/*.rb'] end desc "Build RDoc" task :doc do system "rm -rf site/rdoc; rdoc -tBarby -xvendor -osite/rdoc -mREADME lib/**/* README" end diff --git a/barby.gemspec b/barby.gemspec new file mode 100644 index 0000000..eefe1de --- /dev/null +++ b/barby.gemspec @@ -0,0 +1,23 @@ +$:.push File.expand_path("../lib", __FILE__) +require "barby/version" + +Gem::Specification.new do |s| + s.name = "barby" + s.version = Barby::VERSION::STRING + s.platform = Gem::Platform::RUBY + s.summary = "The Ruby barcode generator" + s.email = "toredarell@gmail.com" + s.homepage = "http://toretore.github.com/barby" + s.description = "Barby creates barcodes." + s.authors = ['Tore Darell'] + + s.rubyforge_project = "barby" + + s.has_rdoc = true + s.extra_rdoc_files = ["README"] + + s.files = `git ls-files`.split("\n") + s.test_files = `git ls-files -- spec/*`.split("\n") + s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } + s.require_paths = ["lib"] +end \ No newline at end of file
toretore/barby
b55806f565120e43b1e7be4ef4358842f1021620
Make chunky_png the default for PngOutputter
diff --git a/lib/barby/outputter/chunky_png_outputter.rb b/lib/barby/outputter/chunky_png_outputter.rb deleted file mode 100644 index 27f7272..0000000 --- a/lib/barby/outputter/chunky_png_outputter.rb +++ /dev/null @@ -1,107 +0,0 @@ -require 'barby/outputter' -require 'chunky_png' - -module Barby - - #Renders the barcode to a PNG image using the "png" gem (gem install png) - # - #Registers the to_png, to_datastream and to_canvas methods - class ChunkyPngOutputter < Outputter - - register :to_png, :to_image, :to_datastream - - attr_accessor :xdim, :ydim, :width, :height, :margin - - - #Creates a PNG::Canvas object and renders the barcode on it - def to_image(opts={}) - with_options opts do - canvas = ChunkyPNG::Image.new(full_width, full_height, ChunkyPNG::Color::WHITE) - - if barcode.two_dimensional? - x, y = margin, margin - booleans.each do |line| - line.each do |bar| - if bar - x.upto(x+(xdim-1)) do |xx| - y.upto y+(ydim-1) do |yy| - canvas[xx,yy] = ChunkyPNG::Color::BLACK - end - end - end - x += xdim - end - y += ydim - x = margin - end - else - x, y = margin, margin - booleans.each do |bar| - if bar - x.upto(x+(xdim-1)) do |xx| - y.upto y+(height-1) do |yy| - canvas[xx,yy] = ChunkyPNG::Color::BLACK - end - end - end - x += xdim - end - end - - canvas - end - end - - - #Create a ChunkyPNG::Datastream containing the barcode image - # - # :constraints - Value is passed on to ChunkyPNG::Image#to_datastream - # E.g. to_datastream(:constraints => {:color_mode => ChunkyPNG::COLOR_GRAYSCALE}) - def to_datastream(*a) - constraints = a.first && a.first[:constraints] ? [a.first[:constraints]] : [] - to_image(*a).to_datastream(*constraints) - end - - - #Renders the barcode to a PNG image - def to_png(*a) - to_datastream(*a).to_s - end - - - def width - length * xdim - end - - def height - barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) - end - - def full_width - width + (margin * 2) - end - - def full_height - height + (margin * 2) - end - - def xdim - @xdim || 1 - end - - def ydim - @ydim || xdim - end - - def margin - @margin || 10 - end - - def length - barcode.two_dimensional? ? encoding.first.length : encoding.length - end - - - end - -end diff --git a/lib/barby/outputter/png_outputter.rb b/lib/barby/outputter/png_outputter.rb index d427e94..dfbb12c 100644 --- a/lib/barby/outputter/png_outputter.rb +++ b/lib/barby/outputter/png_outputter.rb @@ -1,97 +1,107 @@ require 'barby/outputter' -require 'png' +require 'chunky_png' module Barby - #Renders the barcode to a PNG image using the "png" gem (gem install png) + #Renders the barcode to a PNG image using chunky_png (gem install chunky_png) # - #Registers the to_png and to_canvas methods + #Registers the to_png, to_datastream and to_canvas methods class PngOutputter < Outputter - register :to_png, :to_canvas + register :to_png, :to_image, :to_datastream attr_accessor :xdim, :ydim, :width, :height, :margin #Creates a PNG::Canvas object and renders the barcode on it - def to_canvas(opts={}) + def to_image(opts={}) with_options opts do - canvas = PNG::Canvas.new(full_width, full_height, PNG::Color::White) + canvas = ChunkyPNG::Image.new(full_width, full_height, ChunkyPNG::Color::WHITE) if barcode.two_dimensional? x, y = margin, margin - booleans.reverse_each do |line| + booleans.each do |line| line.each do |bar| if bar x.upto(x+(xdim-1)) do |xx| y.upto y+(ydim-1) do |yy| - canvas[xx,yy] = PNG::Color::Black + canvas[xx,yy] = ChunkyPNG::Color::BLACK end end end x += xdim end y += ydim x = margin end else x, y = margin, margin booleans.each do |bar| if bar x.upto(x+(xdim-1)) do |xx| y.upto y+(height-1) do |yy| - canvas[xx,yy] = PNG::Color::Black + canvas[xx,yy] = ChunkyPNG::Color::BLACK end end end x += xdim end end canvas end end + #Create a ChunkyPNG::Datastream containing the barcode image + # + # :constraints - Value is passed on to ChunkyPNG::Image#to_datastream + # E.g. to_datastream(:constraints => {:color_mode => ChunkyPNG::COLOR_GRAYSCALE}) + def to_datastream(*a) + constraints = a.first && a.first[:constraints] ? [a.first[:constraints]] : [] + to_image(*a).to_datastream(*constraints) + end + + #Renders the barcode to a PNG image def to_png(*a) - PNG.new(to_canvas(*a)).to_blob + to_datastream(*a).to_s end def width length * xdim end def height barcode.two_dimensional? ? (ydim * encoding.length) : (@height || 100) end def full_width width + (margin * 2) end def full_height height + (margin * 2) end def xdim @xdim || 1 end def ydim @ydim || xdim end def margin @margin || 10 end def length barcode.two_dimensional? ? encoding.first.length : encoding.length end end end diff --git a/spec/chunky_png_outputter_spec.rb b/spec/png_outputter.rb similarity index 90% rename from spec/chunky_png_outputter_spec.rb rename to spec/png_outputter.rb index 6be51ba..4ce3b2e 100644 --- a/spec/chunky_png_outputter_spec.rb +++ b/spec/png_outputter.rb @@ -1,50 +1,50 @@ require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/outputter/chunky_png_outputter' +require 'barby/outputter/png_outputter' include Barby class TestBarcode < Barcode def initialize(data) @data = data end def encoding @data end end -describe ChunkyPngOutputter do +describe PngOutputter do before :each do @barcode = TestBarcode.new('10110011100011110000') - @outputter = ChunkyPngOutputter.new(@barcode) + @outputter = PngOutputter.new(@barcode) end it "should register to_png and to_image" do Barcode.outputters.should include(:to_png, :to_image) end it "should return a ChunkyPNG::Datastream on to_datastream" do @barcode.to_datastream.should be_an_instance_of(ChunkyPNG::Datastream) end it "should return a string on to_png" do @barcode.to_png.should be_an_instance_of(String) end it "should return a ChunkyPNG::Image on to_canvas" do @barcode.to_image.should be_an_instance_of(ChunkyPNG::Image) end it "should have a width equal to Xdim * barcode_string.length" do @outputter.width.should == @outputter.barcode.encoding.length * @outputter.xdim end it "should have a full_width which is the sum of width + (margin*2)" do @outputter.full_width.should == @outputter.width + (@outputter.margin*2) end it "should have a full_height which is the sum of height + (margin*2)" do @outputter.full_height.should == @outputter.height + (@outputter.margin*2) end end diff --git a/spec/png_outputter_spec.rb b/spec/png_outputter_spec.rb deleted file mode 100644 index aaab1dd..0000000 --- a/spec/png_outputter_spec.rb +++ /dev/null @@ -1,46 +0,0 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') -require 'barby/outputter/png_outputter' -include Barby - -class TestBarcode < Barcode - def initialize(data) - @data = data - end - def encoding - @data - end -end - - -describe PngOutputter do - - before :each do - @barcode = TestBarcode.new('10110011100011110000') - @outputter = PngOutputter.new(@barcode) - end - - it "should register to_png and to_canvas" do - Barcode.outputters.should include(:to_png, :to_canvas) - end - - it "should return a string on to_png" do - @barcode.to_png.should be_an_instance_of(String) - end - - it "should return a PNG::Canvas on to_canvas" do - @barcode.to_canvas.should be_an_instance_of(PNG::Canvas) - end - - it "should have a width equal to Xdim * barcode_string.length" do - @outputter.width.should == @outputter.barcode.encoding.length * @outputter.xdim - end - - it "should have a full_width which is the sum of width + (margin*2)" do - @outputter.full_width.should == @outputter.width + (@outputter.margin*2) - end - - it "should have a full_height which is the sum of height + (margin*2)" do - @outputter.full_height.should == @outputter.height + (@outputter.margin*2) - end - -end
toretore/barby
fb7396606bab54c0f33c0bc928ce6361624b6c2b
Add convenience UPCA class
diff --git a/lib/barby/barcode/ean_13.rb b/lib/barby/barcode/ean_13.rb index 5fa8767..f889926 100644 --- a/lib/barby/barcode/ean_13.rb +++ b/lib/barby/barcode/ean_13.rb @@ -1,178 +1,186 @@ require 'barby/barcode' module Barby #EAN-13, aka UPC-A, barcodes are the ones you can see at your local #supermarket, in your house and, well, everywhere.. # #To use this for a UPC barcode, just add a 0 to the front class EAN13 < Barcode1D LEFT_ENCODINGS_ODD = { 0 => '0001101', 1 => '0011001', 2 => '0010011', 3 => '0111101', 4 => '0100011', 5 => '0110001', 6 => '0101111', 7 => '0111011', 8 => '0110111', 9 => '0001011' } LEFT_ENCODINGS_EVEN = { 0 => '0100111', 1 => '0110011', 2 => '0011011', 3 => '0100001', 4 => '0011101', 5 => '0111001', 6 => '0000101', 7 => '0010001', 8 => '0001001', 9 => '0010111' } RIGHT_ENCODINGS = { 0 => '1110010', 1 => '1100110', 2 => '1101100', 3 => '1000010', 4 => '1011100', 5 => '1001110', 6 => '1010000', 7 => '1000100', 8 => '1001000', 9 => '1110100' } #Describes whether the left-hand encoding should use #LEFT_ENCODINGS_ODD or LEFT_ENCODINGS_EVEN, based on the #first digit in the number system (and the barcode as a whole) LEFT_PARITY_MAPS = { 0 => [:odd, :odd, :odd, :odd, :odd, :odd], #UPC-A 1 => [:odd, :odd, :even, :odd, :even, :even], 2 => [:odd, :odd, :even, :even, :odd, :even], 3 => [:odd, :odd, :even, :even, :even, :odd], 4 => [:odd, :even, :odd, :odd, :even, :even], 5 => [:odd, :even, :even, :odd, :odd, :even], 6 => [:odd, :even, :even, :even, :odd, :odd], 7 => [:odd, :even, :odd, :even, :odd, :even], 8 => [:odd, :even, :odd, :even, :even, :odd], 9 => [:odd, :even, :even, :odd, :even, :odd] } #These are the lines that "stick down" in the graphical representation START = '101' CENTER = '01010' STOP = '101' #EAN-13 barcodes have 12 digits + check digit FORMAT = /^\d{12}$/ attr_accessor :data def initialize(data) self.data = data raise ArgumentError, 'data not valid' unless valid? end def characters data.split(//) end def numbers characters.map{|s| s.to_i } end def odd_and_even_numbers alternater = false numbers.reverse.partition{ alternater = !alternater } end #Numbers that are encoded to the left of the center #The first digit is not included def left_numbers numbers[1,6] end #Numbers that are encoded to the right of the center #The checksum is included here def right_numbers numbers_with_checksum[7,6] end def numbers_with_checksum numbers + [checksum] end def data_with_checksum data + checksum.to_s end def left_encodings left_parity_map.zip(left_numbers).map do |parity,number| parity == :odd ? LEFT_ENCODINGS_ODD[number] : LEFT_ENCODINGS_EVEN[number] end end def right_encodings right_numbers.map{|n| RIGHT_ENCODINGS[n] } end def left_encoding left_encodings.join end def right_encoding right_encodings.join end def encoding start_encoding+left_encoding+center_encoding+right_encoding+stop_encoding end #The parities to use for encoding left-hand numbers def left_parity_map LEFT_PARITY_MAPS[numbers.first] end def weighted_sum odds, evens = odd_and_even_numbers odds.map!{|n| n * 3 } sum = (odds+evens).inject(0){|s,n| s+n } end #Mod10 def checksum mod = weighted_sum % 10 mod.zero? ? 0 : 10-mod end def checksum_encoding RIGHT_ENCODINGS[checksum] end def valid? data =~ FORMAT end def to_s data_with_checksum end #Is this a UPC-A barcode? #UPC barcodes are EAN codes that start with 0 def upc? numbers.first.zero? end def start_encoding START end def center_encoding CENTER end def stop_encoding STOP end end + class UPCA < EAN13 + + def data + '0' + super + end + + end + end
toretore/barby
243f3d0f45bc010c727365e20ffb445b598b2af6
Load UPCSupplemental by default
diff --git a/lib/barby.rb b/lib/barby.rb index c249e07..b6c9849 100644 --- a/lib/barby.rb +++ b/lib/barby.rb @@ -1,17 +1,18 @@ require 'barby/vendor' require 'barby/version' require 'barby/barcode' require 'barby/barcode/code_128' require 'barby/barcode/gs1_128' require 'barby/barcode/code_39' require 'barby/barcode/code_93' require 'barby/barcode/ean_13' require 'barby/barcode/ean_8' +require 'barby/barcode/upc_supplemental' require 'barby/barcode/bookland' require 'barby/barcode/qr_code' require 'barby/barcode/code_25' require 'barby/barcode/code_25_interleaved' require 'barby/barcode/code_25_iata' require 'barby/outputter'
toretore/barby
a080c44df28fe76b4529cf101b27d418e51d0355
Add 2-digit UPC supp
diff --git a/lib/barby/barcode/upc_supplemental.rb b/lib/barby/barcode/upc_supplemental.rb index b842e35..b5183f0 100644 --- a/lib/barby/barcode/upc_supplemental.rb +++ b/lib/barby/barcode/upc_supplemental.rb @@ -1,112 +1,140 @@ require 'barby/barcode' require 'barby/barcode/ean_13' module Barby class UPCSupplemental < Barby::Barcode1D attr_accessor :data - FORMAT = /^\d\d\d\d\d$/ + FORMAT = /^\d\d\d\d\d$|^\d\d$/ START = '1011' SEPARATOR = '01' ODD = :odd EVEN = :even PARITY_MAPS = { - 0 => [EVEN, EVEN, ODD, ODD, ODD], - 1 => [EVEN, ODD, EVEN, ODD, ODD], - 2 => [EVEN, ODD, ODD, EVEN, ODD], - 3 => [EVEN, ODD, ODD, ODD, EVEN], - 4 => [ODD, EVEN, EVEN, ODD, ODD], - 5 => [ODD, ODD, EVEN, EVEN, ODD], - 6 => [ODD, ODD, ODD, EVEN, EVEN], - 7 => [ODD, EVEN, ODD, EVEN, ODD], - 8 => [ODD, EVEN, ODD, ODD, EVEN], - 9 => [ODD, ODD, EVEN, ODD, EVEN] + 2 => { + 0 => [ODD, ODD], + 1 => [ODD, EVEN], + 2 => [EVEN, ODD], + 3 => [EVEN, EVEN] + }, + 5 => { + 0 => [EVEN, EVEN, ODD, ODD, ODD], + 1 => [EVEN, ODD, EVEN, ODD, ODD], + 2 => [EVEN, ODD, ODD, EVEN, ODD], + 3 => [EVEN, ODD, ODD, ODD, EVEN], + 4 => [ODD, EVEN, EVEN, ODD, ODD], + 5 => [ODD, ODD, EVEN, EVEN, ODD], + 6 => [ODD, ODD, ODD, EVEN, EVEN], + 7 => [ODD, EVEN, ODD, EVEN, ODD], + 8 => [ODD, EVEN, ODD, ODD, EVEN], + 9 => [ODD, ODD, EVEN, ODD, EVEN] + } } ENCODINGS = { ODD => EAN13::LEFT_ENCODINGS_ODD, EVEN => EAN13::LEFT_ENCODINGS_EVEN } def initialize(data) self.data = data end + def size + data.size + end + + def two_digit? + size == 2 + end + + def five_digit? + size == 5 + end + + def characters data.split(//) end def digits characters.map{|c| c.to_i } end + #Odd and even methods are only useful for 5 digits def odd_digits alternater = false digits.reverse.select{ alternater = !alternater } end def even_digits alternater = true digits.reverse.select{ alternater = !alternater } end - def odd_sum odd_digits.inject(0){|s,d| s + d * 3 } end def even_sum even_digits.inject(0){|s,d| s + d * 9 } end + #Checksum is different for 2 and 5 digits + #2-digits don't really have a checksum, just a remainder to look up the parity def checksum - (odd_sum + even_sum) % 10 + if two_digit? + data.to_i % 4 + elsif five_digit? + (odd_sum + even_sum) % 10 + end end + #Parity maps are different for 2 and 5 digits def parity_map - PARITY_MAPS[checksum] + PARITY_MAPS[size][checksum] end def encoded_characters parity_map.zip(digits).map do |parity, digit| ENCODINGS[parity][digit] end end def encoding START + encoded_characters.join(SEPARATOR) end def valid? data =~ FORMAT end def to_s data end NO_PRICE = new('90000') #The book doesn't have a suggested retail price COMPLIMENTARY = new('99991') #The book is complimentary (~free) USED = new('99990') #The book is marked as used end end diff --git a/spec/upc_supplemental.rb b/spec/upc_supplemental.rb index 56a0958..524ea67 100644 --- a/spec/upc_supplemental.rb +++ b/spec/upc_supplemental.rb @@ -1,90 +1,110 @@ require File.join(File.dirname(__FILE__), 'spec_helper') require 'barby/barcode/upc_supplemental' include Barby describe UPCSupplemental, 'validity' do - before :each do - @valid = UPCSupplemental.new('12345') - end - - it 'should be valid with 5 digits' do - @valid.should be_valid + it 'should be valid with 2 or 5 digits' do + UPCSupplemental.new('12345').should be_valid + UPCSupplemental.new('12').should be_valid end - it 'should not be valid with less than 5 digits' do + it 'should not be valid with any number of digits other than 2 or 5' do UPCSupplemental.new('1234').should_not be_valid - UPCSupplemental.new('12').should_not be_valid - end - - it 'should not be valid with more than 5 digits' do + UPCSupplemental.new('123').should_not be_valid + UPCSupplemental.new('1').should_not be_valid UPCSupplemental.new('123456').should_not be_valid UPCSupplemental.new('123456789012').should_not be_valid end it 'should not be valid with non-digit characters' do UPCSupplemental.new('abcde').should_not be_valid UPCSupplemental.new('ABC').should_not be_valid UPCSupplemental.new('1234e').should_not be_valid UPCSupplemental.new('!2345').should_not be_valid + UPCSupplemental.new('ab').should_not be_valid + UPCSupplemental.new('1b').should_not be_valid + UPCSupplemental.new('a1').should_not be_valid end end -describe UPCSupplemental, 'checksum' do +describe UPCSupplemental, 'checksum for 5 digits' do it 'should have the expected odd_digits' do UPCSupplemental.new('51234').odd_digits.should == [4,2,5] UPCSupplemental.new('54321').odd_digits.should == [1,3,5] UPCSupplemental.new('99990').odd_digits.should == [0,9,9] end it 'should have the expected even_digits' do UPCSupplemental.new('51234').even_digits.should == [3,1] UPCSupplemental.new('54321').even_digits.should == [2,4] UPCSupplemental.new('99990').even_digits.should == [9,9] end it 'should have the expected odd and even sums' do UPCSupplemental.new('51234').odd_sum.should == 33 UPCSupplemental.new('54321').odd_sum.should == 27 UPCSupplemental.new('99990').odd_sum.should == 54 UPCSupplemental.new('51234').even_sum.should == 36 UPCSupplemental.new('54321').even_sum.should == 54 UPCSupplemental.new('99990').even_sum.should == 162 end it 'should have the expected checksum' do UPCSupplemental.new('51234').checksum.should == 9 UPCSupplemental.new('54321').checksum.should == 1 UPCSupplemental.new('99990').checksum.should == 6 end end +describe UPCSupplemental, 'checksum for 2 digits' do + + + it 'should have the expected checksum' do + UPCSupplemental.new('51').checksum.should == 3 + UPCSupplemental.new('21').checksum.should == 1 + UPCSupplemental.new('99').checksum.should == 3 + end + + +end + + describe UPCSupplemental, 'encoding' do before :each do @data = '51234' @code = UPCSupplemental.new(@data) end it 'should have the expected encoding' do - # START 5 1 2 3 4 + # START 5 1 2 3 4 UPCSupplemental.new('51234').encoding.should == '1011 0110001 01 0011001 01 0011011 01 0111101 01 0011101'.tr(' ', '') - # 9 9 9 9 0 + # 9 9 9 9 0 UPCSupplemental.new('99990').encoding.should == '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') + # START 5 1 + UPCSupplemental.new('51').encoding.should == '1011 0111001 01 0110011'.tr(' ', '') + # 2 2 + UPCSupplemental.new('22').encoding.should == '1011 0011011 01 0010011'.tr(' ', '') end it 'should be able to change its data' do prev_encoding = @code.encoding @code.data = '99990' @code.encoding.should_not == prev_encoding # 9 9 9 9 0 @code.encoding.should == '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') + prev_encoding = @code.encoding + @code.data = '22' + @code.encoding.should_not == prev_encoding + # 2 2 + @code.encoding.should == '1011 0011011 01 0010011'.tr(' ', '') end end
toretore/barby
372d12564a93837529fe852d08c49818dd2fefc0
Add shortcut constants for common types
diff --git a/lib/barby/barcode/upc_supplemental.rb b/lib/barby/barcode/upc_supplemental.rb index a92d088..b842e35 100644 --- a/lib/barby/barcode/upc_supplemental.rb +++ b/lib/barby/barcode/upc_supplemental.rb @@ -1,107 +1,112 @@ require 'barby/barcode' require 'barby/barcode/ean_13' module Barby class UPCSupplemental < Barby::Barcode1D attr_accessor :data FORMAT = /^\d\d\d\d\d$/ START = '1011' SEPARATOR = '01' ODD = :odd EVEN = :even PARITY_MAPS = { 0 => [EVEN, EVEN, ODD, ODD, ODD], 1 => [EVEN, ODD, EVEN, ODD, ODD], 2 => [EVEN, ODD, ODD, EVEN, ODD], 3 => [EVEN, ODD, ODD, ODD, EVEN], 4 => [ODD, EVEN, EVEN, ODD, ODD], 5 => [ODD, ODD, EVEN, EVEN, ODD], 6 => [ODD, ODD, ODD, EVEN, EVEN], 7 => [ODD, EVEN, ODD, EVEN, ODD], 8 => [ODD, EVEN, ODD, ODD, EVEN], 9 => [ODD, ODD, EVEN, ODD, EVEN] } ENCODINGS = { ODD => EAN13::LEFT_ENCODINGS_ODD, EVEN => EAN13::LEFT_ENCODINGS_EVEN } def initialize(data) self.data = data end def characters data.split(//) end def digits characters.map{|c| c.to_i } end def odd_digits alternater = false digits.reverse.select{ alternater = !alternater } end def even_digits alternater = true digits.reverse.select{ alternater = !alternater } end def odd_sum odd_digits.inject(0){|s,d| s + d * 3 } end def even_sum even_digits.inject(0){|s,d| s + d * 9 } end def checksum (odd_sum + even_sum) % 10 end def parity_map PARITY_MAPS[checksum] end def encoded_characters parity_map.zip(digits).map do |parity, digit| ENCODINGS[parity][digit] end end def encoding START + encoded_characters.join(SEPARATOR) end def valid? data =~ FORMAT end def to_s data end + NO_PRICE = new('90000') #The book doesn't have a suggested retail price + COMPLIMENTARY = new('99991') #The book is complimentary (~free) + USED = new('99990') #The book is marked as used + + end end
toretore/barby
9f3d2f9a3fb5c676b76cc6d4dd1903bf8ccc938a
Refactor
diff --git a/lib/barby/barcode/upc_supplemental.rb b/lib/barby/barcode/upc_supplemental.rb index b04332d..a92d088 100644 --- a/lib/barby/barcode/upc_supplemental.rb +++ b/lib/barby/barcode/upc_supplemental.rb @@ -1,105 +1,107 @@ require 'barby/barcode' +require 'barby/barcode/ean_13' module Barby class UPCSupplemental < Barby::Barcode1D attr_accessor :data FORMAT = /^\d\d\d\d\d$/ START = '1011' - STOP = '' - INTER_CHAR = '01' + SEPARATOR = '01' - PARITY_MAPS = { - 0 => [:even, :even, :odd, :odd, :odd], - 1 => [:even, :odd, :even, :odd, :odd], - 2 => [:even, :odd, :odd, :even, :odd], - 3 => [:even, :odd, :odd, :odd, :even], - 4 => [:odd, :even, :even, :odd, :odd], - 5 => [:odd, :odd, :even, :even, :odd], - 6 => [:odd, :odd, :odd, :even, :even], - 7 => [:odd, :even, :odd, :even, :odd], - 8 => [:odd, :even, :odd, :odd, :even], - 9 => [:odd, :odd, :even, :odd, :even] - } + ODD = :odd + EVEN = :even - ENCODINGS_ODD = { - 0 => '0001101', 1 => '0011001', 2 => '0010011', - 3 => '0111101', 4 => '0100011', 5 => '0110001', - 6 => '0101111', 7 => '0111011', 8 => '0110111', - 9 => '0001011' + PARITY_MAPS = { + 0 => [EVEN, EVEN, ODD, ODD, ODD], + 1 => [EVEN, ODD, EVEN, ODD, ODD], + 2 => [EVEN, ODD, ODD, EVEN, ODD], + 3 => [EVEN, ODD, ODD, ODD, EVEN], + 4 => [ODD, EVEN, EVEN, ODD, ODD], + 5 => [ODD, ODD, EVEN, EVEN, ODD], + 6 => [ODD, ODD, ODD, EVEN, EVEN], + 7 => [ODD, EVEN, ODD, EVEN, ODD], + 8 => [ODD, EVEN, ODD, ODD, EVEN], + 9 => [ODD, ODD, EVEN, ODD, EVEN] } - ENCODINGS_EVEN = { - 0 => '0100111', 1 => '0110011', 2 => '0011011', - 3 => '0100001', 4 => '0011101', 5 => '0111001', - 6 => '0000101', 7 => '0010001', 8 => '0001001', - 9 => '0010111' + ENCODINGS = { + ODD => EAN13::LEFT_ENCODINGS_ODD, + EVEN => EAN13::LEFT_ENCODINGS_EVEN } - def initialize data + def initialize(data) self.data = data end + + def characters + data.split(//) + end + + def digits + characters.map{|c| c.to_i } + end + + def odd_digits alternater = false - data.split(//).reverse.map{|c| c.to_i }.partition{ alternater = !alternater }[0] + digits.reverse.select{ alternater = !alternater } end def even_digits - alternater = false - data.split(//).reverse.map{|c| c.to_i }.partition{ alternater = !alternater }[1] + alternater = true + digits.reverse.select{ alternater = !alternater } end + def odd_sum odd_digits.inject(0){|s,d| s + d * 3 } end def even_sum even_digits.inject(0){|s,d| s + d * 9 } end + def checksum (odd_sum + even_sum) % 10 end - def encoding - check_digit = checksum - - parity_map = PARITY_MAPS[check_digit] - - pos = 0 - e = START - data_chars = data.split('') - for digit_char in data_chars - digit = digit_char.to_i - parity = parity_map[pos] - e += ENCODINGS_ODD[digit] if parity==:odd - e += ENCODINGS_EVEN[digit] if parity==:even - e += INTER_CHAR unless pos == 4 - pos += 1 - end - e + def parity_map + PARITY_MAPS[checksum] end - def two_dimensional? - return false + + def encoded_characters + parity_map.zip(digits).map do |parity, digit| + ENCODINGS[parity][digit] + end end + + def encoding + START + encoded_characters.join(SEPARATOR) + end + + def valid? data =~ FORMAT end + def to_s - data[0,20] + data end + end end
toretore/barby
a35ae847d55385b1cab1bc1adc15bc8a8651b2b0
Add checksum
diff --git a/lib/barby/barcode/upc_supplemental.rb b/lib/barby/barcode/upc_supplemental.rb index 2b13f0c..b04332d 100644 --- a/lib/barby/barcode/upc_supplemental.rb +++ b/lib/barby/barcode/upc_supplemental.rb @@ -1,98 +1,105 @@ require 'barby/barcode' module Barby class UPCSupplemental < Barby::Barcode1D - @data = nil - attr_reader :data + + attr_accessor :data FORMAT = /^\d\d\d\d\d$/ START = '1011' STOP = '' INTER_CHAR = '01' PARITY_MAPS = { - 0 => [:even, :even, :odd, :odd, :odd], - 1 => [:even, :odd, :even, :odd, :odd], - 2 => [:even, :odd, :odd, :even, :odd], - 3 => [:even, :odd, :odd, :odd, :even], - 4 => [:odd, :even, :even, :odd, :odd], - 5 => [:odd, :odd, :even, :even, :odd], - 6 => [:odd, :odd, :odd, :even, :even], - 7 => [:odd, :even, :odd, :even, :odd], - 8 => [:odd, :even, :odd, :odd, :even], - 9 => [:odd, :odd, :even, :odd, :even] - } - - ENCODINGS_ODD = { - 0 => '0001101', 1 => '0011001', 2 => '0010011', - 3 => '0111101', 4 => '0100011', 5 => '0110001', - 6 => '0101111', 7 => '0111011', 8 => '0110111', - 9 => '0001011' - } - - ENCODINGS_EVEN = { - 0 => '0100111', 1 => '0110011', 2 => '0011011', - 3 => '0100001', 4 => '0011101', 5 => '0111001', - 6 => '0000101', 7 => '0010001', 8 => '0001001', - 9 => '0010111' - } - - - - def data= data - @data = data - end + 0 => [:even, :even, :odd, :odd, :odd], + 1 => [:even, :odd, :even, :odd, :odd], + 2 => [:even, :odd, :odd, :even, :odd], + 3 => [:even, :odd, :odd, :odd, :even], + 4 => [:odd, :even, :even, :odd, :odd], + 5 => [:odd, :odd, :even, :even, :odd], + 6 => [:odd, :odd, :odd, :even, :even], + 7 => [:odd, :even, :odd, :even, :odd], + 8 => [:odd, :even, :odd, :odd, :even], + 9 => [:odd, :odd, :even, :odd, :even] + } + + ENCODINGS_ODD = { + 0 => '0001101', 1 => '0011001', 2 => '0010011', + 3 => '0111101', 4 => '0100011', 5 => '0110001', + 6 => '0101111', 7 => '0111011', 8 => '0110111', + 9 => '0001011' + } + + ENCODINGS_EVEN = { + 0 => '0100111', 1 => '0110011', 2 => '0011011', + 3 => '0100001', 4 => '0011101', 5 => '0111001', + 6 => '0000101', 7 => '0010001', 8 => '0001001', + 9 => '0010111' + } + def initialize data self.data = data end + def odd_digits + alternater = false + data.split(//).reverse.map{|c| c.to_i }.partition{ alternater = !alternater }[0] + end + + def even_digits + alternater = false + data.split(//).reverse.map{|c| c.to_i }.partition{ alternater = !alternater }[1] + end + + def odd_sum + odd_digits.inject(0){|s,d| s + d * 3 } + end + + def even_sum + even_digits.inject(0){|s,d| s + d * 9 } + end + + def checksum + (odd_sum + even_sum) % 10 + end + def encoding - begin - data = @data - return nil if data.length!=5 - sum_odd = data[0].chr.to_i + data[2].chr.to_i + data[4].chr.to_i - sum_even = data[1].chr.to_i + data[3].chr.to_i - total = sum_odd * 3 + sum_even * 9 - check_digit = total.modulo(10) - - parity_map = PARITY_MAPS[check_digit] - - pos = 0 - e = START - data_chars = data.split('') - for digit_char in data_chars - digit = digit_char.to_i - parity = parity_map[pos] - e += ENCODINGS_ODD[digit] if parity==:odd - e += ENCODINGS_EVEN[digit] if parity==:even - e += INTER_CHAR unless pos == 4 - pos += 1 - end - - - return e - - rescue + check_digit = checksum + + parity_map = PARITY_MAPS[check_digit] + + pos = 0 + e = START + data_chars = data.split('') + for digit_char in data_chars + digit = digit_char.to_i + parity = parity_map[pos] + e += ENCODINGS_ODD[digit] if parity==:odd + e += ENCODINGS_EVEN[digit] if parity==:even + e += INTER_CHAR unless pos == 4 + pos += 1 end + + e end def two_dimensional? return false end def valid? data =~ FORMAT end def to_s data[0,20] end end end diff --git a/spec/upc_supplemental.rb b/spec/upc_supplemental.rb index 16413ae..56a0958 100644 --- a/spec/upc_supplemental.rb +++ b/spec/upc_supplemental.rb @@ -1,32 +1,90 @@ require File.join(File.dirname(__FILE__), 'spec_helper') require 'barby/barcode/upc_supplemental' include Barby describe UPCSupplemental, 'validity' do before :each do @valid = UPCSupplemental.new('12345') end it 'should be valid with 5 digits' do @valid.should be_valid end it 'should not be valid with less than 5 digits' do UPCSupplemental.new('1234').should_not be_valid UPCSupplemental.new('12').should_not be_valid end it 'should not be valid with more than 5 digits' do UPCSupplemental.new('123456').should_not be_valid UPCSupplemental.new('123456789012').should_not be_valid end it 'should not be valid with non-digit characters' do UPCSupplemental.new('abcde').should_not be_valid UPCSupplemental.new('ABC').should_not be_valid UPCSupplemental.new('1234e').should_not be_valid UPCSupplemental.new('!2345').should_not be_valid end end + + +describe UPCSupplemental, 'checksum' do + + it 'should have the expected odd_digits' do + UPCSupplemental.new('51234').odd_digits.should == [4,2,5] + UPCSupplemental.new('54321').odd_digits.should == [1,3,5] + UPCSupplemental.new('99990').odd_digits.should == [0,9,9] + end + + it 'should have the expected even_digits' do + UPCSupplemental.new('51234').even_digits.should == [3,1] + UPCSupplemental.new('54321').even_digits.should == [2,4] + UPCSupplemental.new('99990').even_digits.should == [9,9] + end + + it 'should have the expected odd and even sums' do + UPCSupplemental.new('51234').odd_sum.should == 33 + UPCSupplemental.new('54321').odd_sum.should == 27 + UPCSupplemental.new('99990').odd_sum.should == 54 + + UPCSupplemental.new('51234').even_sum.should == 36 + UPCSupplemental.new('54321').even_sum.should == 54 + UPCSupplemental.new('99990').even_sum.should == 162 + end + + it 'should have the expected checksum' do + UPCSupplemental.new('51234').checksum.should == 9 + UPCSupplemental.new('54321').checksum.should == 1 + UPCSupplemental.new('99990').checksum.should == 6 + end + +end + + +describe UPCSupplemental, 'encoding' do + + before :each do + @data = '51234' + @code = UPCSupplemental.new(@data) + end + + it 'should have the expected encoding' do + # START 5 1 2 3 4 + UPCSupplemental.new('51234').encoding.should == '1011 0110001 01 0011001 01 0011011 01 0111101 01 0011101'.tr(' ', '') + # 9 9 9 9 0 + UPCSupplemental.new('99990').encoding.should == '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') + end + + it 'should be able to change its data' do + prev_encoding = @code.encoding + @code.data = '99990' + @code.encoding.should_not == prev_encoding + # 9 9 9 9 0 + @code.encoding.should == '1011 0001011 01 0001011 01 0001011 01 0010111 01 0100111'.tr(' ', '') + end + +end
alanhogan/contact-form-8
843fc86263f6caf991c29a5b98a4b302c3555c73
Line breaks between checkboxes
diff --git a/modules/checkbox.php b/modules/checkbox.php index e354f0c..d8ecc7b 100644 --- a/modules/checkbox.php +++ b/modules/checkbox.php @@ -1,168 +1,172 @@ <?php /** ** A base module for [checkbox], [checkbox*], and [radio] **/ /* Shortcode handler */ function wpcf7_checkbox_shortcode_handler( $tag ) { global $wpcf7_contact_form; if ( ! is_array( $tag ) ) return ''; $type = $tag['type']; $name = $tag['name']; $options = (array) $tag['options']; $values = (array) $tag['values']; if ( empty( $name ) ) return ''; $atts = ''; $id_att = ''; $class_att = ''; $defaults = array(); $label_first = false; $use_label_element = false; if ( 'checkbox*' == $type ) $class_att .= ' wpcf7-validates-as-required'; if ( 'checkbox' == $type || 'checkbox*' == $type ) $class_att .= ' wpcf7-checkbox'; if ( 'radio' == $type ) $class_att .= ' wpcf7-radio'; foreach ( $options as $option ) { if ( preg_match( '%^id:([-0-9a-zA-Z_]+)$%', $option, $matches ) ) { $id_att = $matches[1]; } elseif ( preg_match( '%^class:([-0-9a-zA-Z_]+)$%', $option, $matches ) ) { $class_att .= ' ' . $matches[1]; } elseif ( preg_match( '/^default:([0-9_]+)$/', $option, $matches ) ) { $defaults = explode( '_', $matches[1] ); } elseif ( preg_match( '%^label[_-]?first$%', $option ) ) { $label_first = true; } elseif ( preg_match( '%^use[_-]?label[_-]?element$%', $option ) ) { $use_label_element = true; } } if ( $id_att ) $atts .= ' id="' . trim( $id_att ) . '"'; if ( $class_att ) $atts .= ' class="' . trim( $class_att ) . '"'; $multiple = preg_match( '/^checkbox[*]?$/', $type ) && ! preg_grep( '%^exclusive$%', $options ); $html = ''; if ( preg_match( '/^checkbox[*]?$/', $type ) && ! $multiple && WPCF7_LOAD_JS ) $onclick = ' onclick="wpcf7ExclusiveCheckbox(this);"'; $input_type = rtrim( $type, '*' ); $posted = is_a( $wpcf7_contact_form, 'WPCF7_ContactForm' ) && $wpcf7_contact_form->is_posted(); + //Array to store HTML of items until it can be glued together with + //<BR>s between checkbox items + $items = array(); foreach ( $values as $key => $value ) { $checked = false; if ( in_array( $key + 1, (array) $defaults ) ) $checked = true; if ( $posted) { if ( $multiple && in_array( esc_sql( $value ), (array) $_POST[$name] ) ) $checked = true; if ( ! $multiple && $_POST[$name] == esc_sql( $value ) ) $checked = true; } $checked = $checked ? ' checked="checked"' : ''; if ( is_array( $tag['labels'] ) && isset( $tag['labels'][$key] ) ) $label = $tag['labels'][$key]; else $label = $value; //Create ID $this_id = 'wpcf8_'.crc32(($id_att?$id_att:'').$value.$label); if ( $label_first ) { // put label first, input last $item = '<label for="'.$this_id.'" class="wpcf7-list-item-label">' . esc_html( $label ) . '</label>&nbsp;'; $item .= '<input type="' . $input_type . '" name="' . $name . ( $multiple ? '[]' : '' ) . '" value="' . esc_attr( $value ) . '" id="'.$this_id.'" ' . $checked . $onclick . ' />'; } else { $item = '<input type="' . $input_type . '" name="' . $name . ( $multiple ? '[]' : '' ) . '" value="' . esc_attr( $value ) . '" id="'.$this_id.'" ' . $checked . $onclick . ' />'; $item .= '&nbsp;<label for="'.$this_id.'" class="wpcf7-list-item-label">' . esc_html( $label ) . '</label>'; } // if ( $use_label_element ) // $item = '<label for="'.$this_id.'">' . $item . '</label>'; // $item = '<span class="wpcf7-list-item">' . $item . '</span>'; - $html .= $item; + $items[] = $item; } - + $html .= implode("\n ",$items); + $html = '<span' . $atts . '>' . $html . '</span>'; $validation_error = ''; if ( is_a( $wpcf7_contact_form, 'WPCF7_ContactForm' ) ) $validation_error = $wpcf7_contact_form->validation_error( $name ); $html = '<span class="wpcf7-form-control-wrap ' . $name . '">' . $html . $validation_error . '</span>'; return $html; } wpcf7_add_shortcode( 'checkbox', 'wpcf7_checkbox_shortcode_handler', true ); wpcf7_add_shortcode( 'checkbox*', 'wpcf7_checkbox_shortcode_handler', true ); wpcf7_add_shortcode( 'radio', 'wpcf7_checkbox_shortcode_handler', true ); /* Validation filter */ function wpcf7_checkbox_validation_filter( $result, $tag ) { global $wpcf7_contact_form; $type = $tag['type']; $name = $tag['name']; $values = $tag['values']; if ( is_array( $_POST[$name] ) ) { foreach ( $_POST[$name] as $key => $value ) { $value = stripslashes( $value ); if ( ! in_array( $value, (array) $values ) ) // Not in given choices. unset( $_POST[$name][$key] ); } } else { $value = stripslashes( $_POST[$name] ); if ( ! in_array( $value, (array) $values ) ) // Not in given choices. $_POST[$name] = ''; } if ( 'checkbox*' == $type ) { if ( empty( $_POST[$name] ) ) { $result['valid'] = false; $result['reason'][$name] = $wpcf7_contact_form->message( 'invalid_required' ); } } return $result; } add_filter( 'wpcf7_validate_checkbox', 'wpcf7_checkbox_validation_filter', 10, 2 ); add_filter( 'wpcf7_validate_checkbox*', 'wpcf7_checkbox_validation_filter', 10, 2 ); add_filter( 'wpcf7_validate_radio', 'wpcf7_checkbox_validation_filter', 10, 2 ); ?> \ No newline at end of file
nickretallack/elemental-chess-web
6ec298bc9f02f559014c43ec6c343e182538289a
removed debug statement
diff --git a/helper.py b/helper.py index 32f31e6..70f5992 100644 --- a/helper.py +++ b/helper.py @@ -1,105 +1,105 @@ import web from database import db import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), line_statement_prefix="#") def user_name(user): if 'name' in user: return user['name'] else: return "anonymous" def hex_color(seed,invert=False): import random import md5 from hsl import HSL_2_RGB digest = md5.new(seed).digest() print digest random.seed(digest) color = HSL_2_RGB(random.random(), 1, random.uniform(.2,.8)) print color hex = "%02X%02X%02X" % color print hex return hex # color = random.randint(0,16**6) # if invert: # color = 16**6 - color # return "%X" % color env.filters['len'] = len env.filters['user_name'] = user_name env.filters['hex_color'] = hex_color try: import json except ImportError: import simplejson as json env.filters['json'] = json.dumps def render(template,**args): return env.get_template(template+'.html').render(**args) import dbview def get_you(): openid = web.openid.status() if openid: key = "user-%s" % openid if key in db: return db[key] else: from random_name import random_name from time import time while True: unique = True name = random_name("%s-%d" % (openid,time())) slug = slugify(name) for row in dbview.users(db, startkey=slug, endkey=slug): if slug == row.key: unique = False break if unique: break you = {'type':'user', 'openids':[openid], "name":name, "slug":slug} db[key] = you return you #def unique_random_name(openid): def get_game(game_id): if game_id not in db: raise web.notfound() game = db[game_id] if game['type'] != "game": raise web.notfound() return game def require_you(): you = get_you() if not you: raise web.HTTPError("401 unauthorized", {}, "You must be logged in") return you def make_timestamp(): from datetime import datetime - return datetime.now().isoformat() + return datetime.now().isoformat() # Modified slugging routines originally stolen from patches to django def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata import re #value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) diff --git a/static/game.js b/static/game.js index f96d30d..398a795 100644 --- a/static/game.js +++ b/static/game.js @@ -1,170 +1,170 @@ $(document).ready(function(){ function find_targets(piece){ var orthogonals = [[0,1],[0,-1],[1,0],[-1,0]] var diagonals = [[-1,-1],[-1,+1],[+1,-1],[+1,+1]] var strengths = {water:'fire', fire:'plant', plant:'water'} // Find legal spaces to move to var kind = piece.attr('data_kind') var movements = orthogonals if(kind == "wizard") movements = orthogonals.concat(diagonals) var space = piece.parents('.space:first') var location = space.attr("data_location").split('-') filter = $(movements).map(function(){ return "[data_location="+(parseInt(location[0])+this[0])+"-"+(parseInt(location[1])+this[1])+"]" }).get().join(',') var neighbors = $('.space').filter(filter) // blacklist ones with disagreeable pieces on them var level = kind.slice(kind.length-1,kind.length) var type = kind.slice(0, kind.length-1) var player = piece.attr('data_player') var targets = neighbors.filter(function(){ var piece = $(this).children('.piece') if(!piece.length) return true // blank spaces are always legal if(piece && kind == 'wizard') return false // wizards can't attack var target_player = piece.attr('data_player') if(player == target_player) return false // can't attack yourself var target_kind = piece.attr('data_kind') if(target_kind == 'wizard') return true // anything beats wizard var target_level = target_kind.slice(target_kind.length-1,target_kind.length) var target_type = target_kind.slice(0, target_kind.length-1) if(strengths[type] == target_type) return true // elemental strengths //if(strengths[target_type] == type) return false if(type == target_type && level > target_level) return true // same type fights by level return false }) return targets } // Moving Pieces var dragging = false var sent_events = {} function update_dragging(){ $(".piece").draggable("destroy") var player = turn_order[turn % turn_order.length] if($.inArray(player,your_players) == -1) return // no dragging other people's stuff $(".piece."+player+"-player").draggable({helper:'clone', scroll:true, start:function(event,ui){ dragging = true $(this).addClass('dragging') }, stop:function(event,ui){ dragging = false $('.highlight').removeClass('highlight') $(this).removeClass('dragging') } }) } update_dragging() $(".space").droppable({accept:".piece", drop:function(event,ui){ piece = ui.draggable from_space = piece.parents(".space:first") to_space = $(this) // check if it's a legal move before we send it if($.inArray(this,find_targets(piece)) == -1) return from_space_tag = from_space.attr("data_location") to_space_tag = to_space.attr("data_location") data = {from_space:from_space_tag, to_space:to_space_tag} $.ajax({type:"POST", url:"/games/"+game_id+"/moves", data:data, success:function(response){ $('#status').text('') sent_events[response] = true move_message("You move", piece.attr('data_kind'), from_space_tag, to_space_tag) }, error:function(response){ $('#status').text(response.responseText) }}) // since we want to be responsive, lets just move the thing right now. to_space.children(".piece").remove() from_space.children(".piece").appendTo(to_space) // and advance the turn ourselves turn += 1 update_dragging() }}) // hilighting moves $(".piece").hover(function(){ var player = turn_order[turn % turn_order.length] if($.inArray(player,your_players) == -1) return // no dragging other people's stuff if($(this).attr('data_player') != player) return if(!dragging) find_targets($(this)).addClass('highlight') }, function(){ if(!dragging) $('.highlight').removeClass('highlight') }) // Getting Game Events var min_event_period = 1000 var event_period = min_event_period var event_check_timer var last_interaction = new Date().getTime() var checking_events = false function move_message(user, piece, from, to){ $('#messages').prepend("<p>"+user+" "+piece+" from "+from+" to "+to+"</p>") } function checkEvents(){ - console.debug(sent_events) + // console.debug(sent_events) checking_events = true var miliseconds_idle = new Date().getTime() - last_interaction event_period = min_event_period + miliseconds_idle*miliseconds_idle / 1000000.0 //console.debug(event_check_timer) $.getJSON('/games/'+game_id+'/events/'+timestamp, function(response){ if(response.timestamp) timestamp = response.timestamp if(response.events){ $.each(response.events, function(){ if(sent_events[this.timestamp]){ // don't apply events you sent yourself delete sent_events[this.timestamp] } else if(this.type == "move"){ var from_space = $("[data_location="+this.from_space+"]") var to_space = $("[data_location="+this.to_space+"]") var piece = from_space.children(".piece") to_space.children(".piece").remove() piece.prependTo(to_space) turn += 1 update_dragging() move_message(this.name+" moves", piece.attr('data_kind'), this.from_space, this.to_space) } else if(this.type == "chat"){ $('#messages').prepend("<p>"+this.name+": "+this.text+"</p>" ) } }) } event_check_timer = setTimeout(checkEvents, event_period) checking_events = false }) } function nudge(){ if (checking_events) return var miliseconds_idle = new Date().getTime() - last_interaction last_interaction = new Date().getTime() if(miliseconds_idle > 5000){ clearTimeout(event_check_timer) checkEvents() } } $(document).mousemove(nudge) $(document).keypress(nudge) event_check_timer = setTimeout(checkEvents, event_period) // Sending Game Chat $('#chat').submit(function(event){ event.preventDefault() var field = $('#chat [name=text]') if(field.val() == '') return data = $(this).serialize() field.val('') $.post('/games/'+game_id+'/chat',data) }) })
nickretallack/elemental-chess-web
6a0dc48dbfde3b002d25b255cd1bfc46274dae35
attack wizards
diff --git a/discussion.txt b/discussion.txt index a7e572d..7c5da66 100644 --- a/discussion.txt +++ b/discussion.txt @@ -1,113 +1,123 @@ To display player names on a game: well, the player's name isn't really part of the game object, so it requires an extra query. I guess we could put those queries in the list comprehension though. Maybe we should break out the game logic into a game class. I guess we could handle the object caching after we have defined that, as object caching is kind of premature optimization right now Okay, this implementation is a little batshit. It would be much more minimal to just make an individual static method for it. +Fault Tolerance may be important here -- sometimes the server fails. +If it fails when you send a move, and doesn't give you a timestamp, then it'll eventually GET that move and do it in the name of a remote player. Crap. +-- ugh, it would have saved the move anyway + Todo: + make wizard killable in js + highlight last moved piece so you know what they did + sounds when people move + put move logs into page template as well as chat, like js does -- colored and small too + win condition + fault tolerance -- see above revert illegal moves factor game logic into game class random unique user names make it look nice player names in a game. randomize game colors with hsl - check that you can create games properly - check game logic on client side - how do I avoid sending the same event back to you? - maintain a list of sent events responsive client-side handling of moving pieces and stuff - detect mouse and keyboard activity, and throttle down polling if there is none for a while - users list so you can start a game with them - hash-colored games - settings page to set your name - Wishlist: unify user system with other projects? stretchy board with jquery resize filter droppables as well as draggables and set revert:true Board representation: It might be easier to represent the board as a hash of string-named spaces. This works for more kinds of games anyway. It's up to the game logic to decide if something on "space_foo" can move to "space_bar", either by deconstructing it into components or maintaining a border list or whatever. Then again, I'd have to remember the board's dimensions somewhere if I wanted to conveniently lay out a table for it. --- Strategy for tolerating multiple events in the same microsecond: 1) fetch all events starting at the requested microsecond 2) construct a new array that skims out all events equal to the requested microsecond 3) if the new array has length zero or one less than the old array, all is well. Return normally. 4) if the new array has length 2 or more less than the old array, return the old array instead 5) on the javascript side, only apply events at our same microsecond that we didn't personally send wait no, this is much simpler: just don't send events back to the client who broadcasted them if they have the same microsecond as requested. Hm, but how do we know which client broadcast them... Perhaps we should use their user id... Yeah, that makes sense. Then we can tell who was controlling a player when they caused an event :D. Nah this is all crap. I think we should just have the client check if they're receiving an event they already know about...? urgh no. Ugh, I have to do something to avoid always sending your own events back to yourself... db formats: (type=first word) move(user(id), from(space_tag), to(space_tag)) chat(user(id), text(string), game(id)) game(board(structure), players(color:id), turn(color)) --- Names: generate random silly names and stick them in the session for now. I guess you could change your name pretty easy by posting it to a url, but then we'd have to check that other people aren't using it... Should we represent players in the database? Do we need to know who's in a game? Lets see. Hm. Well we need to know who's allowed to post a new move, so yes. Maybe I should save the avante-guarde simplicity for later. Okay. Database stuff. Game: players, pieces(player_id, kind_tag, space_tag) hm, maybe you have to be logged in to play, but not to watch. Page setup: index: new game form, list of public games (private/public. Invite users?) Hmm, what about chatting directly at people. I guess we could have chat events that are to someone...(private) game/id: in a game. Hmm. How can we make a humane id for this. is.gd style? but what if people start a game at the same time... ah fuckit, we can use guids for now okay, setting up a game. lets use some old code to generate the board... nah fuckit, storing game data as pieces instead of the board just may be too much work. We have to render the board when you refresh anyway. ---------- okay! The event system would be much more efficient if we did not duplicate records, but instead used timestamps. When a player receives a page from the server, it includes a timestamp in a javascript variable. When they ask for events, they pass that timestamp in. The server finds events that have happened since that timestamp but not equal to it. It then passes them back with the timestamp of the latest one. Nothing is mutated on the server side for this reading action. Including a timestamp in the page: we better make sure there's no caching going on! Perhaps keep a record of the last timestamp you've sent and see if you ever regress. (oh god what about multiple windows... Well, they're safer with the timestamp approach at least. Now we know that if we regress on timestamps, it's likely either a caching problem OR multiple game windows.) Okay, events. Lets try out chat events first. Post text to the chat url. what happens if two events happen at the same microsecond? I guess you'd miss one. Hm. I suppose we could return events that even have a timestamp equal to our last, and then check against things we already know about? -old- We shall have a glorious event system! When a user moves a piece, the board in the system is updated And, an event is created for each player detailing the move When a player checks for new events, all new events are sent to them And, (if the handshake succeeds?) they are deleted When a player loads the board view, all their incoming move events are deleted Should we use timestamps in this event system? They have potential to screw things up, so, perhaps only for show. \ No newline at end of file diff --git a/static/game.js b/static/game.js index 27dfeff..f96d30d 100644 --- a/static/game.js +++ b/static/game.js @@ -1,168 +1,170 @@ $(document).ready(function(){ function find_targets(piece){ var orthogonals = [[0,1],[0,-1],[1,0],[-1,0]] var diagonals = [[-1,-1],[-1,+1],[+1,-1],[+1,+1]] var strengths = {water:'fire', fire:'plant', plant:'water'} // Find legal spaces to move to var kind = piece.attr('data_kind') var movements = orthogonals if(kind == "wizard") movements = orthogonals.concat(diagonals) var space = piece.parents('.space:first') var location = space.attr("data_location").split('-') filter = $(movements).map(function(){ return "[data_location="+(parseInt(location[0])+this[0])+"-"+(parseInt(location[1])+this[1])+"]" }).get().join(',') var neighbors = $('.space').filter(filter) // blacklist ones with disagreeable pieces on them var level = kind.slice(kind.length-1,kind.length) var type = kind.slice(0, kind.length-1) var player = piece.attr('data_player') var targets = neighbors.filter(function(){ var piece = $(this).children('.piece') if(!piece.length) return true // blank spaces are always legal if(piece && kind == 'wizard') return false // wizards can't attack var target_player = piece.attr('data_player') if(player == target_player) return false // can't attack yourself var target_kind = piece.attr('data_kind') + if(target_kind == 'wizard') return true // anything beats wizard var target_level = target_kind.slice(target_kind.length-1,target_kind.length) var target_type = target_kind.slice(0, target_kind.length-1) - if(strengths[type] == target_type) return true - if(strengths[target_type] == type) return false + if(strengths[type] == target_type) return true // elemental strengths + //if(strengths[target_type] == type) return false if(type == target_type && level > target_level) return true // same type fights by level return false }) return targets } // Moving Pieces var dragging = false var sent_events = {} function update_dragging(){ $(".piece").draggable("destroy") var player = turn_order[turn % turn_order.length] if($.inArray(player,your_players) == -1) return // no dragging other people's stuff $(".piece."+player+"-player").draggable({helper:'clone', scroll:true, start:function(event,ui){ dragging = true $(this).addClass('dragging') }, stop:function(event,ui){ dragging = false $('.highlight').removeClass('highlight') $(this).removeClass('dragging') } }) } update_dragging() $(".space").droppable({accept:".piece", drop:function(event,ui){ piece = ui.draggable from_space = piece.parents(".space:first") to_space = $(this) // check if it's a legal move before we send it if($.inArray(this,find_targets(piece)) == -1) return from_space_tag = from_space.attr("data_location") to_space_tag = to_space.attr("data_location") data = {from_space:from_space_tag, to_space:to_space_tag} $.ajax({type:"POST", url:"/games/"+game_id+"/moves", data:data, success:function(response){ $('#status').text('') sent_events[response] = true move_message("You move", piece.attr('data_kind'), from_space_tag, to_space_tag) }, error:function(response){ $('#status').text(response.responseText) }}) // since we want to be responsive, lets just move the thing right now. to_space.children(".piece").remove() from_space.children(".piece").appendTo(to_space) // and advance the turn ourselves turn += 1 update_dragging() }}) // hilighting moves $(".piece").hover(function(){ var player = turn_order[turn % turn_order.length] if($.inArray(player,your_players) == -1) return // no dragging other people's stuff if($(this).attr('data_player') != player) return if(!dragging) find_targets($(this)).addClass('highlight') }, function(){ if(!dragging) $('.highlight').removeClass('highlight') }) // Getting Game Events var min_event_period = 1000 var event_period = min_event_period var event_check_timer var last_interaction = new Date().getTime() + var checking_events = false function move_message(user, piece, from, to){ $('#messages').prepend("<p>"+user+" "+piece+" from "+from+" to "+to+"</p>") } - var checking_events_lock = false function checkEvents(){ - checking_events_lock = true + console.debug(sent_events) + checking_events = true var miliseconds_idle = new Date().getTime() - last_interaction event_period = min_event_period + miliseconds_idle*miliseconds_idle / 1000000.0 //console.debug(event_check_timer) $.getJSON('/games/'+game_id+'/events/'+timestamp, function(response){ if(response.timestamp) timestamp = response.timestamp if(response.events){ - $.each(response.events ,function(){ + $.each(response.events, function(){ if(sent_events[this.timestamp]){ // don't apply events you sent yourself delete sent_events[this.timestamp] } else if(this.type == "move"){ var from_space = $("[data_location="+this.from_space+"]") var to_space = $("[data_location="+this.to_space+"]") var piece = from_space.children(".piece") to_space.children(".piece").remove() piece.prependTo(to_space) turn += 1 update_dragging() move_message(this.name+" moves", piece.attr('data_kind'), this.from_space, this.to_space) } else if(this.type == "chat"){ $('#messages').prepend("<p>"+this.name+": "+this.text+"</p>" ) } }) } event_check_timer = setTimeout(checkEvents, event_period) - checking_events_lock = false + checking_events = false }) } function nudge(){ - if (checking_events_lock) return + if (checking_events) return var miliseconds_idle = new Date().getTime() - last_interaction last_interaction = new Date().getTime() if(miliseconds_idle > 5000){ clearTimeout(event_check_timer) checkEvents() } } $(document).mousemove(nudge) $(document).keypress(nudge) event_check_timer = setTimeout(checkEvents, event_period) // Sending Game Chat $('#chat').submit(function(event){ event.preventDefault() var field = $('#chat [name=text]') if(field.val() == '') return data = $(this).serialize() field.val('') $.post('/games/'+game_id+'/chat',data) }) }) diff --git a/views.py b/views.py index e004467..65f219e 100644 --- a/views.py +++ b/views.py @@ -1,245 +1,246 @@ import web from database import db import dbview #from couch_util import couch_request COUCH_MAX = u"\u9999" from helper import render, get_you, get_game, require_you, make_timestamp from dbview import * import http +try: + import json +except ImportError: + import simplejson as json + + from game_model import User, Game class IndexView: def GET(self): you = get_you() games = Game.all() users = User.all() return render("index", games=games, users=users, you=get_you()) class UserView: def GET(self, slug): user = User.get(slug=slug) return render("user", user=user, you=get_you()) class GameView: def GET(self, game_id): game = Game.get(game_id) chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True) you = get_you() #players = dict([(color, db[player_id]) for (color,player_id) in game["players"].iteritems()]) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if you: your_players = [color for (color,player) in game.players.items() if player.id == you.id] #print "Your Players: %s" % game.players.items()[0].id else: print "NOTHING" your_players = [] return render('game',game=game, you=get_you(), chats=chats, your_players=your_players) class GameEventsView: def GET(self, game_id, timestamp): - try: - import json - except ImportError: - import simplejson as json events = dbview.events(db, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows if not len(events): # no events have happened in this game yet, most likely return json.dumps({"timestamp":timestamp}) newest_timestamp = events[-1].key[1] # highly dependent on query new_events = [event.value for event in events if event.key[1] != timestamp] if not len(new_events): return "{}" return json.dumps({"timestamp":newest_timestamp, "events":new_events}) class GamesView: def POST(self): you = require_you() params = web.input() if not params["user"]: return web.notfound() user = dbview.users(db, startkey=params['user'], endkey=params['user']).rows if not len(user): return web.notfound() else: user = user[0] from setup_board import board game = {"type":"game", "board":board, "timestamp":make_timestamp(), "turn":0, "players":{"red":you.id,"blue":user.id}, "order":["red","blue"]} game_id = db.create(game) web.seeother("/games/%s" % game_id) class GameChatView: #def GET(self, game_id): # could just give us the chats, for debug purposes def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(text='') text = params["text"] if len(text) == 0: raise http.unacceptable("Chat messages must contain some text") chat = {"type":"chat", "text":text, "game":game_id, "user":you.id, "name":you["name"]} # synchronize timestamps game["timestamp"] = chat["timestamp"] = make_timestamp() db[game_id] = game db.create(chat) return "OK" class GameMoveView: def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(from_space=None, to_space=None) if not (params["from_space"] and params["to_space"]): raise http.badrequest("Moves must include from_space and to_space") from_space = tag_2d(params["from_space"]) to_space = tag_2d(params["to_space"]) if not (len(from_space) == len(to_space) == 2): raise http.badrequest("Invalid space tags") # check if it's your turn player = game["order"][game["turn"] % len(game["order"])] if game["players"][player] != you.id: raise http.precondition("It's not your turn") board = game["board"] attacking_piece = game["board"][from_space[0]][from_space[1]] if attacking_piece == None: raise http.forbidden("No piece to move from %s" % params["from_space"]) if attacking_piece["player"] != player: raise http.forbidden("It's not %s's turn" % attacking_piece["player"]) if not valid_move(attacking_piece["kind"], from_space, to_space): raise http.forbidden("You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"])) defending_piece = game["board"][to_space[0]][to_space[1]] if defending_piece != None: if attacking_piece["player"] == defending_piece["player"]: raise http.forbidden("You can't attack yourself") if not battle(attacking_piece["kind"], defending_piece["kind"]): raise http.forbidden("You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"])) # actually move the piece game["board"][from_space[0]][from_space[1]] = None game["board"][to_space[0]][to_space[1]] = attacking_piece # advance the turn game["turn"] += 1 # trigger an event move = {"type":"move", "game":game_id, "user":you.id, "name":you["name"], "from_space":params["from_space"], "to_space":params["to_space"]} # update timestamps just before saving game["timestamp"] = move["timestamp"] = timestamp = make_timestamp() db[game_id] = game move_id = db.create(move) return timestamp class SettingsView: def GET(self): return render("settings", you=require_you()) def POST(self): you = require_you() params = web.input(name='') - unique = True name = params['name'] if name and name != you.get('name',None): from helper import slugify slug = slugify(name) for row in dbview.users(db, startkey=slug, endkey=slug): if slug == row.key: unique = False break if unique: you['name'] = name you['slug'] = slug elif not name and 'name' in you: # blanking your name makes you anonymous, and makes your page inaccessible del you['name'] del you['slug'] db[you.id] = you if unique: web.redirect('/') else: return render('settings', errors="Sorry, that name's taken!", you=you) urls = ( '/', IndexView, '/login', web.openid.host, '/settings', SettingsView, '/users/(.*)', UserView, #'/chat', Chat, '/games/(.*)/events/(.*)', GameEventsView, '/games/(.*)/moves', GameMoveView, '/games/(.*)/chat', GameChatView, '/games/(.*)', GameView, '/games', GamesView, ) application = web.application(urls, locals()) type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} def tag_2d(tag): return [int(x) for x in tag.split('-')] def battle(attacker, defender): if attacker == "wizard": return False if defender == "wizard": return True attacker_type = attacker[:-1] defender_type = defender[:-1] if type_advantages[attacker_type] == defender_type: return True if type_advantages[defender_type] == attacker_type: return False attacker_level = int(attacker[-1]) defender_level = int(defender[-1]) if attacker_level > defender_level: return True return False def valid_move(kind, from_space, to_space): if abs(from_space[0] - to_space[0]) + abs(from_space[1] - to_space[1]) == 1: return True # only moved one space elif (kind == "wizard") and (abs(from_space[0] - to_space[0]) == 1) and (abs(from_space[1] - to_space[1]) == 1): return True # moved one space on each axis
nickretallack/elemental-chess-web
00899e845f8e66ae1006fd126622e0635d67667c
trying to remove race conditions
diff --git a/static/game.js b/static/game.js index 65056d9..27dfeff 100644 --- a/static/game.js +++ b/static/game.js @@ -1,164 +1,168 @@ $(document).ready(function(){ function find_targets(piece){ var orthogonals = [[0,1],[0,-1],[1,0],[-1,0]] var diagonals = [[-1,-1],[-1,+1],[+1,-1],[+1,+1]] var strengths = {water:'fire', fire:'plant', plant:'water'} // Find legal spaces to move to var kind = piece.attr('data_kind') var movements = orthogonals if(kind == "wizard") movements = orthogonals.concat(diagonals) var space = piece.parents('.space:first') var location = space.attr("data_location").split('-') filter = $(movements).map(function(){ return "[data_location="+(parseInt(location[0])+this[0])+"-"+(parseInt(location[1])+this[1])+"]" }).get().join(',') var neighbors = $('.space').filter(filter) // blacklist ones with disagreeable pieces on them var level = kind.slice(kind.length-1,kind.length) var type = kind.slice(0, kind.length-1) var player = piece.attr('data_player') var targets = neighbors.filter(function(){ var piece = $(this).children('.piece') if(!piece.length) return true // blank spaces are always legal if(piece && kind == 'wizard') return false // wizards can't attack var target_player = piece.attr('data_player') if(player == target_player) return false // can't attack yourself var target_kind = piece.attr('data_kind') var target_level = target_kind.slice(target_kind.length-1,target_kind.length) var target_type = target_kind.slice(0, target_kind.length-1) if(strengths[type] == target_type) return true if(strengths[target_type] == type) return false if(type == target_type && level > target_level) return true // same type fights by level return false }) return targets } // Moving Pieces var dragging = false var sent_events = {} function update_dragging(){ $(".piece").draggable("destroy") var player = turn_order[turn % turn_order.length] if($.inArray(player,your_players) == -1) return // no dragging other people's stuff $(".piece."+player+"-player").draggable({helper:'clone', scroll:true, start:function(event,ui){ dragging = true $(this).addClass('dragging') }, stop:function(event,ui){ dragging = false $('.highlight').removeClass('highlight') $(this).removeClass('dragging') } }) } update_dragging() $(".space").droppable({accept:".piece", drop:function(event,ui){ piece = ui.draggable from_space = piece.parents(".space:first") to_space = $(this) // check if it's a legal move before we send it if($.inArray(this,find_targets(piece)) == -1) return from_space_tag = from_space.attr("data_location") to_space_tag = to_space.attr("data_location") data = {from_space:from_space_tag, to_space:to_space_tag} $.ajax({type:"POST", url:"/games/"+game_id+"/moves", data:data, success:function(response){ $('#status').text('') sent_events[response] = true move_message("You move", piece.attr('data_kind'), from_space_tag, to_space_tag) }, error:function(response){ $('#status').text(response.responseText) }}) // since we want to be responsive, lets just move the thing right now. to_space.children(".piece").remove() from_space.children(".piece").appendTo(to_space) // and advance the turn ourselves turn += 1 update_dragging() }}) // hilighting moves $(".piece").hover(function(){ var player = turn_order[turn % turn_order.length] if($.inArray(player,your_players) == -1) return // no dragging other people's stuff if($(this).attr('data_player') != player) return if(!dragging) find_targets($(this)).addClass('highlight') }, function(){ if(!dragging) $('.highlight').removeClass('highlight') }) // Getting Game Events var min_event_period = 1000 var event_period = min_event_period var event_check_timer var last_interaction = new Date().getTime() function move_message(user, piece, from, to){ $('#messages').prepend("<p>"+user+" "+piece+" from "+from+" to "+to+"</p>") } + var checking_events_lock = false function checkEvents(){ + checking_events_lock = true var miliseconds_idle = new Date().getTime() - last_interaction event_period = min_event_period + miliseconds_idle*miliseconds_idle / 1000000.0 - + //console.debug(event_check_timer) $.getJSON('/games/'+game_id+'/events/'+timestamp, function(response){ if(response.timestamp) timestamp = response.timestamp if(response.events){ $.each(response.events ,function(){ if(sent_events[this.timestamp]){ // don't apply events you sent yourself delete sent_events[this.timestamp] } else if(this.type == "move"){ var from_space = $("[data_location="+this.from_space+"]") var to_space = $("[data_location="+this.to_space+"]") var piece = from_space.children(".piece") to_space.children(".piece").remove() piece.prependTo(to_space) turn += 1 update_dragging() move_message(this.name+" moves", piece.attr('data_kind'), this.from_space, this.to_space) } else if(this.type == "chat"){ $('#messages').prepend("<p>"+this.name+": "+this.text+"</p>" ) } }) } event_check_timer = setTimeout(checkEvents, event_period) + checking_events_lock = false }) } function nudge(){ + if (checking_events_lock) return var miliseconds_idle = new Date().getTime() - last_interaction last_interaction = new Date().getTime() if(miliseconds_idle > 5000){ clearTimeout(event_check_timer) checkEvents() } } $(document).mousemove(nudge) $(document).keypress(nudge) event_check_timer = setTimeout(checkEvents, event_period) // Sending Game Chat $('#chat').submit(function(event){ event.preventDefault() var field = $('#chat [name=text]') if(field.val() == '') return data = $(this).serialize() field.val('') $.post('/games/'+game_id+'/chat',data) }) })
nickretallack/elemental-chess-web
171033520618de5d527df7a026cbe55e40d31cb3
json for old python
diff --git a/helper.py b/helper.py index f52520d..b83ed73 100644 --- a/helper.py +++ b/helper.py @@ -1,73 +1,77 @@ import web from database import db import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), line_statement_prefix="#") def user_name(user): if 'name' in user: return user['name'] else: return "anonymous" def hex_color(seed,invert=False): import random random.seed(seed) color = random.randint(0,16**6) if invert: color = 16**6 - color return "%X" % color env.filters['len'] = len env.filters['user_name'] = user_name env.filters['hex_color'] = hex_color -import json + +try: + import json +except ImportError: + import simplejson as json env.filters['json'] = json.dumps def render(template,**args): return env.get_template(template+'.html').render(**args) def get_you(): openid = web.openid.status() if openid: key = "user-%s" % openid if key in db: return db[key] else: you = {'type':'user', 'openids':[openid], "name":"no-name"} db[key] = you return you def get_game(game_id): if game_id not in db: raise web.notfound() game = db[game_id] if game['type'] != "game": raise web.notfound() return game def require_you(): you = get_you() if not you: raise web.HTTPError("401 unauthorized", {}, "You must be logged in") return you def make_timestamp(): from datetime import datetime return datetime.now().isoformat() # Modified slugging routines originally stolen from patches to django def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata import re #value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) diff --git a/views.py b/views.py index 1b9bc77..b887b5c 100644 --- a/views.py +++ b/views.py @@ -1,233 +1,236 @@ import web from database import db import dbview #from couch_util import couch_request COUCH_MAX = u"\u9999" from helper import render, get_you, get_game, require_you, make_timestamp from dbview import * import http class Index: def GET(self): you = get_you() games = dbview.games(db).rows users = [row.value for row in dbview.users(db)] return render("index", games=games, users=users, you=get_you()) class User: def GET(self, slug): possible_users = dbview.users(db, startkey=slug, endkey=slug).rows if not len(possible_users): return web.notfound() user = possible_users[0].value return render("user", user=user, you=get_you()) class Game: def GET(self, game_id): game = get_game(game_id) chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True) you = get_you() players = dict([(color, db[player_id]) for (color,player_id) in game["players"].iteritems()]) if you: your_players = [key for (key,value) in game["players"].iteritems() if value == you.id] else: your_players = [] return render('game',game=game, you=get_you(), chats=chats, your_players=your_players, players=players) class GameEvents: def GET(self, game_id, timestamp): - import json + try: + import json + except ImportError: + import simplejson as json events = dbview.events(db, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows if not len(events): # no events have happened in this game yet, most likely return json.dumps({"timestamp":timestamp}) newest_timestamp = events[-1].key[1] # highly dependent on query new_events = [event.value for event in events if event.key[1] != timestamp] if not len(new_events): return "{}" return json.dumps({"timestamp":newest_timestamp, "events":new_events}) class Games: def POST(self): you = require_you() from setup_board import board game = {"type":"game", "board":board, "timestamp":make_timestamp(), "turn":0, "players":{"red":you.id,"blue":you.id}, "order":["red","blue"]} game_id = db.create(game) web.seeother("/games/%s" % game_id) class GameChat: #def GET(self, game_id): # could just give us the chats, for debug purposes def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(text='') text = params["text"] if len(text) == 0: raise http.unacceptable("Chat messages must contain some text") chat = {"type":"chat", "text":text, "game":game_id, "user":you.id, "name":you["name"]} # synchronize timestamps game["timestamp"] = chat["timestamp"] = make_timestamp() db[game_id] = game db.create(chat) return "OK" class GameMove: def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(from_space=None, to_space=None) if not (params["from_space"] and params["to_space"]): raise http.badrequest("Moves must include from_space and to_space") from_space = tag_2d(params["from_space"]) to_space = tag_2d(params["to_space"]) if not (len(from_space) == len(to_space) == 2): raise http.badrequest("Invalid space tags") # check if it's your turn player = game["order"][game["turn"] % len(game["order"])] if game["players"][player] != you.id: raise http.precondition("It's not your turn") board = game["board"] attacking_piece = game["board"][from_space[0]][from_space[1]] if attacking_piece == None: raise http.forbidden("No piece to move from %s" % params["from_space"]) if attacking_piece["player"] != player: raise http.forbidden("It's not %s's turn" % attacking_piece["player"]) if not valid_move(attacking_piece["kind"], from_space, to_space): raise http.forbidden("You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"])) defending_piece = game["board"][to_space[0]][to_space[1]] if defending_piece != None: if attacking_piece["player"] == defending_piece["player"]: raise http.forbidden("You can't attack yourself") if not battle(attacking_piece["kind"], defending_piece["kind"]): raise http.forbidden("You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"])) # actually move the piece game["board"][from_space[0]][from_space[1]] = None game["board"][to_space[0]][to_space[1]] = attacking_piece # advance the turn game["turn"] += 1 # trigger an event move = {"type":"move", "game":game_id, "user":you.id, "name":you["name"], "from_space":params["from_space"], "to_space":params["to_space"]} # update timestamps just before saving game["timestamp"] = move["timestamp"] = timestamp = make_timestamp() db[game_id] = game move_id = db.create(move) return timestamp class Settings: def GET(self): return render("settings", you=require_you()) def POST(self): you = require_you() params = web.input(name='') unique = True name = params['name'] if name and name != you.get('name',None): from helper import slugify slug = slugify(name) for row in dbview.users(db): if slug == row.key: unique = False break if unique: you['name'] = name you['slug'] = slug elif not name and 'name' in you: # blanking your name makes you anonymous, and makes your page inaccessible del you['name'] del you['slug'] db[you.id] = you if unique: web.redirect('/') else: return render('settings', errors="Sorry, that name's taken!", you=you) urls = ( '/', Index, '/login', web.openid.host, '/settings', Settings, '/users/(.*)', User, #'/chat', Chat, '/games/(.*)/events/(.*)', GameEvents, '/games/(.*)/moves', GameMove, '/games/(.*)/chat', GameChat, '/games/(.*)', Game, '/games', Games, ) application = web.application(urls, locals()) type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} def tag_2d(tag): return [int(x) for x in tag.split('-')] def battle(attacker, defender): if attacker == "wizard": return False if defender == "wizard": return True attacker_type = attacker[:-1] defender_type = defender[:-1] if type_advantages[attacker_type] == defender_type: return True if type_advantages[defender_type] == attacker_type: return False attacker_level = int(attacker[-1]) defender_level = int(defender[-1]) if attacker_level > defender_level: return True return False def valid_move(kind, from_space, to_space): if abs(from_space[0] - to_space[0]) + abs(from_space[1] - to_space[1]) == 1: return True # only moved one space elif (kind == "wizard") and (abs(from_space[0] - to_space[0]) == 1) and (abs(from_space[1] - to_space[1]) == 1): return True # moved one space on each axis
nickretallack/elemental-chess-web
2a47826482c423cd2b37c2bb2cb1ad617e17355e
random names, player names on games, caching instances and such
diff --git a/database.py b/database.py index 9543b80..aed9f92 100644 --- a/database.py +++ b/database.py @@ -1,15 +1,20 @@ from settings import db_server, db_name import couchdb +import socket server = couchdb.Server(db_server) -if db_name not in server: - server.create(db_name) -db = server[db_name] +try: + if db_name not in server: + server.create(db_name) + db = server[db_name] +except socket.error: + print "Make sure CouchDB is running" + exit() """ def view_sync(): from dbviews import views from couchdb.design import ViewDefinition as View View.sync_many(db,views,remove_missing=True) """ diff --git a/discussion.txt b/discussion.txt index 1a7dc97..a7e572d 100644 --- a/discussion.txt +++ b/discussion.txt @@ -1,102 +1,113 @@ +To display player names on a game: well, the player's name isn't really part of the game object, so it requires an extra query. I guess we could put those queries in the list comprehension though. + +Maybe we should break out the game logic into a game class. I guess we could handle the object caching after we have defined that, as object caching is kind of premature optimization right now + +Okay, this implementation is a little batshit. It would be much more minimal to just make an individual static method for it. + + + + Todo: - revert illegal moves? - make it look nice - random unique user names - randomize game colors with hsl + revert illegal moves + factor game logic into game class + random unique user names + make it look nice + player names in a game. + randomize game colors with hsl - check that you can create games properly - check game logic on client side - how do I avoid sending the same event back to you? - maintain a list of sent events responsive client-side handling of moving pieces and stuff - detect mouse and keyboard activity, and throttle down polling if there is none for a while - users list so you can start a game with them - hash-colored games - settings page to set your name - Wishlist: unify user system with other projects? stretchy board with jquery resize filter droppables as well as draggables and set revert:true Board representation: It might be easier to represent the board as a hash of string-named spaces. This works for more kinds of games anyway. It's up to the game logic to decide if something on "space_foo" can move to "space_bar", either by deconstructing it into components or maintaining a border list or whatever. Then again, I'd have to remember the board's dimensions somewhere if I wanted to conveniently lay out a table for it. --- Strategy for tolerating multiple events in the same microsecond: 1) fetch all events starting at the requested microsecond 2) construct a new array that skims out all events equal to the requested microsecond 3) if the new array has length zero or one less than the old array, all is well. Return normally. 4) if the new array has length 2 or more less than the old array, return the old array instead 5) on the javascript side, only apply events at our same microsecond that we didn't personally send wait no, this is much simpler: just don't send events back to the client who broadcasted them if they have the same microsecond as requested. Hm, but how do we know which client broadcast them... Perhaps we should use their user id... Yeah, that makes sense. Then we can tell who was controlling a player when they caused an event :D. Nah this is all crap. I think we should just have the client check if they're receiving an event they already know about...? urgh no. Ugh, I have to do something to avoid always sending your own events back to yourself... db formats: (type=first word) move(user(id), from(space_tag), to(space_tag)) chat(user(id), text(string), game(id)) game(board(structure), players(color:id), turn(color)) --- Names: generate random silly names and stick them in the session for now. I guess you could change your name pretty easy by posting it to a url, but then we'd have to check that other people aren't using it... Should we represent players in the database? Do we need to know who's in a game? Lets see. Hm. Well we need to know who's allowed to post a new move, so yes. Maybe I should save the avante-guarde simplicity for later. Okay. Database stuff. Game: players, pieces(player_id, kind_tag, space_tag) hm, maybe you have to be logged in to play, but not to watch. Page setup: index: new game form, list of public games (private/public. Invite users?) Hmm, what about chatting directly at people. I guess we could have chat events that are to someone...(private) game/id: in a game. Hmm. How can we make a humane id for this. is.gd style? but what if people start a game at the same time... ah fuckit, we can use guids for now okay, setting up a game. lets use some old code to generate the board... nah fuckit, storing game data as pieces instead of the board just may be too much work. We have to render the board when you refresh anyway. ---------- okay! The event system would be much more efficient if we did not duplicate records, but instead used timestamps. When a player receives a page from the server, it includes a timestamp in a javascript variable. When they ask for events, they pass that timestamp in. The server finds events that have happened since that timestamp but not equal to it. It then passes them back with the timestamp of the latest one. Nothing is mutated on the server side for this reading action. Including a timestamp in the page: we better make sure there's no caching going on! Perhaps keep a record of the last timestamp you've sent and see if you ever regress. (oh god what about multiple windows... Well, they're safer with the timestamp approach at least. Now we know that if we regress on timestamps, it's likely either a caching problem OR multiple game windows.) Okay, events. Lets try out chat events first. Post text to the chat url. what happens if two events happen at the same microsecond? I guess you'd miss one. Hm. I suppose we could return events that even have a timestamp equal to our last, and then check against things we already know about? -old- We shall have a glorious event system! When a user moves a piece, the board in the system is updated And, an event is created for each player detailing the move When a player checks for new events, all new events are sent to them And, (if the handshake succeeds?) they are deleted When a player loads the board view, all their incoming move events are deleted Should we use timestamps in this event system? They have potential to screw things up, so, perhaps only for show. \ No newline at end of file diff --git a/game_model.py b/game_model.py new file mode 100644 index 0000000..7396dce --- /dev/null +++ b/game_model.py @@ -0,0 +1,169 @@ +from database import db +import web # for exceptions. Yeah I'm being lazy. I know this couples badly +import dbview + +class User: + SlugCache = {} + IDCache = {} + + @classmethod + def all(cls): + instances = [] + for record in dbview.users(db).rows: + instance = User(record) + cls.IDCache[instance.id] = cls.SlugCache[instance.slug] = instance + instances.append(instance) + return instances + + @classmethod + def get(cls, slug=None, id=None): + if id: + if not id in db: + raise web.notfound() + record = db[id] + if record['type'] != "user": + raise web.notfound() + if slug: + records = dbview.users(db, startkey=slug, endkey=slug).rows + if not len(records): + raise web.notfound() + record = records[0] + + instance = User(record) + cls.SlugCache[instance.slug] = cls.IDCache[instance.id] = instance + return instance + + def __init__(self, params): + #print params + if 'value' in params: + self.name = params['value']['name'] + self.slug = params['key'] + self.id = params['id'] + else: + self.name = params['name'] + self.slug = params['slug'] + self.id = params['_id'] + + +class Game: + IDCache = {} + + def __init__(self, params): + if 'value' in params: + self.player_ids = params["value"]["players"] + #self.order = params["value"]["order"] + #self.timestamp = params[""] + self.id = params["id"] + else: + self.player_ids = params['players'] + self.order = params['order'] + self.turn = params['turn'] + self.timestamp = params['timestamp'] + self.board = params['board'] + self.id = params['_id'] + + self._players = None + + def get_players(self): + if not self._players: + #print self.player_ids + self._players = dict([(color, User.get(id=id)) for (color,id) in self.player_ids.items()]) + return self._players + + players = property(get_players) + + @classmethod + def get(cls, id=None): + if id: + if not id in db: + raise web.notfound() + record = db[id] + if record['type'] != "game": + raise web.notfound() + + instance = Game(record) + cls.IDCache[instance.id] = instance + return instance + + @classmethod + def all(cls): + instances = [] + for record in dbview.games(db).rows: + instance = Game(record) + cls.IDCache[instance.id] = instance + instances.append(instance) + return instances + + + +if __name__ == "__main__": + #print User.get(slug="kalufurret").name + #print Game.all()[0].players + #print User.all() + game = Game.get(id="e4725af328f248c6b32cc52d3cb932c1") + for (color,player) in game.players.items(): + print player.id + +# import web +# from database import db +# import dbview +# +# class Indirect +# class __impl: +# pass +# +# __cached = {} +# def __init__(self, args): +# id = args.id +# if id in __cached: +# self.__instance = __cached[id] +# else: +# self.__instance = __cached[id] = __impl(args) +# self.__record = db[id] +# +# def __getattr__(self, attr): +# return getattr(self.__instance, attr) +# +# def __setattr__(self, attr, value): +# return setattr(self.__instance, attr, value) +# +# class User(Indirect): +# class __impl: +# def __init__(self, args): +# pass +# +# def name(self): +# self.__record["name"] +# +# class Game: +# class __impl: +# def __init__(self, args): +# self.id = args.id +# if "value" in args: +# # it was queried from a view +# self.player_ids = args["value"]["players"] +# else: +# # we have the whole game object +# self.player_ids = args["players"] +# self.board = args["board"] +# self.turn = args["turn"] +# self.order = args["order"] +# +# def players(): +# +# #[{"name": db[player_id].name, "color":color} for (color, player_id) in self.player_ids] +# +# @classmethod +# def all(cls): +# return memo ||= [Game(game) for game in dbview.games(db)] +# +# @classmethod +# def get(cls, game_id): +# if game_id not in db: +# raise web.notfound() +# +# game = db[game_id] +# if game['type'] != "game": +# raise web.notfound() +# +# return Game(game) diff --git a/helper.py b/helper.py index 97fbd8d..2d43b18 100644 --- a/helper.py +++ b/helper.py @@ -1,82 +1,101 @@ import web from database import db import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), line_statement_prefix="#") def user_name(user): if 'name' in user: return user['name'] else: return "anonymous" def hex_color(seed,invert=False): import random import md5 from hsl import HSL_2_RGB digest = md5.new(seed).digest() print digest random.seed(digest) color = HSL_2_RGB(random.random(), 1, random.uniform(.2,.8)) print color hex = "%02X%02X%02X" % color print hex return hex # color = random.randint(0,16**6) # if invert: # color = 16**6 - color # return "%X" % color env.filters['len'] = len env.filters['user_name'] = user_name env.filters['hex_color'] = hex_color import json env.filters['json'] = json.dumps def render(template,**args): return env.get_template(template+'.html').render(**args) +import dbview + def get_you(): openid = web.openid.status() if openid: key = "user-%s" % openid if key in db: return db[key] else: - you = {'type':'user', 'openids':[openid], "name":"no-name"} + from random_name import random_name + from time import time + while True: + unique = True + name = random_name("%s-%d" % (openid,time())) + slug = slugify(name) + for row in dbview.users(db, startkey=slug, endkey=slug): + if slug == row.key: + unique = False + break + + if unique: + break + + you = {'type':'user', 'openids':[openid], "name":name, "slug":slug} db[key] = you return you +#def unique_random_name(openid): + + def get_game(game_id): if game_id not in db: raise web.notfound() game = db[game_id] if game['type'] != "game": raise web.notfound() return game def require_you(): you = get_you() if not you: raise web.HTTPError("401 unauthorized", {}, "You must be logged in") return you def make_timestamp(): from datetime import datetime return datetime.now().isoformat() # Modified slugging routines originally stolen from patches to django def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata import re #value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) diff --git a/random_name.py b/random_name.py new file mode 100644 index 0000000..d88f1ce --- /dev/null +++ b/random_name.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python + +"""Produces a random anonymous name. + +This is a port of the make_anonymous function in the Wakaba imageboard software +and uses the same names. + +You can either import this as a module, or simply run it to print a single name +to stdout. +""" + +import random +from time import time + +def random_name(seed=None): + """Returns a random name. + + The only parameter is an optional seed to use. + """ + + if not seed: + seed = time() + random.seed(seed) + + name = "%s %s" % (_rand_first_name(), _rand_surname()) + + # Be polite and reseed if this should be used as a module + random.seed() + + return name + +def _rand_first_name(): + return random.choice( [ + 'Albert', 'Alice', 'Angus', 'Archie', 'Augustus', 'Barnaby', 'Basil', + 'Beatrice', 'Betsy', 'Caroline', 'Cedric', 'Charles', 'Charlotte', + 'Clara', 'Cornelius', 'Cyril', 'David', 'Doris', 'Ebenezer', + 'Edward', 'Edwin', 'Eliza', 'Emma', 'Ernest', 'Esther', 'Eugene', + 'Fanny', 'Frederick', 'George', 'Graham', 'Hamilton', 'Hannah', + 'Hedda', 'Henry', 'Hugh', 'Ian', 'Isabella', 'Jack', 'James', + 'Jarvis', 'Jenny', 'John', 'Lillian', 'Lydia', 'Martha', 'Martin', + 'Matilda', 'Molly', 'Nathaniel', 'Nell', 'Nicholas', 'Nigel', + 'Oliver', 'Phineas', 'Phoebe', 'Phyllis', 'Polly', 'Priscilla', + 'Rebecca', 'Reuben', 'Samuel', 'Sidney', 'Simon', 'Sophie', + 'Thomas', 'Walter', 'Wesley', 'William', + ] ) + +def _rand_surname(): + simple = [ + _rand_surname_prefix, _rand_surname_suffix + ] + complex_prefix = [ + _rand_surname_start, _rand_surname_vowel, _rand_surname_prefix_end, + _rand_surname_suffix, + ] + complex_both = [ + _rand_surname_start, _rand_surname_vowel, _rand_surname_prefix_end, + _rand_surname_consonant, _rand_surname_vowel, _rand_surname_suffix_end, + ] + + functions = random.choice( [ + simple, simple, + complex_prefix, complex_prefix, complex_prefix, + complex_both, complex_both, complex_both, + ] ) + + return ''.join([ func() for func in functions ]) + +def _rand_surname_prefix(): + return random.choice( [ + 'Small', 'Snod', 'Bard', 'Billing', 'Black', 'Shake', 'Tilling', + 'Good', 'Worthing', 'Blythe', 'Green', 'Duck', 'Pitt', 'Grand', + 'Brook', 'Blather', 'Bun', 'Buzz', 'Clay', 'Fan', 'Dart', 'Grim', + 'Honey', 'Light', 'Murd', 'Nickle', 'Pick', 'Pock', 'Trot', 'Toot', + 'Turvey', + ] ) + +def _rand_surname_suffix(): + return random.choice( [ + 'shaw', 'man', 'stone', 'son', 'ham', 'gold', 'banks', 'foot', 'worth', + 'way', 'hall', 'dock', 'ford', 'well', 'bury', 'stock', 'field', + 'lock', 'dale', 'water', 'hood', 'ridge', 'ville', 'spear', 'forth', + 'will' + ] ) + +def _rand_surname_vowel(): + return random.choice( ['a', 'e', 'i', 'o', 'u'] ) + +def _rand_surname_start(): + return random.choice( [ + 'B', 'B', 'C', 'D', 'D', 'F', 'F', 'G', 'G', 'H', 'H', 'M', 'N', 'P', + 'P', 'S', 'S', 'W', 'Ch', 'Br', 'Cr', 'Dr', 'Bl', 'Cl', 'S', + ] ) + +def _rand_surname_consonant(): + return random.choice( [ + 'b', 'd', 'f', 'h', 'k', 'l', 'm', 'n', 'p', 's', 't', 'w', 'ch', 'st', + ] ) + +def _rand_surname_prefix_end(): + return random.choice( [ + 'ving', 'zzle', 'ndle', 'ddle', 'ller', 'rring', 'tting', 'nning', + 'ssle', 'mmer', 'bber', 'bble', 'nger', 'nner', 'sh', 'ffing', 'nder', + 'pper', 'mmle', 'lly', 'bling', 'nkin', 'dge', 'ckle', 'ggle', 'mble', + 'ckle', 'rry', + ] ) + +def _rand_surname_suffix_end(): + return random.choice( [ + 't', 'ck', 'tch', 'd', 'g', 'n', 't', 't', 'ck', 'tch', 'dge', 're', + 'rk', 'dge', 're', 'ne', 'dging', + ] ) + + +if __name__ == '__main__': + print random_name() diff --git a/static/style.css b/static/style.css index 7042b8b..20cdd42 100644 --- a/static/style.css +++ b/static/style.css @@ -1,18 +1,20 @@ table {border-collapse:collapse; } td {vertical-align:top;} .space {background-color:lightgrey; border:1px solid white; padding:0;} .space, .piece {width:80px; height:80px;} .piece img {max-width:80px; max-height:80px; display:block;} #logout-form, #login-form {display:inline;} .red-player {background-color:red;} .blue-player {background-color:blue;} .highlight {background-color:yellow !important;} .highlight .piece {background-color:orange;} .dragging {opacity:0.5;} /*input {width:80px; height:80px; background-color:green;}*/ h2 {background-color:#00808d; color:white; margin:1ex 0 !important; text-align:center; padding-top:.2ex;} + +p{ margin-left:5ex; margin-right:5ex;} \ No newline at end of file diff --git a/templates/base.html b/templates/base.html index 55985d9..3cf26b7 100644 --- a/templates/base.html +++ b/templates/base.html @@ -1,27 +1,28 @@ <html> <head> <title>Elemental Chess</title> <script type="text/javascript" src="/static/jquery-1.2.6.js"></script> <script type="text/javascript" src="/static/jquery.ui.all.js"></script> <link rel="stylesheet" type="text/css" href="/static/reset.css"> <link rel="stylesheet" type="text/css" href="/static/style.css"> # block head # endblock </head> <body> <div id="header"> <a href="/">Home</a> | # if you logged in as {{you|user_name}} -<a href="/settings" id="settings">settings</a><form method="post" action="/login" id="logout-form"><input type="hidden" name="action" value="logout" /><input type="submit" value="Log Out" id="logout"></form> +| <a href="/settings" id="settings">settings</a> +| <form method="post" action="/login" id="logout-form"><input type="hidden" name="action" value="logout" /><input type="submit" value="Log Out" id="logout"></form> # else <form method="post" action="/login" id="login-form"><input type="hidden" name="return_to" value="/"><input type="text" name="openid" id="openid_identifier"/><input type="submit" id="login" value="Log In"></form> <script type="text/javascript" id="__openidselector" src="https://www.idselector.com/selector/ddb6106634870c12617f13ab740aa8f24b723b56" charset="utf-8"></script> # endif </div> # block body # endblock </body> </html> \ No newline at end of file diff --git a/templates/game.html b/templates/game.html index f6f2bf2..5a3e5cd 100644 --- a/templates/game.html +++ b/templates/game.html @@ -1,37 +1,37 @@ # extends 'base.html' # block head <script type="text/javascript"> var game_id = "{{game.id}}" var timestamp = "{{game.timestamp}}" var turn_order = {{game.order|json}} var turn = {{game.turn}} var your_players = {{your_players|json}} </script> <script type="text/javascript" src="/static/game.js"></script> # endblock # block body <h3 id="status"></h3> -Red: {{players.red.name}} +Red: {{game.players.red.name}} <table> # for x in range(game.board|len) <tr> # for y in range(game.board[x]|len) <td class="space" data_location="{{x}}-{{y}}"> # if game.board[x][y] # set piece = game.board[x][y] <div class="piece {{piece.player}}-player {{piece.kind}}-kind" data_player="{{piece.player}}" data_kind="{{piece.kind}}"> <img src="/static/pieces/{{game.board[x][y].kind}}.png"> </div> # endif </td> # endfor </tr> # endfor </table> -Blue: {{players.blue.name}} +Blue: {{game.players.blue.name}} # include "chat.html" # endblock \ No newline at end of file diff --git a/templates/index.html b/templates/index.html index 2c355f4..c299c61 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,44 +1,53 @@ # extends 'base.html' # block head <script type="text/javascript"> var timestamp = "{{timestamp}}" /* $(document).ready(function(){ console.debug("Going") $('#chat').submit(function(event){ event.preventDefault() data = $(event.target).serialize() $.post('/chat',data) }) event_period = 1000 function checkEvents(){ data = {timestamp:timestamp,stuff:{things:"hey"}} $.getJSON('/chat', data, function(response){ timestamp = response.timestamp $.each(response.chats,function(){ $('#messages').prepend("<p>New Message: "+this.text+"</p>" ) }) console.debug(response) setTimeout(checkEvents, event_period) }) } setTimeout(checkEvents, event_period) })*/ </script> # endblock # block body +<h2>Elemental Chess</h2> +<p>This website allows you to play a minimal version of my original board game Elemental Chess over the internet + (rules page coming soon). You can log in with <a href="http://openid.net/">OpenID</a>, + challenge users to a game, or watch the games in progress. If you spot anything broken, email me at [the domain of this website]@gmail.com</p> + <h2>Users</h2> # for user in users <a href="/users/{{user.slug}}">{{user.name}}</a> # endfor <h2>Games</h2> # for game in games -<a style="background-color:#{{game.id|hex_color}}; color:#{{game.id|hex_color(-1)}}" href="/games/{{game.id}}">{{game.id}}</a> +<a style="background-color:#{{game.id|hex_color}}; display:inline-block; margin:.5ex; padding:1ex" href="/games/{{game.id}}"> +# for (color,player) in game.players.items() +<span style="color:{{color}}; font-weight:bold; display:block">{{player.name}}</span> +# endfor +</a> # endfor # endblock \ No newline at end of file diff --git a/views.py b/views.py index bee0f61..fae1712 100644 --- a/views.py +++ b/views.py @@ -1,244 +1,242 @@ import web from database import db import dbview #from couch_util import couch_request COUCH_MAX = u"\u9999" from helper import render, get_you, get_game, require_you, make_timestamp from dbview import * import http +from game_model import User, Game - -class Index: +class IndexView: def GET(self): you = get_you() - games = dbview.games(db).rows - users = [row.value for row in dbview.users(db)] + games = Game.all() + users = User.all() return render("index", games=games, users=users, you=get_you()) - -class User: +class UserView: def GET(self, slug): - possible_users = dbview.users(db, startkey=slug, endkey=slug).rows - if not len(possible_users): - return web.notfound() - user = possible_users[0].value + user = User.get(slug=slug) return render("user", user=user, you=get_you()) - -class Game: +class GameView: def GET(self, game_id): - game = get_game(game_id) + game = Game.get(game_id) chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True) you = get_you() - players = dict([(color, db[player_id]) for (color,player_id) in game["players"].iteritems()]) + #players = dict([(color, db[player_id]) for (color,player_id) in game["players"].iteritems()]) + #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if you: - your_players = [key for (key,value) in game["players"].iteritems() if value == you.id] + your_players = [color for (color,player) in game.players.items() if player.id == you.id] + #print "Your Players: %s" % game.players.items()[0].id else: + print "NOTHING" your_players = [] - return render('game',game=game, you=get_you(), chats=chats, your_players=your_players, players=players) + return render('game',game=game, you=get_you(), chats=chats, your_players=your_players) -class GameEvents: +class GameEventsView: def GET(self, game_id, timestamp): import json events = dbview.events(db, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows if not len(events): # no events have happened in this game yet, most likely return json.dumps({"timestamp":timestamp}) newest_timestamp = events[-1].key[1] # highly dependent on query new_events = [event.value for event in events if event.key[1] != timestamp] if not len(new_events): return "{}" return json.dumps({"timestamp":newest_timestamp, "events":new_events}) -class Games: +class GamesView: def POST(self): you = require_you() params = web.input() if not params["user"]: return web.notfound() user = dbview.users(db, startkey=params['user'], endkey=params['user']).rows if not len(user): return web.notfound() else: user = user[0] from setup_board import board game = {"type":"game", "board":board, "timestamp":make_timestamp(), "turn":0, "players":{"red":you.id,"blue":user.id}, "order":["red","blue"]} game_id = db.create(game) web.seeother("/games/%s" % game_id) -class GameChat: +class GameChatView: #def GET(self, game_id): # could just give us the chats, for debug purposes def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(text='') text = params["text"] if len(text) == 0: raise http.unacceptable("Chat messages must contain some text") chat = {"type":"chat", "text":text, "game":game_id, "user":you.id, "name":you["name"]} # synchronize timestamps game["timestamp"] = chat["timestamp"] = make_timestamp() db[game_id] = game db.create(chat) return "OK" -class GameMove: +class GameMoveView: def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(from_space=None, to_space=None) if not (params["from_space"] and params["to_space"]): raise http.badrequest("Moves must include from_space and to_space") from_space = tag_2d(params["from_space"]) to_space = tag_2d(params["to_space"]) if not (len(from_space) == len(to_space) == 2): raise http.badrequest("Invalid space tags") # check if it's your turn player = game["order"][game["turn"] % len(game["order"])] if game["players"][player] != you.id: raise http.precondition("It's not your turn") board = game["board"] attacking_piece = game["board"][from_space[0]][from_space[1]] if attacking_piece == None: raise http.forbidden("No piece to move from %s" % params["from_space"]) if attacking_piece["player"] != player: raise http.forbidden("It's not %s's turn" % attacking_piece["player"]) if not valid_move(attacking_piece["kind"], from_space, to_space): raise http.forbidden("You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"])) defending_piece = game["board"][to_space[0]][to_space[1]] if defending_piece != None: if attacking_piece["player"] == defending_piece["player"]: raise http.forbidden("You can't attack yourself") if not battle(attacking_piece["kind"], defending_piece["kind"]): raise http.forbidden("You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"])) # actually move the piece game["board"][from_space[0]][from_space[1]] = None game["board"][to_space[0]][to_space[1]] = attacking_piece # advance the turn game["turn"] += 1 # trigger an event move = {"type":"move", "game":game_id, "user":you.id, "name":you["name"], "from_space":params["from_space"], "to_space":params["to_space"]} # update timestamps just before saving game["timestamp"] = move["timestamp"] = timestamp = make_timestamp() db[game_id] = game move_id = db.create(move) return timestamp -class Settings: +class SettingsView: def GET(self): return render("settings", you=require_you()) def POST(self): you = require_you() params = web.input(name='') unique = True name = params['name'] if name and name != you.get('name',None): from helper import slugify slug = slugify(name) - for row in dbview.users(db): + for row in dbview.users(db, startkey=slug, endkey=slug): if slug == row.key: unique = False break if unique: you['name'] = name you['slug'] = slug elif not name and 'name' in you: # blanking your name makes you anonymous, and makes your page inaccessible del you['name'] del you['slug'] db[you.id] = you if unique: web.redirect('/') else: return render('settings', errors="Sorry, that name's taken!", you=you) urls = ( - '/', Index, + '/', IndexView, '/login', web.openid.host, - '/settings', Settings, - '/users/(.*)', User, + '/settings', SettingsView, + '/users/(.*)', UserView, #'/chat', Chat, - '/games/(.*)/events/(.*)', GameEvents, - '/games/(.*)/moves', GameMove, - '/games/(.*)/chat', GameChat, - '/games/(.*)', Game, - '/games', Games, + '/games/(.*)/events/(.*)', GameEventsView, + '/games/(.*)/moves', GameMoveView, + '/games/(.*)/chat', GameChatView, + '/games/(.*)', GameView, + '/games', GamesView, ) application = web.application(urls, locals()) type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} def tag_2d(tag): return [int(x) for x in tag.split('-')] def battle(attacker, defender): if attacker == "wizard": return False if defender == "wizard": return True attacker_type = attacker[:-1] defender_type = defender[:-1] if type_advantages[attacker_type] == defender_type: return True if type_advantages[defender_type] == attacker_type: return False attacker_level = int(attacker[-1]) defender_level = int(defender[-1]) if attacker_level > defender_level: return True return False def valid_move(kind, from_space, to_space): if abs(from_space[0] - to_space[0]) + abs(from_space[1] - to_space[1]) == 1: return True # only moved one space elif (kind == "wizard") and (abs(from_space[0] - to_space[0]) == 1) and (abs(from_space[1] - to_space[1]) == 1): return True # moved one space on each axis
nickretallack/elemental-chess-web
da3026213e535dd8f84d7c5e343fdba44c719fc9
transitioning to a more object oriented design
diff --git a/discussion.txt b/discussion.txt index 1a7dc97..7a37980 100644 --- a/discussion.txt +++ b/discussion.txt @@ -1,102 +1,104 @@ Todo: + maybe we should represent games somehow, so the view can query for extra stuff like player names... + revert illegal moves? make it look nice random unique user names randomize game colors with hsl check that you can create games properly - check game logic on client side - how do I avoid sending the same event back to you? - maintain a list of sent events responsive client-side handling of moving pieces and stuff - detect mouse and keyboard activity, and throttle down polling if there is none for a while - users list so you can start a game with them - hash-colored games - settings page to set your name - Wishlist: unify user system with other projects? stretchy board with jquery resize filter droppables as well as draggables and set revert:true Board representation: It might be easier to represent the board as a hash of string-named spaces. This works for more kinds of games anyway. It's up to the game logic to decide if something on "space_foo" can move to "space_bar", either by deconstructing it into components or maintaining a border list or whatever. Then again, I'd have to remember the board's dimensions somewhere if I wanted to conveniently lay out a table for it. --- Strategy for tolerating multiple events in the same microsecond: 1) fetch all events starting at the requested microsecond 2) construct a new array that skims out all events equal to the requested microsecond 3) if the new array has length zero or one less than the old array, all is well. Return normally. 4) if the new array has length 2 or more less than the old array, return the old array instead 5) on the javascript side, only apply events at our same microsecond that we didn't personally send wait no, this is much simpler: just don't send events back to the client who broadcasted them if they have the same microsecond as requested. Hm, but how do we know which client broadcast them... Perhaps we should use their user id... Yeah, that makes sense. Then we can tell who was controlling a player when they caused an event :D. Nah this is all crap. I think we should just have the client check if they're receiving an event they already know about...? urgh no. Ugh, I have to do something to avoid always sending your own events back to yourself... db formats: (type=first word) move(user(id), from(space_tag), to(space_tag)) chat(user(id), text(string), game(id)) game(board(structure), players(color:id), turn(color)) --- Names: generate random silly names and stick them in the session for now. I guess you could change your name pretty easy by posting it to a url, but then we'd have to check that other people aren't using it... Should we represent players in the database? Do we need to know who's in a game? Lets see. Hm. Well we need to know who's allowed to post a new move, so yes. Maybe I should save the avante-guarde simplicity for later. Okay. Database stuff. Game: players, pieces(player_id, kind_tag, space_tag) hm, maybe you have to be logged in to play, but not to watch. Page setup: index: new game form, list of public games (private/public. Invite users?) Hmm, what about chatting directly at people. I guess we could have chat events that are to someone...(private) game/id: in a game. Hmm. How can we make a humane id for this. is.gd style? but what if people start a game at the same time... ah fuckit, we can use guids for now okay, setting up a game. lets use some old code to generate the board... nah fuckit, storing game data as pieces instead of the board just may be too much work. We have to render the board when you refresh anyway. ---------- okay! The event system would be much more efficient if we did not duplicate records, but instead used timestamps. When a player receives a page from the server, it includes a timestamp in a javascript variable. When they ask for events, they pass that timestamp in. The server finds events that have happened since that timestamp but not equal to it. It then passes them back with the timestamp of the latest one. Nothing is mutated on the server side for this reading action. Including a timestamp in the page: we better make sure there's no caching going on! Perhaps keep a record of the last timestamp you've sent and see if you ever regress. (oh god what about multiple windows... Well, they're safer with the timestamp approach at least. Now we know that if we regress on timestamps, it's likely either a caching problem OR multiple game windows.) Okay, events. Lets try out chat events first. Post text to the chat url. what happens if two events happen at the same microsecond? I guess you'd miss one. Hm. I suppose we could return events that even have a timestamp equal to our last, and then check against things we already know about? -old- We shall have a glorious event system! When a user moves a piece, the board in the system is updated And, an event is created for each player detailing the move When a player checks for new events, all new events are sent to them And, (if the handshake succeeds?) they are deleted When a player loads the board view, all their incoming move events are deleted Should we use timestamps in this event system? They have potential to screw things up, so, perhaps only for show. \ No newline at end of file diff --git a/views.py b/views.py index bee0f61..ff57e3e 100644 --- a/views.py +++ b/views.py @@ -1,244 +1,246 @@ import web from database import db import dbview #from couch_util import couch_request COUCH_MAX = u"\u9999" from helper import render, get_you, get_game, require_you, make_timestamp from dbview import * import http class Index: def GET(self): you = get_you() - games = dbview.games(db).rows + import game_model + gameset = game_model.Game.all() + #games = dbview.games(db).rows users = [row.value for row in dbview.users(db)] - return render("index", games=games, users=users, you=get_you()) + return render("index", games=gameset, users=users, you=get_you()) class User: def GET(self, slug): possible_users = dbview.users(db, startkey=slug, endkey=slug).rows if not len(possible_users): return web.notfound() user = possible_users[0].value return render("user", user=user, you=get_you()) class Game: def GET(self, game_id): game = get_game(game_id) chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True) you = get_you() players = dict([(color, db[player_id]) for (color,player_id) in game["players"].iteritems()]) if you: your_players = [key for (key,value) in game["players"].iteritems() if value == you.id] else: your_players = [] return render('game',game=game, you=get_you(), chats=chats, your_players=your_players, players=players) class GameEvents: def GET(self, game_id, timestamp): import json events = dbview.events(db, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows if not len(events): # no events have happened in this game yet, most likely return json.dumps({"timestamp":timestamp}) newest_timestamp = events[-1].key[1] # highly dependent on query new_events = [event.value for event in events if event.key[1] != timestamp] if not len(new_events): return "{}" return json.dumps({"timestamp":newest_timestamp, "events":new_events}) class Games: def POST(self): you = require_you() params = web.input() if not params["user"]: return web.notfound() user = dbview.users(db, startkey=params['user'], endkey=params['user']).rows if not len(user): return web.notfound() else: user = user[0] from setup_board import board game = {"type":"game", "board":board, "timestamp":make_timestamp(), "turn":0, "players":{"red":you.id,"blue":user.id}, "order":["red","blue"]} game_id = db.create(game) web.seeother("/games/%s" % game_id) class GameChat: #def GET(self, game_id): # could just give us the chats, for debug purposes def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(text='') text = params["text"] if len(text) == 0: raise http.unacceptable("Chat messages must contain some text") chat = {"type":"chat", "text":text, "game":game_id, "user":you.id, "name":you["name"]} # synchronize timestamps game["timestamp"] = chat["timestamp"] = make_timestamp() db[game_id] = game db.create(chat) return "OK" class GameMove: def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(from_space=None, to_space=None) if not (params["from_space"] and params["to_space"]): raise http.badrequest("Moves must include from_space and to_space") from_space = tag_2d(params["from_space"]) to_space = tag_2d(params["to_space"]) if not (len(from_space) == len(to_space) == 2): raise http.badrequest("Invalid space tags") # check if it's your turn player = game["order"][game["turn"] % len(game["order"])] if game["players"][player] != you.id: raise http.precondition("It's not your turn") board = game["board"] attacking_piece = game["board"][from_space[0]][from_space[1]] if attacking_piece == None: raise http.forbidden("No piece to move from %s" % params["from_space"]) if attacking_piece["player"] != player: raise http.forbidden("It's not %s's turn" % attacking_piece["player"]) if not valid_move(attacking_piece["kind"], from_space, to_space): raise http.forbidden("You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"])) defending_piece = game["board"][to_space[0]][to_space[1]] if defending_piece != None: if attacking_piece["player"] == defending_piece["player"]: raise http.forbidden("You can't attack yourself") if not battle(attacking_piece["kind"], defending_piece["kind"]): raise http.forbidden("You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"])) # actually move the piece game["board"][from_space[0]][from_space[1]] = None game["board"][to_space[0]][to_space[1]] = attacking_piece # advance the turn game["turn"] += 1 # trigger an event move = {"type":"move", "game":game_id, "user":you.id, "name":you["name"], "from_space":params["from_space"], "to_space":params["to_space"]} # update timestamps just before saving game["timestamp"] = move["timestamp"] = timestamp = make_timestamp() db[game_id] = game move_id = db.create(move) return timestamp class Settings: def GET(self): return render("settings", you=require_you()) def POST(self): you = require_you() params = web.input(name='') unique = True name = params['name'] if name and name != you.get('name',None): from helper import slugify slug = slugify(name) for row in dbview.users(db): if slug == row.key: unique = False break if unique: you['name'] = name you['slug'] = slug elif not name and 'name' in you: # blanking your name makes you anonymous, and makes your page inaccessible del you['name'] del you['slug'] db[you.id] = you if unique: web.redirect('/') else: return render('settings', errors="Sorry, that name's taken!", you=you) urls = ( '/', Index, '/login', web.openid.host, '/settings', Settings, '/users/(.*)', User, #'/chat', Chat, '/games/(.*)/events/(.*)', GameEvents, '/games/(.*)/moves', GameMove, '/games/(.*)/chat', GameChat, '/games/(.*)', Game, '/games', Games, ) application = web.application(urls, locals()) type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} def tag_2d(tag): return [int(x) for x in tag.split('-')] def battle(attacker, defender): if attacker == "wizard": return False if defender == "wizard": return True attacker_type = attacker[:-1] defender_type = defender[:-1] if type_advantages[attacker_type] == defender_type: return True if type_advantages[defender_type] == attacker_type: return False attacker_level = int(attacker[-1]) defender_level = int(defender[-1]) if attacker_level > defender_level: return True return False def valid_move(kind, from_space, to_space): if abs(from_space[0] - to_space[0]) + abs(from_space[1] - to_space[1]) == 1: return True # only moved one space elif (kind == "wizard") and (abs(from_space[0] - to_space[0]) == 1) and (abs(from_space[1] - to_space[1]) == 1): return True # moved one space on each axis
nickretallack/elemental-chess-web
200c71a14b6f2245d34cb758d18a90b4a5dfeef6
prettier, hsl game list, now you can challenge people
diff --git a/discussion.txt b/discussion.txt index cdb8a2a..1a7dc97 100644 --- a/discussion.txt +++ b/discussion.txt @@ -1,100 +1,102 @@ Todo: - random unique user names + revert illegal moves? make it look nice + random unique user names randomize game colors with hsl + check that you can create games properly - check game logic on client side - how do I avoid sending the same event back to you? - maintain a list of sent events responsive client-side handling of moving pieces and stuff - detect mouse and keyboard activity, and throttle down polling if there is none for a while - users list so you can start a game with them - hash-colored games - settings page to set your name - Wishlist: unify user system with other projects? stretchy board with jquery resize filter droppables as well as draggables and set revert:true Board representation: It might be easier to represent the board as a hash of string-named spaces. This works for more kinds of games anyway. It's up to the game logic to decide if something on "space_foo" can move to "space_bar", either by deconstructing it into components or maintaining a border list or whatever. Then again, I'd have to remember the board's dimensions somewhere if I wanted to conveniently lay out a table for it. --- Strategy for tolerating multiple events in the same microsecond: 1) fetch all events starting at the requested microsecond 2) construct a new array that skims out all events equal to the requested microsecond 3) if the new array has length zero or one less than the old array, all is well. Return normally. 4) if the new array has length 2 or more less than the old array, return the old array instead 5) on the javascript side, only apply events at our same microsecond that we didn't personally send wait no, this is much simpler: just don't send events back to the client who broadcasted them if they have the same microsecond as requested. Hm, but how do we know which client broadcast them... Perhaps we should use their user id... Yeah, that makes sense. Then we can tell who was controlling a player when they caused an event :D. Nah this is all crap. I think we should just have the client check if they're receiving an event they already know about...? urgh no. Ugh, I have to do something to avoid always sending your own events back to yourself... db formats: (type=first word) move(user(id), from(space_tag), to(space_tag)) chat(user(id), text(string), game(id)) game(board(structure), players(color:id), turn(color)) --- Names: generate random silly names and stick them in the session for now. I guess you could change your name pretty easy by posting it to a url, but then we'd have to check that other people aren't using it... Should we represent players in the database? Do we need to know who's in a game? Lets see. Hm. Well we need to know who's allowed to post a new move, so yes. Maybe I should save the avante-guarde simplicity for later. Okay. Database stuff. Game: players, pieces(player_id, kind_tag, space_tag) hm, maybe you have to be logged in to play, but not to watch. Page setup: index: new game form, list of public games (private/public. Invite users?) Hmm, what about chatting directly at people. I guess we could have chat events that are to someone...(private) game/id: in a game. Hmm. How can we make a humane id for this. is.gd style? but what if people start a game at the same time... ah fuckit, we can use guids for now okay, setting up a game. lets use some old code to generate the board... nah fuckit, storing game data as pieces instead of the board just may be too much work. We have to render the board when you refresh anyway. ---------- okay! The event system would be much more efficient if we did not duplicate records, but instead used timestamps. When a player receives a page from the server, it includes a timestamp in a javascript variable. When they ask for events, they pass that timestamp in. The server finds events that have happened since that timestamp but not equal to it. It then passes them back with the timestamp of the latest one. Nothing is mutated on the server side for this reading action. Including a timestamp in the page: we better make sure there's no caching going on! Perhaps keep a record of the last timestamp you've sent and see if you ever regress. (oh god what about multiple windows... Well, they're safer with the timestamp approach at least. Now we know that if we regress on timestamps, it's likely either a caching problem OR multiple game windows.) Okay, events. Lets try out chat events first. Post text to the chat url. what happens if two events happen at the same microsecond? I guess you'd miss one. Hm. I suppose we could return events that even have a timestamp equal to our last, and then check against things we already know about? -old- We shall have a glorious event system! When a user moves a piece, the board in the system is updated And, an event is created for each player detailing the move When a player checks for new events, all new events are sent to them And, (if the handshake succeeds?) they are deleted When a player loads the board view, all their incoming move events are deleted Should we use timestamps in this event system? They have potential to screw things up, so, perhaps only for show. \ No newline at end of file diff --git a/helper.py b/helper.py index f52520d..97fbd8d 100644 --- a/helper.py +++ b/helper.py @@ -1,73 +1,82 @@ import web from database import db import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), line_statement_prefix="#") def user_name(user): if 'name' in user: return user['name'] else: return "anonymous" def hex_color(seed,invert=False): import random - random.seed(seed) - color = random.randint(0,16**6) - if invert: - color = 16**6 - color - return "%X" % color + import md5 + from hsl import HSL_2_RGB + digest = md5.new(seed).digest() + print digest + random.seed(digest) + color = HSL_2_RGB(random.random(), 1, random.uniform(.2,.8)) + print color + hex = "%02X%02X%02X" % color + print hex + return hex + # color = random.randint(0,16**6) + # if invert: + # color = 16**6 - color + # return "%X" % color env.filters['len'] = len env.filters['user_name'] = user_name env.filters['hex_color'] = hex_color import json env.filters['json'] = json.dumps def render(template,**args): return env.get_template(template+'.html').render(**args) def get_you(): openid = web.openid.status() if openid: key = "user-%s" % openid if key in db: return db[key] else: you = {'type':'user', 'openids':[openid], "name":"no-name"} db[key] = you return you def get_game(game_id): if game_id not in db: raise web.notfound() game = db[game_id] if game['type'] != "game": raise web.notfound() return game def require_you(): you = get_you() if not you: raise web.HTTPError("401 unauthorized", {}, "You must be logged in") return you def make_timestamp(): from datetime import datetime return datetime.now().isoformat() # Modified slugging routines originally stolen from patches to django def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata import re #value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) diff --git a/hsl.py b/hsl.py new file mode 100644 index 0000000..75512f1 --- /dev/null +++ b/hsl.py @@ -0,0 +1,66 @@ +from __future__ import division +import math + +def HSL_2_RGB(H,S,L): + if (S == 0 ): # HSL values = [0-1] + R = L * 255 # RGB results = [0-255] + G = L * 255 + B = L * 255 + else: + if ( L < 0.5 ): + var_2 = L * ( 1 + S ) + else: + var_2 = ( L + S ) - ( S * L ) + var_1 = 2 * L - var_2 + R = rounded(255 * Hue_2_RGB( var_1, var_2, H + ( 1 / 3 ) )) + G = rounded(255 * Hue_2_RGB( var_1, var_2, H )) + B = rounded(255 * Hue_2_RGB( var_1, var_2, H - ( 1 / 3 ) )) + return (R,G,B) + +def Hue_2_RGB( v1, v2, vH ): # Hue_2_RGB + if ( vH < 0 ): + vH += 1 + if ( vH > 1 ): + vH -= 1 + if ( ( 6 * vH ) < 1 ): + return ( v1 + ( v2 - v1 ) * 6 * vH ) + if ( ( 2 * vH ) < 1 ): + return v2 + if ( ( 3 * vH ) < 2 ): + return ( v1 + ( v2 - v1 ) * ( ( 2 / 3 ) - vH ) * 6 ) + return v1 + + +def hsl_rgb(hue, saturation, lightness): + if lightness < 0.5: + temp2 = lightness * (1 + saturation); + else: + temp2 = lightness + saturation - lightness*saturation; + + temp1 = 2 * lightness - temp2; + + colors = { + "red": (hue + 4/3) % 1, + "green": (hue + 3/3) % 1, + "blue": (hue + 2/3) % 1 + } + + result = {} + for (color,coloriness) in colors.iteritems(): + if coloriness * 6 < 1: + result[color] = temp1 + (temp2 - temp1) * 6 * coloriness; + elif coloriness * 2 < 1: + result[color] = temp2; + elif coloriness * 3 < 2: + result[color] = temp1 + (temp2 - temp1) * 6 * (2/3 - coloriness); + else: + result[color] = temp1; + return result + + + +def rounded(float): + return int(math.floor(float+0.5)) + +if __name__ == "__main__": + print HSL_2_RGB(0,1,.5) \ No newline at end of file diff --git a/static/game.js b/static/game.js index 1d24d8e..65056d9 100644 --- a/static/game.js +++ b/static/game.js @@ -1,157 +1,164 @@ $(document).ready(function(){ function find_targets(piece){ var orthogonals = [[0,1],[0,-1],[1,0],[-1,0]] var diagonals = [[-1,-1],[-1,+1],[+1,-1],[+1,+1]] var strengths = {water:'fire', fire:'plant', plant:'water'} // Find legal spaces to move to var kind = piece.attr('data_kind') var movements = orthogonals if(kind == "wizard") movements = orthogonals.concat(diagonals) var space = piece.parents('.space:first') var location = space.attr("data_location").split('-') filter = $(movements).map(function(){ return "[data_location="+(parseInt(location[0])+this[0])+"-"+(parseInt(location[1])+this[1])+"]" }).get().join(',') var neighbors = $('.space').filter(filter) // blacklist ones with disagreeable pieces on them var level = kind.slice(kind.length-1,kind.length) var type = kind.slice(0, kind.length-1) var player = piece.attr('data_player') var targets = neighbors.filter(function(){ var piece = $(this).children('.piece') if(!piece.length) return true // blank spaces are always legal if(piece && kind == 'wizard') return false // wizards can't attack var target_player = piece.attr('data_player') if(player == target_player) return false // can't attack yourself var target_kind = piece.attr('data_kind') var target_level = target_kind.slice(target_kind.length-1,target_kind.length) var target_type = target_kind.slice(0, target_kind.length-1) if(strengths[type] == target_type) return true if(strengths[target_type] == type) return false if(type == target_type && level > target_level) return true // same type fights by level return false }) return targets } // Moving Pieces var dragging = false var sent_events = {} function update_dragging(){ $(".piece").draggable("destroy") var player = turn_order[turn % turn_order.length] if($.inArray(player,your_players) == -1) return // no dragging other people's stuff $(".piece."+player+"-player").draggable({helper:'clone', scroll:true, start:function(event,ui){ dragging = true $(this).addClass('dragging') }, stop:function(event,ui){ dragging = false $('.highlight').removeClass('highlight') $(this).removeClass('dragging') } }) } update_dragging() $(".space").droppable({accept:".piece", drop:function(event,ui){ piece = ui.draggable from_space = piece.parents(".space:first") to_space = $(this) // check if it's a legal move before we send it if($.inArray(this,find_targets(piece)) == -1) return from_space_tag = from_space.attr("data_location") to_space_tag = to_space.attr("data_location") data = {from_space:from_space_tag, to_space:to_space_tag} $.ajax({type:"POST", url:"/games/"+game_id+"/moves", data:data, success:function(response){ $('#status').text('') sent_events[response] = true + move_message("You move", piece.attr('data_kind'), from_space_tag, to_space_tag) }, error:function(response){ $('#status').text(response.responseText) }}) // since we want to be responsive, lets just move the thing right now. to_space.children(".piece").remove() from_space.children(".piece").appendTo(to_space) // and advance the turn ourselves turn += 1 update_dragging() }}) // hilighting moves $(".piece").hover(function(){ var player = turn_order[turn % turn_order.length] if($.inArray(player,your_players) == -1) return // no dragging other people's stuff if($(this).attr('data_player') != player) return if(!dragging) find_targets($(this)).addClass('highlight') }, function(){ if(!dragging) $('.highlight').removeClass('highlight') }) // Getting Game Events var min_event_period = 1000 var event_period = min_event_period var event_check_timer var last_interaction = new Date().getTime() + function move_message(user, piece, from, to){ + $('#messages').prepend("<p>"+user+" "+piece+" from "+from+" to "+to+"</p>") + } + function checkEvents(){ var miliseconds_idle = new Date().getTime() - last_interaction event_period = min_event_period + miliseconds_idle*miliseconds_idle / 1000000.0 - console.debug(event_period) $.getJSON('/games/'+game_id+'/events/'+timestamp, function(response){ if(response.timestamp) timestamp = response.timestamp if(response.events){ $.each(response.events ,function(){ if(sent_events[this.timestamp]){ - delete sent_events[this.timestamp] // don't apply events you sent yourself + // don't apply events you sent yourself + delete sent_events[this.timestamp] } else if(this.type == "move"){ var from_space = $("[data_location="+this.from_space+"]") var to_space = $("[data_location="+this.to_space+"]") + var piece = from_space.children(".piece") to_space.children(".piece").remove() - from_space.children(".piece").appendTo(to_space) + piece.prependTo(to_space) turn += 1 update_dragging() + move_message(this.name+" moves", piece.attr('data_kind'), this.from_space, this.to_space) } else if(this.type == "chat"){ $('#messages').prepend("<p>"+this.name+": "+this.text+"</p>" ) } }) } event_check_timer = setTimeout(checkEvents, event_period) }) } function nudge(){ var miliseconds_idle = new Date().getTime() - last_interaction last_interaction = new Date().getTime() if(miliseconds_idle > 5000){ clearTimeout(event_check_timer) checkEvents() } } $(document).mousemove(nudge) $(document).keypress(nudge) event_check_timer = setTimeout(checkEvents, event_period) // Sending Game Chat $('#chat').submit(function(event){ event.preventDefault() var field = $('#chat [name=text]') if(field.val() == '') return data = $(this).serialize() field.val('') $.post('/games/'+game_id+'/chat',data) }) }) diff --git a/static/style.css b/static/style.css index 47185c7..7042b8b 100644 --- a/static/style.css +++ b/static/style.css @@ -1,16 +1,18 @@ table {border-collapse:collapse; } td {vertical-align:top;} .space {background-color:lightgrey; border:1px solid white; padding:0;} .space, .piece {width:80px; height:80px;} .piece img {max-width:80px; max-height:80px; display:block;} #logout-form, #login-form {display:inline;} .red-player {background-color:red;} .blue-player {background-color:blue;} .highlight {background-color:yellow !important;} .highlight .piece {background-color:orange;} .dragging {opacity:0.5;} -/*input {width:80px; height:80px; background-color:green;}*/ \ No newline at end of file +/*input {width:80px; height:80px; background-color:green;}*/ + +h2 {background-color:#00808d; color:white; margin:1ex 0 !important; text-align:center; padding-top:.2ex;} diff --git a/urls.py b/urls.py deleted file mode 100644 index e69de29..0000000 diff --git a/views.py b/views.py index 1b9bc77..bee0f61 100644 --- a/views.py +++ b/views.py @@ -1,233 +1,244 @@ import web from database import db import dbview #from couch_util import couch_request COUCH_MAX = u"\u9999" from helper import render, get_you, get_game, require_you, make_timestamp from dbview import * import http class Index: def GET(self): you = get_you() games = dbview.games(db).rows users = [row.value for row in dbview.users(db)] return render("index", games=games, users=users, you=get_you()) class User: def GET(self, slug): possible_users = dbview.users(db, startkey=slug, endkey=slug).rows if not len(possible_users): return web.notfound() user = possible_users[0].value return render("user", user=user, you=get_you()) class Game: def GET(self, game_id): game = get_game(game_id) chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True) you = get_you() players = dict([(color, db[player_id]) for (color,player_id) in game["players"].iteritems()]) if you: your_players = [key for (key,value) in game["players"].iteritems() if value == you.id] else: your_players = [] return render('game',game=game, you=get_you(), chats=chats, your_players=your_players, players=players) class GameEvents: def GET(self, game_id, timestamp): import json events = dbview.events(db, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows if not len(events): # no events have happened in this game yet, most likely return json.dumps({"timestamp":timestamp}) newest_timestamp = events[-1].key[1] # highly dependent on query new_events = [event.value for event in events if event.key[1] != timestamp] if not len(new_events): return "{}" return json.dumps({"timestamp":newest_timestamp, "events":new_events}) class Games: def POST(self): you = require_you() + params = web.input() + + if not params["user"]: + return web.notfound() + + user = dbview.users(db, startkey=params['user'], endkey=params['user']).rows + if not len(user): + return web.notfound() + else: + user = user[0] + from setup_board import board game = {"type":"game", "board":board, "timestamp":make_timestamp(), "turn":0, - "players":{"red":you.id,"blue":you.id}, "order":["red","blue"]} + "players":{"red":you.id,"blue":user.id}, "order":["red","blue"]} game_id = db.create(game) web.seeother("/games/%s" % game_id) class GameChat: #def GET(self, game_id): # could just give us the chats, for debug purposes def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(text='') text = params["text"] if len(text) == 0: raise http.unacceptable("Chat messages must contain some text") chat = {"type":"chat", "text":text, "game":game_id, "user":you.id, "name":you["name"]} # synchronize timestamps game["timestamp"] = chat["timestamp"] = make_timestamp() db[game_id] = game db.create(chat) return "OK" class GameMove: def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(from_space=None, to_space=None) if not (params["from_space"] and params["to_space"]): raise http.badrequest("Moves must include from_space and to_space") from_space = tag_2d(params["from_space"]) to_space = tag_2d(params["to_space"]) if not (len(from_space) == len(to_space) == 2): raise http.badrequest("Invalid space tags") # check if it's your turn player = game["order"][game["turn"] % len(game["order"])] if game["players"][player] != you.id: raise http.precondition("It's not your turn") board = game["board"] attacking_piece = game["board"][from_space[0]][from_space[1]] if attacking_piece == None: raise http.forbidden("No piece to move from %s" % params["from_space"]) if attacking_piece["player"] != player: raise http.forbidden("It's not %s's turn" % attacking_piece["player"]) if not valid_move(attacking_piece["kind"], from_space, to_space): raise http.forbidden("You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"])) defending_piece = game["board"][to_space[0]][to_space[1]] if defending_piece != None: if attacking_piece["player"] == defending_piece["player"]: raise http.forbidden("You can't attack yourself") if not battle(attacking_piece["kind"], defending_piece["kind"]): raise http.forbidden("You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"])) # actually move the piece game["board"][from_space[0]][from_space[1]] = None game["board"][to_space[0]][to_space[1]] = attacking_piece # advance the turn game["turn"] += 1 # trigger an event move = {"type":"move", "game":game_id, "user":you.id, "name":you["name"], "from_space":params["from_space"], "to_space":params["to_space"]} # update timestamps just before saving game["timestamp"] = move["timestamp"] = timestamp = make_timestamp() db[game_id] = game move_id = db.create(move) return timestamp class Settings: def GET(self): return render("settings", you=require_you()) def POST(self): you = require_you() params = web.input(name='') unique = True name = params['name'] if name and name != you.get('name',None): from helper import slugify slug = slugify(name) for row in dbview.users(db): if slug == row.key: unique = False break if unique: you['name'] = name you['slug'] = slug elif not name and 'name' in you: # blanking your name makes you anonymous, and makes your page inaccessible del you['name'] del you['slug'] db[you.id] = you if unique: web.redirect('/') else: return render('settings', errors="Sorry, that name's taken!", you=you) urls = ( '/', Index, '/login', web.openid.host, '/settings', Settings, '/users/(.*)', User, #'/chat', Chat, '/games/(.*)/events/(.*)', GameEvents, '/games/(.*)/moves', GameMove, '/games/(.*)/chat', GameChat, '/games/(.*)', Game, '/games', Games, ) application = web.application(urls, locals()) type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} def tag_2d(tag): return [int(x) for x in tag.split('-')] def battle(attacker, defender): if attacker == "wizard": return False if defender == "wizard": return True attacker_type = attacker[:-1] defender_type = defender[:-1] if type_advantages[attacker_type] == defender_type: return True if type_advantages[defender_type] == attacker_type: return False attacker_level = int(attacker[-1]) defender_level = int(defender[-1]) if attacker_level > defender_level: return True return False def valid_move(kind, from_space, to_space): if abs(from_space[0] - to_space[0]) + abs(from_space[1] - to_space[1]) == 1: return True # only moved one space elif (kind == "wizard") and (abs(from_space[0] - to_space[0]) == 1) and (abs(from_space[1] - to_space[1]) == 1): return True # moved one space on each axis
nickretallack/elemental-chess-web
1f1ed4b15e819e802f01fe38d71ef48a2dd30c5c
whoops
diff --git a/website.py b/website.py new file mode 100755 index 0000000..85b3c7a --- /dev/null +++ b/website.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +if __name__ == "__main__": + import web + web.config.debug = True + + from dbview import view_sync + view_sync() + + from views import application + application.run()
nickretallack/elemental-chess-web
b81cdbd7efa33802a40adffd19f24cc1d0aeed8d
okay, lets deploy it
diff --git a/discussion.txt b/discussion.txt index a84d961..cdb8a2a 100644 --- a/discussion.txt +++ b/discussion.txt @@ -1,99 +1,100 @@ Todo: random unique user names make it look nice + randomize game colors with hsl game logic on client side - how do I avoid sending the same event back to you? - maintain a list of sent events responsive client-side handling of moving pieces and stuff - detect mouse and keyboard activity, and throttle down polling if there is none for a while - users list so you can start a game with them - hash-colored games - settings page to set your name - Wishlist: unify user system with other projects? stretchy board with jquery resize filter droppables as well as draggables and set revert:true Board representation: It might be easier to represent the board as a hash of string-named spaces. This works for more kinds of games anyway. It's up to the game logic to decide if something on "space_foo" can move to "space_bar", either by deconstructing it into components or maintaining a border list or whatever. Then again, I'd have to remember the board's dimensions somewhere if I wanted to conveniently lay out a table for it. --- Strategy for tolerating multiple events in the same microsecond: 1) fetch all events starting at the requested microsecond 2) construct a new array that skims out all events equal to the requested microsecond 3) if the new array has length zero or one less than the old array, all is well. Return normally. 4) if the new array has length 2 or more less than the old array, return the old array instead 5) on the javascript side, only apply events at our same microsecond that we didn't personally send wait no, this is much simpler: just don't send events back to the client who broadcasted them if they have the same microsecond as requested. Hm, but how do we know which client broadcast them... Perhaps we should use their user id... Yeah, that makes sense. Then we can tell who was controlling a player when they caused an event :D. Nah this is all crap. I think we should just have the client check if they're receiving an event they already know about...? urgh no. Ugh, I have to do something to avoid always sending your own events back to yourself... db formats: (type=first word) move(user(id), from(space_tag), to(space_tag)) chat(user(id), text(string), game(id)) game(board(structure), players(color:id), turn(color)) --- Names: generate random silly names and stick them in the session for now. I guess you could change your name pretty easy by posting it to a url, but then we'd have to check that other people aren't using it... Should we represent players in the database? Do we need to know who's in a game? Lets see. Hm. Well we need to know who's allowed to post a new move, so yes. Maybe I should save the avante-guarde simplicity for later. Okay. Database stuff. Game: players, pieces(player_id, kind_tag, space_tag) hm, maybe you have to be logged in to play, but not to watch. Page setup: index: new game form, list of public games (private/public. Invite users?) Hmm, what about chatting directly at people. I guess we could have chat events that are to someone...(private) game/id: in a game. Hmm. How can we make a humane id for this. is.gd style? but what if people start a game at the same time... ah fuckit, we can use guids for now okay, setting up a game. lets use some old code to generate the board... nah fuckit, storing game data as pieces instead of the board just may be too much work. We have to render the board when you refresh anyway. ---------- okay! The event system would be much more efficient if we did not duplicate records, but instead used timestamps. When a player receives a page from the server, it includes a timestamp in a javascript variable. When they ask for events, they pass that timestamp in. The server finds events that have happened since that timestamp but not equal to it. It then passes them back with the timestamp of the latest one. Nothing is mutated on the server side for this reading action. Including a timestamp in the page: we better make sure there's no caching going on! Perhaps keep a record of the last timestamp you've sent and see if you ever regress. (oh god what about multiple windows... Well, they're safer with the timestamp approach at least. Now we know that if we regress on timestamps, it's likely either a caching problem OR multiple game windows.) Okay, events. Lets try out chat events first. Post text to the chat url. what happens if two events happen at the same microsecond? I guess you'd miss one. Hm. I suppose we could return events that even have a timestamp equal to our last, and then check against things we already know about? -old- We shall have a glorious event system! When a user moves a piece, the board in the system is updated And, an event is created for each player detailing the move When a player checks for new events, all new events are sent to them And, (if the handshake succeeds?) they are deleted When a player loads the board view, all their incoming move events are deleted Should we use timestamps in this event system? They have potential to screw things up, so, perhaps only for show. \ No newline at end of file diff --git a/main.py b/main.py deleted file mode 100755 index 85b3c7a..0000000 --- a/main.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -if __name__ == "__main__": - import web - web.config.debug = True - - from dbview import view_sync - view_sync() - - from views import application - application.run()
nickretallack/elemental-chess-web
7728cc0624ce7a7d0a319e55df92b0961aca2c26
now you can challenge users to a game
diff --git a/dbview.py b/dbview.py index 653078c..436a817 100644 --- a/dbview.py +++ b/dbview.py @@ -1,45 +1,45 @@ map_chats = """ function(doc){ if(doc.type == "chat"){ emit([doc.game, doc.timestamp], {"type":"chat", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, "text":doc.text}) } }""" map_events = """ function(doc){ if(doc.type == "chat"){ emit([doc.game, doc.timestamp], {"type":"chat", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, "text":doc.text}) } else if(doc.type == "move"){ emit([doc.game, doc.timestamp], {"type":"move", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, "from_space":doc.from_space, "to_space":doc.to_space }) } }""" map_games = """ function(doc){ if(doc.type == "game"){ emit(null,{"players":doc.players}) } } """ map_users = """ function(doc){ if(doc.type == "user"){ - emit(doc.slug, {"name":doc.name}) + emit(doc.slug, {"name":doc.name, "slug":doc.slug}) } }""" from couchdb.design import ViewDefinition as View users = View('users','show',map_users) games = View('games','show',map_games) events = View('events','all',map_events) chats = View('events','chats',map_chats) views = [users,games,events,chats] def view_sync(): from database import db View.sync_many(db,views,remove_missing=True) diff --git a/discussion.txt b/discussion.txt index 02b5fef..a84d961 100644 --- a/discussion.txt +++ b/discussion.txt @@ -1,94 +1,99 @@ Todo: random unique user names - users list so you can start a game with them - hash-colored games - game logic on client side - detect mouse and keyboard activity, and throttle down polling if there is none for a while - responsive client-side handling of moving pieces and stuff - how do I avoid sending the same event back to you? + make it look nice - settings page to set your name - CHECK + game logic on client side - + how do I avoid sending the same event back to you? - maintain a list of sent events + responsive client-side handling of moving pieces and stuff - + detect mouse and keyboard activity, and throttle down polling if there is none for a while - + users list so you can start a game with them - + hash-colored games - + settings page to set your name - +Wishlist: + unify user system with other projects? + stretchy board with jquery resize + filter droppables as well as draggables and set revert:true Board representation: It might be easier to represent the board as a hash of string-named spaces. This works for more kinds of games anyway. It's up to the game logic to decide if something on "space_foo" can move to "space_bar", either by deconstructing it into components or maintaining a border list or whatever. Then again, I'd have to remember the board's dimensions somewhere if I wanted to conveniently lay out a table for it. --- Strategy for tolerating multiple events in the same microsecond: 1) fetch all events starting at the requested microsecond 2) construct a new array that skims out all events equal to the requested microsecond 3) if the new array has length zero or one less than the old array, all is well. Return normally. 4) if the new array has length 2 or more less than the old array, return the old array instead 5) on the javascript side, only apply events at our same microsecond that we didn't personally send wait no, this is much simpler: just don't send events back to the client who broadcasted them if they have the same microsecond as requested. Hm, but how do we know which client broadcast them... Perhaps we should use their user id... Yeah, that makes sense. Then we can tell who was controlling a player when they caused an event :D. Nah this is all crap. I think we should just have the client check if they're receiving an event they already know about...? urgh no. Ugh, I have to do something to avoid always sending your own events back to yourself... db formats: (type=first word) move(user(id), from(space_tag), to(space_tag)) chat(user(id), text(string), game(id)) game(board(structure), players(color:id), turn(color)) --- Names: generate random silly names and stick them in the session for now. I guess you could change your name pretty easy by posting it to a url, but then we'd have to check that other people aren't using it... Should we represent players in the database? Do we need to know who's in a game? Lets see. Hm. Well we need to know who's allowed to post a new move, so yes. Maybe I should save the avante-guarde simplicity for later. Okay. Database stuff. Game: players, pieces(player_id, kind_tag, space_tag) hm, maybe you have to be logged in to play, but not to watch. Page setup: index: new game form, list of public games (private/public. Invite users?) Hmm, what about chatting directly at people. I guess we could have chat events that are to someone...(private) game/id: in a game. Hmm. How can we make a humane id for this. is.gd style? but what if people start a game at the same time... ah fuckit, we can use guids for now okay, setting up a game. lets use some old code to generate the board... nah fuckit, storing game data as pieces instead of the board just may be too much work. We have to render the board when you refresh anyway. ---------- okay! The event system would be much more efficient if we did not duplicate records, but instead used timestamps. When a player receives a page from the server, it includes a timestamp in a javascript variable. When they ask for events, they pass that timestamp in. The server finds events that have happened since that timestamp but not equal to it. It then passes them back with the timestamp of the latest one. Nothing is mutated on the server side for this reading action. Including a timestamp in the page: we better make sure there's no caching going on! Perhaps keep a record of the last timestamp you've sent and see if you ever regress. (oh god what about multiple windows... Well, they're safer with the timestamp approach at least. Now we know that if we regress on timestamps, it's likely either a caching problem OR multiple game windows.) Okay, events. Lets try out chat events first. Post text to the chat url. what happens if two events happen at the same microsecond? I guess you'd miss one. Hm. I suppose we could return events that even have a timestamp equal to our last, and then check against things we already know about? -old- We shall have a glorious event system! When a user moves a piece, the board in the system is updated And, an event is created for each player detailing the move When a player checks for new events, all new events are sent to them And, (if the handshake succeeds?) they are deleted When a player loads the board view, all their incoming move events are deleted Should we use timestamps in this event system? They have potential to screw things up, so, perhaps only for show. \ No newline at end of file diff --git a/templates/game.html b/templates/game.html index 5332f5b..f6f2bf2 100644 --- a/templates/game.html +++ b/templates/game.html @@ -1,35 +1,37 @@ # extends 'base.html' # block head <script type="text/javascript"> var game_id = "{{game.id}}" var timestamp = "{{game.timestamp}}" var turn_order = {{game.order|json}} var turn = {{game.turn}} var your_players = {{your_players|json}} </script> <script type="text/javascript" src="/static/game.js"></script> # endblock # block body <h3 id="status"></h3> +Red: {{players.red.name}} <table> # for x in range(game.board|len) <tr> # for y in range(game.board[x]|len) <td class="space" data_location="{{x}}-{{y}}"> # if game.board[x][y] # set piece = game.board[x][y] <div class="piece {{piece.player}}-player {{piece.kind}}-kind" data_player="{{piece.player}}" data_kind="{{piece.kind}}"> <img src="/static/pieces/{{game.board[x][y].kind}}.png"> </div> # endif </td> # endfor </tr> # endfor </table> +Blue: {{players.blue.name}} # include "chat.html" # endblock \ No newline at end of file diff --git a/templates/index.html b/templates/index.html index 82fffe5..2c355f4 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,51 +1,44 @@ # extends 'base.html' # block head <script type="text/javascript"> var timestamp = "{{timestamp}}" /* $(document).ready(function(){ console.debug("Going") $('#chat').submit(function(event){ event.preventDefault() data = $(event.target).serialize() $.post('/chat',data) }) event_period = 1000 function checkEvents(){ data = {timestamp:timestamp,stuff:{things:"hey"}} $.getJSON('/chat', data, function(response){ timestamp = response.timestamp $.each(response.chats,function(){ $('#messages').prepend("<p>New Message: "+this.text+"</p>" ) }) console.debug(response) setTimeout(checkEvents, event_period) }) } setTimeout(checkEvents, event_period) })*/ </script> # endblock # block body -# if you -<form action="/games" method="post"> - <input type="submit" value="New Game"> - +<h2>Users</h2> # for user in users -<input type="radio" name="challenger" value="{{user.id}}" id="challeng-{{user.id}}"> -<label for="challenge-{{user.id}}">{{user.value|user_name}}</label> +<a href="/users/{{user.slug}}">{{user.name}}</a> # endfor -</form> -# endif - +<h2>Games</h2> # for game in games <a style="background-color:#{{game.id|hex_color}}; color:#{{game.id|hex_color(-1)}}" href="/games/{{game.id}}">{{game.id}}</a> # endfor -# include "chat.html" # endblock \ No newline at end of file diff --git a/templates/user.html b/templates/user.html new file mode 100644 index 0000000..a69777a --- /dev/null +++ b/templates/user.html @@ -0,0 +1,8 @@ +# extends "base.html" +# block body +<h1>{{user.name}}</h1> +<form action="/games" method="post"> + <input type="hidden" name="user" value="{{user.slug}}" /> + <input type="submit" value="Challenge" /> +</form> +# endblock \ No newline at end of file diff --git a/views.py b/views.py index b90abb2..1b9bc77 100644 --- a/views.py +++ b/views.py @@ -1,225 +1,233 @@ import web from database import db import dbview #from couch_util import couch_request COUCH_MAX = u"\u9999" from helper import render, get_you, get_game, require_you, make_timestamp from dbview import * import http class Index: def GET(self): you = get_you() games = dbview.games(db).rows - - if you: - users = [row for row in dbview.users(db) if row["id"] != you.id] - else: - users = [] - #chats = db.query(find_chats).rows + users = [row.value for row in dbview.users(db)] return render("index", games=games, users=users, you=get_you()) +class User: + def GET(self, slug): + possible_users = dbview.users(db, startkey=slug, endkey=slug).rows + if not len(possible_users): + return web.notfound() + user = possible_users[0].value + return render("user", user=user, you=get_you()) + + + class Game: def GET(self, game_id): game = get_game(game_id) chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True) you = get_you() + + players = dict([(color, db[player_id]) for (color,player_id) in game["players"].iteritems()]) if you: your_players = [key for (key,value) in game["players"].iteritems() if value == you.id] else: your_players = [] - return render('game',game=game, you=get_you(), chats=chats, your_players=your_players) + return render('game',game=game, you=get_you(), chats=chats, your_players=your_players, players=players) class GameEvents: def GET(self, game_id, timestamp): import json events = dbview.events(db, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows if not len(events): # no events have happened in this game yet, most likely return json.dumps({"timestamp":timestamp}) newest_timestamp = events[-1].key[1] # highly dependent on query new_events = [event.value for event in events if event.key[1] != timestamp] if not len(new_events): return "{}" return json.dumps({"timestamp":newest_timestamp, "events":new_events}) class Games: def POST(self): you = require_you() from setup_board import board game = {"type":"game", "board":board, "timestamp":make_timestamp(), "turn":0, "players":{"red":you.id,"blue":you.id}, "order":["red","blue"]} game_id = db.create(game) web.seeother("/games/%s" % game_id) class GameChat: #def GET(self, game_id): # could just give us the chats, for debug purposes def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(text='') text = params["text"] if len(text) == 0: raise http.unacceptable("Chat messages must contain some text") chat = {"type":"chat", "text":text, "game":game_id, "user":you.id, "name":you["name"]} # synchronize timestamps game["timestamp"] = chat["timestamp"] = make_timestamp() db[game_id] = game db.create(chat) return "OK" class GameMove: def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(from_space=None, to_space=None) if not (params["from_space"] and params["to_space"]): raise http.badrequest("Moves must include from_space and to_space") from_space = tag_2d(params["from_space"]) to_space = tag_2d(params["to_space"]) if not (len(from_space) == len(to_space) == 2): raise http.badrequest("Invalid space tags") # check if it's your turn player = game["order"][game["turn"] % len(game["order"])] if game["players"][player] != you.id: raise http.precondition("It's not your turn") board = game["board"] attacking_piece = game["board"][from_space[0]][from_space[1]] if attacking_piece == None: raise http.forbidden("No piece to move from %s" % params["from_space"]) if attacking_piece["player"] != player: raise http.forbidden("It's not %s's turn" % attacking_piece["player"]) if not valid_move(attacking_piece["kind"], from_space, to_space): raise http.forbidden("You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"])) defending_piece = game["board"][to_space[0]][to_space[1]] if defending_piece != None: if attacking_piece["player"] == defending_piece["player"]: raise http.forbidden("You can't attack yourself") if not battle(attacking_piece["kind"], defending_piece["kind"]): raise http.forbidden("You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"])) # actually move the piece game["board"][from_space[0]][from_space[1]] = None game["board"][to_space[0]][to_space[1]] = attacking_piece # advance the turn game["turn"] += 1 # trigger an event move = {"type":"move", "game":game_id, "user":you.id, "name":you["name"], "from_space":params["from_space"], "to_space":params["to_space"]} # update timestamps just before saving game["timestamp"] = move["timestamp"] = timestamp = make_timestamp() db[game_id] = game move_id = db.create(move) return timestamp class Settings: def GET(self): return render("settings", you=require_you()) def POST(self): you = require_you() params = web.input(name='') unique = True name = params['name'] if name and name != you.get('name',None): from helper import slugify slug = slugify(name) for row in dbview.users(db): if slug == row.key: unique = False break if unique: you['name'] = name you['slug'] = slug elif not name and 'name' in you: # blanking your name makes you anonymous, and makes your page inaccessible del you['name'] del you['slug'] db[you.id] = you if unique: web.redirect('/') else: return render('settings', errors="Sorry, that name's taken!", you=you) urls = ( '/', Index, '/login', web.openid.host, '/settings', Settings, + '/users/(.*)', User, #'/chat', Chat, '/games/(.*)/events/(.*)', GameEvents, '/games/(.*)/moves', GameMove, '/games/(.*)/chat', GameChat, '/games/(.*)', Game, '/games', Games, ) application = web.application(urls, locals()) type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} def tag_2d(tag): return [int(x) for x in tag.split('-')] def battle(attacker, defender): if attacker == "wizard": return False if defender == "wizard": return True attacker_type = attacker[:-1] defender_type = defender[:-1] if type_advantages[attacker_type] == defender_type: return True if type_advantages[defender_type] == attacker_type: return False attacker_level = int(attacker[-1]) defender_level = int(defender[-1]) if attacker_level > defender_level: return True return False def valid_move(kind, from_space, to_space): if abs(from_space[0] - to_space[0]) + abs(from_space[1] - to_space[1]) == 1: return True # only moved one space elif (kind == "wizard") and (abs(from_space[0] - to_space[0]) == 1) and (abs(from_space[1] - to_space[1]) == 1): return True # moved one space on each axis
nickretallack/elemental-chess-web
5fe69b7c0ed4e8f5808b5b344d7e507d675a97eb
woot, added a decay function
diff --git a/static/game.js b/static/game.js index 4f9bb66..1d24d8e 100644 --- a/static/game.js +++ b/static/game.js @@ -1,109 +1,157 @@ -$(document).ready(function(){ +$(document).ready(function(){ function find_targets(piece){ var orthogonals = [[0,1],[0,-1],[1,0],[-1,0]] var diagonals = [[-1,-1],[-1,+1],[+1,-1],[+1,+1]] var strengths = {water:'fire', fire:'plant', plant:'water'} // Find legal spaces to move to var kind = piece.attr('data_kind') var movements = orthogonals if(kind == "wizard") movements = orthogonals.concat(diagonals) var space = piece.parents('.space:first') var location = space.attr("data_location").split('-') filter = $(movements).map(function(){ return "[data_location="+(parseInt(location[0])+this[0])+"-"+(parseInt(location[1])+this[1])+"]" }).get().join(',') var neighbors = $('.space').filter(filter) // blacklist ones with disagreeable pieces on them var level = kind.slice(kind.length-1,kind.length) var type = kind.slice(0, kind.length-1) var player = piece.attr('data_player') var targets = neighbors.filter(function(){ var piece = $(this).children('.piece') if(!piece.length) return true // blank spaces are always legal if(piece && kind == 'wizard') return false // wizards can't attack var target_player = piece.attr('data_player') if(player == target_player) return false // can't attack yourself var target_kind = piece.attr('data_kind') - var target_level = target_kind.slice(kind.length-1,kind.length) - var target_type = target_kind.slice(0, kind.length-1) + var target_level = target_kind.slice(target_kind.length-1,target_kind.length) + var target_type = target_kind.slice(0, target_kind.length-1) if(strengths[type] == target_type) return true if(strengths[target_type] == type) return false if(type == target_type && level > target_level) return true // same type fights by level return false }) return targets } // Moving Pieces var dragging = false - $(".piece").draggable({helper:'clone', scroll:true, start:function(event,ui){ - dragging = true - $(this).addClass('dragging') - }, stop:function(event,ui){ - dragging = false - $('.highlight').removeClass('highlight') - $(this).removeClass('dragging') - } - }) + var sent_events = {} + function update_dragging(){ + $(".piece").draggable("destroy") + + var player = turn_order[turn % turn_order.length] + if($.inArray(player,your_players) == -1) return // no dragging other people's stuff + + $(".piece."+player+"-player").draggable({helper:'clone', scroll:true, start:function(event,ui){ + dragging = true + $(this).addClass('dragging') + }, stop:function(event,ui){ + dragging = false + $('.highlight').removeClass('highlight') + $(this).removeClass('dragging') + } + }) + } + update_dragging() $(".space").droppable({accept:".piece", drop:function(event,ui){ piece = ui.draggable - from = piece.parents(".space:first").attr("data_location") - to = $(this).attr("data_location") + from_space = piece.parents(".space:first") + to_space = $(this) // check if it's a legal move before we send it if($.inArray(this,find_targets(piece)) == -1) return - data = {from_space:from, to_space:to} + from_space_tag = from_space.attr("data_location") + to_space_tag = to_space.attr("data_location") + data = {from_space:from_space_tag, to_space:to_space_tag} $.ajax({type:"POST", url:"/games/"+game_id+"/moves", data:data, success:function(response){ $('#status').text('') + sent_events[response] = true }, error:function(response){ $('#status').text(response.responseText) }}) + + // since we want to be responsive, lets just move the thing right now. + to_space.children(".piece").remove() + from_space.children(".piece").appendTo(to_space) + + // and advance the turn ourselves + turn += 1 + update_dragging() }}) // hilighting moves $(".piece").hover(function(){ + var player = turn_order[turn % turn_order.length] + if($.inArray(player,your_players) == -1) return // no dragging other people's stuff + if($(this).attr('data_player') != player) return + if(!dragging) find_targets($(this)).addClass('highlight') }, function(){ if(!dragging) $('.highlight').removeClass('highlight') }) // Getting Game Events - event_period = 1000 + var min_event_period = 1000 + var event_period = min_event_period + var event_check_timer + var last_interaction = new Date().getTime() + function checkEvents(){ + var miliseconds_idle = new Date().getTime() - last_interaction + event_period = min_event_period + miliseconds_idle*miliseconds_idle / 1000000.0 + console.debug(event_period) + $.getJSON('/games/'+game_id+'/events/'+timestamp, function(response){ if(response.timestamp) timestamp = response.timestamp if(response.events){ $.each(response.events ,function(){ - if(this.type == "move"){ + if(sent_events[this.timestamp]){ + delete sent_events[this.timestamp] // don't apply events you sent yourself + } else if(this.type == "move"){ var from_space = $("[data_location="+this.from_space+"]") var to_space = $("[data_location="+this.to_space+"]") to_space.children(".piece").remove() from_space.children(".piece").appendTo(to_space) - //console.debug(from_space.children(".piece"), to_space.children(".piece")) turn += 1 + update_dragging() } else if(this.type == "chat"){ $('#messages').prepend("<p>"+this.name+": "+this.text+"</p>" ) } }) } - setTimeout(checkEvents, event_period) + event_check_timer = setTimeout(checkEvents, event_period) }) } - setTimeout(checkEvents, event_period) + + function nudge(){ + var miliseconds_idle = new Date().getTime() - last_interaction + last_interaction = new Date().getTime() + if(miliseconds_idle > 5000){ + clearTimeout(event_check_timer) + checkEvents() + } + } + + $(document).mousemove(nudge) + $(document).keypress(nudge) + + event_check_timer = setTimeout(checkEvents, event_period) + // Sending Game Chat $('#chat').submit(function(event){ event.preventDefault() var field = $('#chat [name=text]') if(field.val() == '') return data = $(this).serialize() field.val('') $.post('/games/'+game_id+'/chat',data) }) }) diff --git a/views.py b/views.py index 8820d6c..b90abb2 100644 --- a/views.py +++ b/views.py @@ -1,225 +1,225 @@ import web from database import db import dbview #from couch_util import couch_request COUCH_MAX = u"\u9999" from helper import render, get_you, get_game, require_you, make_timestamp from dbview import * import http class Index: def GET(self): you = get_you() games = dbview.games(db).rows if you: users = [row for row in dbview.users(db) if row["id"] != you.id] else: users = [] #chats = db.query(find_chats).rows return render("index", games=games, users=users, you=get_you()) class Game: def GET(self, game_id): game = get_game(game_id) chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True) you = get_you() if you: your_players = [key for (key,value) in game["players"].iteritems() if value == you.id] else: your_players = [] return render('game',game=game, you=get_you(), chats=chats, your_players=your_players) class GameEvents: def GET(self, game_id, timestamp): import json events = dbview.events(db, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows if not len(events): # no events have happened in this game yet, most likely return json.dumps({"timestamp":timestamp}) newest_timestamp = events[-1].key[1] # highly dependent on query new_events = [event.value for event in events if event.key[1] != timestamp] if not len(new_events): return "{}" return json.dumps({"timestamp":newest_timestamp, "events":new_events}) class Games: def POST(self): you = require_you() from setup_board import board game = {"type":"game", "board":board, "timestamp":make_timestamp(), "turn":0, "players":{"red":you.id,"blue":you.id}, "order":["red","blue"]} game_id = db.create(game) web.seeother("/games/%s" % game_id) class GameChat: #def GET(self, game_id): # could just give us the chats, for debug purposes def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(text='') text = params["text"] if len(text) == 0: raise http.unacceptable("Chat messages must contain some text") chat = {"type":"chat", "text":text, "game":game_id, "user":you.id, "name":you["name"]} # synchronize timestamps game["timestamp"] = chat["timestamp"] = make_timestamp() db[game_id] = game db.create(chat) return "OK" class GameMove: def POST(self, game_id): you = require_you() game = get_game(game_id) params = web.input(from_space=None, to_space=None) if not (params["from_space"] and params["to_space"]): raise http.badrequest("Moves must include from_space and to_space") from_space = tag_2d(params["from_space"]) to_space = tag_2d(params["to_space"]) if not (len(from_space) == len(to_space) == 2): raise http.badrequest("Invalid space tags") # check if it's your turn player = game["order"][game["turn"] % len(game["order"])] if game["players"][player] != you.id: raise http.precondition("It's not your turn") board = game["board"] attacking_piece = game["board"][from_space[0]][from_space[1]] if attacking_piece == None: raise http.forbidden("No piece to move from %s" % params["from_space"]) if attacking_piece["player"] != player: raise http.forbidden("It's not %s's turn" % attacking_piece["player"]) if not valid_move(attacking_piece["kind"], from_space, to_space): raise http.forbidden("You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"])) defending_piece = game["board"][to_space[0]][to_space[1]] if defending_piece != None: if attacking_piece["player"] == defending_piece["player"]: raise http.forbidden("You can't attack yourself") if not battle(attacking_piece["kind"], defending_piece["kind"]): raise http.forbidden("You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"])) # actually move the piece game["board"][from_space[0]][from_space[1]] = None game["board"][to_space[0]][to_space[1]] = attacking_piece # advance the turn game["turn"] += 1 # trigger an event move = {"type":"move", "game":game_id, "user":you.id, "name":you["name"], "from_space":params["from_space"], "to_space":params["to_space"]} # update timestamps just before saving - game["timestamp"] = move["timestamp"] = make_timestamp() + game["timestamp"] = move["timestamp"] = timestamp = make_timestamp() db[game_id] = game move_id = db.create(move) - return move_id + return timestamp class Settings: def GET(self): return render("settings", you=require_you()) def POST(self): you = require_you() params = web.input(name='') unique = True name = params['name'] if name and name != you.get('name',None): from helper import slugify slug = slugify(name) for row in dbview.users(db): if slug == row.key: unique = False break if unique: you['name'] = name you['slug'] = slug elif not name and 'name' in you: # blanking your name makes you anonymous, and makes your page inaccessible del you['name'] del you['slug'] db[you.id] = you if unique: web.redirect('/') else: return render('settings', errors="Sorry, that name's taken!", you=you) urls = ( '/', Index, '/login', web.openid.host, '/settings', Settings, #'/chat', Chat, '/games/(.*)/events/(.*)', GameEvents, '/games/(.*)/moves', GameMove, '/games/(.*)/chat', GameChat, '/games/(.*)', Game, '/games', Games, ) application = web.application(urls, locals()) type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} def tag_2d(tag): return [int(x) for x in tag.split('-')] def battle(attacker, defender): if attacker == "wizard": return False if defender == "wizard": return True attacker_type = attacker[:-1] defender_type = defender[:-1] if type_advantages[attacker_type] == defender_type: return True if type_advantages[defender_type] == attacker_type: return False attacker_level = int(attacker[-1]) defender_level = int(defender[-1]) if attacker_level > defender_level: return True return False def valid_move(kind, from_space, to_space): if abs(from_space[0] - to_space[0]) + abs(from_space[1] - to_space[1]) == 1: return True # only moved one space elif (kind == "wizard") and (abs(from_space[0] - to_space[0]) == 1) and (abs(from_space[1] - to_space[1]) == 1): return True # moved one space on each axis
nickretallack/elemental-chess-web
e88002fa7e926a551176eb5e61eeabd9e6007ad1
lotsa new features. You can drag stuff around now
diff --git a/dbview.py b/dbview.py new file mode 100644 index 0000000..653078c --- /dev/null +++ b/dbview.py @@ -0,0 +1,45 @@ +map_chats = """ +function(doc){ +if(doc.type == "chat"){ + emit([doc.game, doc.timestamp], {"type":"chat", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, + "text":doc.text}) + } +}""" + +map_events = """ +function(doc){ + if(doc.type == "chat"){ + emit([doc.game, doc.timestamp], {"type":"chat", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, + "text":doc.text}) + } else if(doc.type == "move"){ + emit([doc.game, doc.timestamp], {"type":"move", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, + "from_space":doc.from_space, "to_space":doc.to_space }) + } +}""" + +map_games = """ +function(doc){ + if(doc.type == "game"){ + emit(null,{"players":doc.players}) + } +} +""" + +map_users = """ +function(doc){ + if(doc.type == "user"){ + emit(doc.slug, {"name":doc.name}) + } +}""" + +from couchdb.design import ViewDefinition as View +users = View('users','show',map_users) +games = View('games','show',map_games) +events = View('events','all',map_events) +chats = View('events','chats',map_chats) + +views = [users,games,events,chats] + +def view_sync(): + from database import db + View.sync_many(db,views,remove_missing=True) diff --git a/discussion.txt b/discussion.txt index 1c20f56..02b5fef 100644 --- a/discussion.txt +++ b/discussion.txt @@ -1,81 +1,94 @@ -Board representation: -It might be easier to represent the board as a hash of string-named spaces. This works for more kinds of games anyway. It's up to the game logic to decide if something on "space_foo" can move to "space_bar", either by deconstructing it into components or maintaining a border list or whatever. +Todo: + random unique user names + users list so you can start a game with them + hash-colored games + game logic on client side + detect mouse and keyboard activity, and throttle down polling if there is none for a while + responsive client-side handling of moving pieces and stuff + how do I avoid sending the same event back to you? + + settings page to set your name - CHECK + +Board representation: +It might be easier to represent the board as a hash of string-named spaces. This works for more kinds of games anyway. It's up to the game logic to decide if something on "space_foo" can move to "space_bar", either by deconstructing it into components or maintaining a border list or whatever. + +Then again, I'd have to remember the board's dimensions somewhere if I wanted to conveniently lay out a table for it. --- Strategy for tolerating multiple events in the same microsecond: 1) fetch all events starting at the requested microsecond 2) construct a new array that skims out all events equal to the requested microsecond 3) if the new array has length zero or one less than the old array, all is well. Return normally. 4) if the new array has length 2 or more less than the old array, return the old array instead 5) on the javascript side, only apply events at our same microsecond that we didn't personally send wait no, this is much simpler: just don't send events back to the client who broadcasted them if they have the same microsecond as requested. Hm, but how do we know which client broadcast them... Perhaps we should use their user id... Yeah, that makes sense. Then we can tell who was controlling a player when they caused an event :D. Nah this is all crap. I think we should just have the client check if they're receiving an event they already know about...? urgh no. - +Ugh, I have to do something to avoid always sending your own events back to yourself... db formats: (type=first word) move(user(id), from(space_tag), to(space_tag)) chat(user(id), text(string), game(id)) game(board(structure), players(color:id), turn(color)) --- Names: generate random silly names and stick them in the session for now. I guess you could change your name pretty easy by posting it to a url, but then we'd have to check that other people aren't using it... Should we represent players in the database? Do we need to know who's in a game? Lets see. Hm. Well we need to know who's allowed to post a new move, so yes. Maybe I should save the avante-guarde simplicity for later. Okay. Database stuff. Game: players, pieces(player_id, kind_tag, space_tag) hm, maybe you have to be logged in to play, but not to watch. Page setup: index: new game form, list of public games (private/public. Invite users?) Hmm, what about chatting directly at people. I guess we could have chat events that are to someone...(private) game/id: in a game. Hmm. How can we make a humane id for this. is.gd style? but what if people start a game at the same time... ah fuckit, we can use guids for now okay, setting up a game. lets use some old code to generate the board... nah fuckit, storing game data as pieces instead of the board just may be too much work. We have to render the board when you refresh anyway. ---------- okay! The event system would be much more efficient if we did not duplicate records, but instead used timestamps. When a player receives a page from the server, it includes a timestamp in a javascript variable. When they ask for events, they pass that timestamp in. The server finds events that have happened since that timestamp but not equal to it. It then passes them back with the timestamp of the latest one. Nothing is mutated on the server side for this reading action. Including a timestamp in the page: we better make sure there's no caching going on! Perhaps keep a record of the last timestamp you've sent and see if you ever regress. (oh god what about multiple windows... Well, they're safer with the timestamp approach at least. Now we know that if we regress on timestamps, it's likely either a caching problem OR multiple game windows.) Okay, events. Lets try out chat events first. Post text to the chat url. what happens if two events happen at the same microsecond? I guess you'd miss one. Hm. I suppose we could return events that even have a timestamp equal to our last, and then check against things we already know about? -old- We shall have a glorious event system! When a user moves a piece, the board in the system is updated And, an event is created for each player detailing the move When a player checks for new events, all new events are sent to them And, (if the handshake succeeds?) they are deleted When a player loads the board view, all their incoming move events are deleted Should we use timestamps in this event system? They have potential to screw things up, so, perhaps only for show. \ No newline at end of file diff --git a/helper.py b/helper.py new file mode 100644 index 0000000..f52520d --- /dev/null +++ b/helper.py @@ -0,0 +1,73 @@ +import web +from database import db +import jinja2 +env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), line_statement_prefix="#") + + +def user_name(user): + if 'name' in user: + return user['name'] + else: + return "anonymous" + +def hex_color(seed,invert=False): + import random + random.seed(seed) + color = random.randint(0,16**6) + if invert: + color = 16**6 - color + return "%X" % color + +env.filters['len'] = len +env.filters['user_name'] = user_name +env.filters['hex_color'] = hex_color +import json +env.filters['json'] = json.dumps + + +def render(template,**args): + return env.get_template(template+'.html').render(**args) + +def get_you(): + openid = web.openid.status() + if openid: + key = "user-%s" % openid + if key in db: + return db[key] + else: + you = {'type':'user', 'openids':[openid], "name":"no-name"} + db[key] = you + return you + +def get_game(game_id): + if game_id not in db: + raise web.notfound() + + game = db[game_id] + if game['type'] != "game": + raise web.notfound() + + return game + +def require_you(): + you = get_you() + if not you: + raise web.HTTPError("401 unauthorized", {}, "You must be logged in") + return you + + +def make_timestamp(): + from datetime import datetime + return datetime.now().isoformat() + + +# Modified slugging routines originally stolen from patches to django +def slugify(value): + """ Normalizes string, converts to lowercase, removes non-alpha characters, + and converts spaces to hyphens. """ + import unicodedata + import re + #value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') + value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) + return re.sub('[-\s]+', '-', value) + diff --git a/http.py b/http.py new file mode 100644 index 0000000..b875e30 --- /dev/null +++ b/http.py @@ -0,0 +1,13 @@ +import web + +def badrequest(message): + return web.HTTPError("400 Bad Request", {}, message) + +def forbidden(message): + return web.HTTPError("403 Forbidden", {}, message) + +def unacceptable(message): + return web.HTTPError("406 Not Acceptable", {}, message) + +def precondition(message): + return web.HTTPError("412 Precondition Failed", {}, message) diff --git a/main.py b/main.py index bfc3bb3..85b3c7a 100755 --- a/main.py +++ b/main.py @@ -1,8 +1,11 @@ #!/usr/bin/env python if __name__ == "__main__": import web web.config.debug = True + + from dbview import view_sync + view_sync() from views import application application.run() diff --git a/static/game.js b/static/game.js new file mode 100644 index 0000000..4f9bb66 --- /dev/null +++ b/static/game.js @@ -0,0 +1,109 @@ +$(document).ready(function(){ + function find_targets(piece){ + var orthogonals = [[0,1],[0,-1],[1,0],[-1,0]] + var diagonals = [[-1,-1],[-1,+1],[+1,-1],[+1,+1]] + var strengths = {water:'fire', fire:'plant', plant:'water'} + + // Find legal spaces to move to + var kind = piece.attr('data_kind') + var movements = orthogonals + if(kind == "wizard") movements = orthogonals.concat(diagonals) + + var space = piece.parents('.space:first') + var location = space.attr("data_location").split('-') + filter = $(movements).map(function(){ + return "[data_location="+(parseInt(location[0])+this[0])+"-"+(parseInt(location[1])+this[1])+"]" + }).get().join(',') + var neighbors = $('.space').filter(filter) + + // blacklist ones with disagreeable pieces on them + var level = kind.slice(kind.length-1,kind.length) + var type = kind.slice(0, kind.length-1) + var player = piece.attr('data_player') + var targets = neighbors.filter(function(){ + var piece = $(this).children('.piece') + if(!piece.length) return true // blank spaces are always legal + if(piece && kind == 'wizard') return false // wizards can't attack + var target_player = piece.attr('data_player') + if(player == target_player) return false // can't attack yourself + var target_kind = piece.attr('data_kind') + var target_level = target_kind.slice(kind.length-1,kind.length) + var target_type = target_kind.slice(0, kind.length-1) + if(strengths[type] == target_type) return true + if(strengths[target_type] == type) return false + if(type == target_type && level > target_level) return true // same type fights by level + return false + }) + return targets + } + + + // Moving Pieces + var dragging = false + $(".piece").draggable({helper:'clone', scroll:true, start:function(event,ui){ + dragging = true + $(this).addClass('dragging') + }, stop:function(event,ui){ + dragging = false + $('.highlight').removeClass('highlight') + $(this).removeClass('dragging') + } + }) + $(".space").droppable({accept:".piece", drop:function(event,ui){ + piece = ui.draggable + from = piece.parents(".space:first").attr("data_location") + to = $(this).attr("data_location") + + // check if it's a legal move before we send it + if($.inArray(this,find_targets(piece)) == -1) return + + data = {from_space:from, to_space:to} + $.ajax({type:"POST", url:"/games/"+game_id+"/moves", data:data, success:function(response){ + $('#status').text('') + }, error:function(response){ + $('#status').text(response.responseText) + }}) + }}) + + // hilighting moves + $(".piece").hover(function(){ + if(!dragging) find_targets($(this)).addClass('highlight') + }, function(){ + if(!dragging) $('.highlight').removeClass('highlight') + }) + + + // Getting Game Events + event_period = 1000 + function checkEvents(){ + $.getJSON('/games/'+game_id+'/events/'+timestamp, function(response){ + if(response.timestamp) timestamp = response.timestamp + if(response.events){ + $.each(response.events ,function(){ + if(this.type == "move"){ + var from_space = $("[data_location="+this.from_space+"]") + var to_space = $("[data_location="+this.to_space+"]") + to_space.children(".piece").remove() + from_space.children(".piece").appendTo(to_space) + //console.debug(from_space.children(".piece"), to_space.children(".piece")) + turn += 1 + } else if(this.type == "chat"){ + $('#messages').prepend("<p>"+this.name+": "+this.text+"</p>" ) + } + }) + } + setTimeout(checkEvents, event_period) + }) + } + setTimeout(checkEvents, event_period) + + // Sending Game Chat + $('#chat').submit(function(event){ + event.preventDefault() + var field = $('#chat [name=text]') + if(field.val() == '') return + data = $(this).serialize() + field.val('') + $.post('/games/'+game_id+'/chat',data) + }) +}) diff --git a/static/style.css b/static/style.css index afcb36c..47185c7 100644 --- a/static/style.css +++ b/static/style.css @@ -1,12 +1,16 @@ table {border-collapse:collapse; } td {vertical-align:top;} .space {background-color:lightgrey; border:1px solid white; padding:0;} .space, .piece {width:80px; height:80px;} .piece img {max-width:80px; max-height:80px; display:block;} +#logout-form, #login-form {display:inline;} .red-player {background-color:red;} .blue-player {background-color:blue;} +.highlight {background-color:yellow !important;} +.highlight .piece {background-color:orange;} +.dragging {opacity:0.5;} /*input {width:80px; height:80px; background-color:green;}*/ \ No newline at end of file diff --git a/templates/base.html b/templates/base.html index bfabdb7..55985d9 100644 --- a/templates/base.html +++ b/templates/base.html @@ -1,26 +1,27 @@ <html> <head> <title>Elemental Chess</title> <script type="text/javascript" src="/static/jquery-1.2.6.js"></script> <script type="text/javascript" src="/static/jquery.ui.all.js"></script> <link rel="stylesheet" type="text/css" href="/static/reset.css"> <link rel="stylesheet" type="text/css" href="/static/style.css"> # block head # endblock </head> <body> -<div id="userinfo"> + +<div id="header"> +<a href="/">Home</a> | # if you -logged in as {{you}} +logged in as {{you|user_name}} <a href="/settings" id="settings">settings</a><form method="post" action="/login" id="logout-form"><input type="hidden" name="action" value="logout" /><input type="submit" value="Log Out" id="logout"></form> # else <form method="post" action="/login" id="login-form"><input type="hidden" name="return_to" value="/"><input type="text" name="openid" id="openid_identifier"/><input type="submit" id="login" value="Log In"></form> <script type="text/javascript" id="__openidselector" src="https://www.idselector.com/selector/ddb6106634870c12617f13ab740aa8f24b723b56" charset="utf-8"></script> # endif </div> - # block body # endblock </body> </html> \ No newline at end of file diff --git a/templates/chat.html b/templates/chat.html new file mode 100644 index 0000000..70393b7 --- /dev/null +++ b/templates/chat.html @@ -0,0 +1,10 @@ +<form action="/chat" method="post" id="chat"> +<input type="text" name="text" /> +<input type="submit" value="Chat" /> +</form> + +<div id="messages"> +# for chat in chats +<p>{{chat.value.name}}: {{chat.value.text}}</p> +# endfor +</div> \ No newline at end of file diff --git a/templates/game.html b/templates/game.html index 7e44ee9..5332f5b 100644 --- a/templates/game.html +++ b/templates/game.html @@ -1,59 +1,35 @@ # extends 'base.html' # block head <script type="text/javascript"> var game_id = "{{game.id}}" var timestamp = "{{game.timestamp}}" - -$(document).ready(function(){ - $(".piece").draggable({helper:"clone"}) - $(".space").droppable({accept:".piece", drop:function(event,ui){ - piece = ui.draggable - from = piece.parents(".space:first").attr("data_location") - to = $(this).attr("data_location") - data = {from_space:from, to_space:to} - $.post("/games/"+game_id+"/moves", data, function(response){ - console.debug(response) - }) - }}) - - event_period = 1000 - function checkEvents(){ - $.getJSON('/games/'+game_id+'/events/'+timestamp, function(response){ - timestamp = response.timestamp - if(response.events){ - $.each(response.events ,function(){ - from_space = $("[data_location="+this.from_space+"]") - to_space = $("[data_location="+this.to_space+"]") - to_space.children(".piece").remove() - from_space.children(".piece").appendTo(to_space) - console.debug(from_space.children(".piece"), to_space.children(".piece")) - }) - } - //console.debug(response) - setTimeout(checkEvents, event_period) - }) - } - setTimeout(checkEvents, event_period) -}) - - +var turn_order = {{game.order|json}} +var turn = {{game.turn}} +var your_players = {{your_players|json}} </script> +<script type="text/javascript" src="/static/game.js"></script> # endblock - # block body +<h3 id="status"></h3> + <table> # for x in range(game.board|len) <tr> # for y in range(game.board[x]|len) <td class="space" data_location="{{x}}-{{y}}"> # if game.board[x][y] -<div class="piece {{game.board[x][y].player}}-player"><img src="/static/pieces/{{game.board[x][y].kind}}.png"></div> +# set piece = game.board[x][y] +<div class="piece {{piece.player}}-player {{piece.kind}}-kind" data_player="{{piece.player}}" data_kind="{{piece.kind}}"> + <img src="/static/pieces/{{game.board[x][y].kind}}.png"> +</div> # endif </td> # endfor </tr> # endfor </table> + +# include "chat.html" # endblock \ No newline at end of file diff --git a/templates/index.html b/templates/index.html index 55d08b4..82fffe5 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,52 +1,51 @@ # extends 'base.html' # block head <script type="text/javascript"> var timestamp = "{{timestamp}}" /* $(document).ready(function(){ console.debug("Going") $('#chat').submit(function(event){ event.preventDefault() data = $(event.target).serialize() $.post('/chat',data) }) event_period = 1000 function checkEvents(){ data = {timestamp:timestamp,stuff:{things:"hey"}} $.getJSON('/chat', data, function(response){ timestamp = response.timestamp $.each(response.chats,function(){ $('#messages').prepend("<p>New Message: "+this.text+"</p>" ) }) console.debug(response) setTimeout(checkEvents, event_period) }) } setTimeout(checkEvents, event_period) })*/ </script> # endblock # block body +# if you <form action="/games" method="post"> <input type="submit" value="New Game"> + +# for user in users +<input type="radio" name="challenger" value="{{user.id}}" id="challeng-{{user.id}}"> +<label for="challenge-{{user.id}}">{{user.value|user_name}}</label> +# endfor </form> +# endif + # for game in games -<a href="/games/{{game.id}}">{{game.id}}</a> +<a style="background-color:#{{game.id|hex_color}}; color:#{{game.id|hex_color(-1)}}" href="/games/{{game.id}}">{{game.id}}</a> # endfor -<form action="/chat" method="post" id="chat"> -<input type="text" name="text" /> -<input type="submit" value="Chat" /> -</form> - -<div id="messages"> -# for chat in chats -<p>Message: {{chat.value.text}}</p> -# endfor -</div> +# include "chat.html" # endblock \ No newline at end of file diff --git a/templates/settings.html b/templates/settings.html new file mode 100644 index 0000000..b3ccdf6 --- /dev/null +++ b/templates/settings.html @@ -0,0 +1,10 @@ +# extends "base.html" +# block body +<h3>{{errors}}</h3> + +<form action="/settings" method="post"> + <label for="name">Name:</label> + <input type="text" name="name" value="{{you.name}}"> + <input type="submit" value="Save"> +</form> +# endblock \ No newline at end of file diff --git a/views.py b/views.py index 2bd344e..8820d6c 100644 --- a/views.py +++ b/views.py @@ -1,333 +1,225 @@ import web from database import db +import dbview #from couch_util import couch_request COUCH_MAX = u"\u9999" +from helper import render, get_you, get_game, require_you, make_timestamp +from dbview import * +import http -import jinja2 -env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), line_statement_prefix="#") -env.filters['len'] = len - -def render(template,**args): - return env.get_template(template+'.html').render(**args) - -""" -class Piece(object): - def __init__(self,options): - self.rank = options['rank'] - self.kind = options['kind'] - self.player = options['player'] - self.x, self.y = options['location'] - - def tag(self): - return "%s-%s%d" % (self.player, self.kind, self.rank) - - def __str__(self): - return tag() - -class Target(object): - def __init__(self,piece,x,y): - self.piece = piece - self.x = x - self.y = y - - def __str__(self): - return "%s|%s|%s" % (piece.tag(),x,y) - -class Game(object): - def __init__(self): - # retrieve game state - game = couch_request('game',200) - #self.pieces = game['pieces'] - self.width = 5 - self.height = 6 - - # build some local indexes - self.spaces = [[{} for x in xrange(self.width)] for y in xrange(self.height)] - for piece_opts in game['pieces']: - piece = Piece(piece_opts) - self.spaces[piece.y][piece.x]['piece'] = piece - self.pieces[piece.tag()] = piece - - def mark_moves(self,piece_tag): - piece = self.pieces[piece_tag] - x,y = piece.x, piece.y - for move in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]: - nx,ny = move - if nx >= 0 and nx < self.width and ny >= 0 and ny < self.height: # make sure move lands on the board - target = self.spaces[ny][nx] - # unsafe wording.... - if not 'piece' in target or self.battle(piece_tag,target['piece']): # see if move is legal - self.spaces[ny][nx]['target'] = Target(piece) - - def battle(self,attacker_tag,defender_tag): - attacker = self.pieces[attacker_tag] - defender = self.pieces[defender_tag] - if int(attacker['rank']) < int(defender['rank']): - True - - -def mark_valid_moves(piece,board): - x,y = piece['location'] - for move in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]: - nx,ny = move - if nx >= 0 and nx < len(board[y]) and ny >= 0 and ny < len(board): # make sure move lands on the board - target = board[ny][nx] - # unsafe wording.... - if not 'piece' in target or battle(piece,target['piece']): # see if move is legal - board[ny][nx]['target'] = piece -""" - -def get_you(): - openid = web.openid.status() - if openid: - key = "user-%s" % openid - if key in db: - return db[key] - else: - you = {'type':'user', 'openids':[openid]} - db[key] = you - return you - - - -def make_timestamp(): - from datetime import datetime - return datetime.now().isoformat() - -find_chats = """ -function(doc){ - if(doc.type == "chat"){ - emit(doc.timestamp, {"text":doc.text}) - } -}""" - -find_events = """ -function(doc){ - if(doc.type == "chat"){ - emit([doc.game, doc.timestamp], {"type":"chat", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, - "text":doc.text}) - } else if(doc.type == "move"){ - emit([doc.game, doc.timestamp], {"type":"move", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, - "from_space":doc.from_space, "to_space":doc.to_space }) - } -}""" - - - -find_games = """ -function(doc){ - if(doc.type == "game"){ - emit(doc._id,1) - } -} -""" - - class Index: def GET(self): - games = db.query(find_games).rows - chats = db.query(find_chats).rows - return render("index", chats=chats, games=games, timestamp=chats[-1].key, you=get_you()) - -# class Chat: -# def POST(self): -# # this is an event -# params = web.input(text='') -# event = {"type":"chat", "timestamp":make_timestamp(), "text":params["text"]} -# db.create(event) -# return '' -# -# def GET(self): -# import json # making a current timestamp is totally meaningless... lets put it in the url -# params = web.input(timestamp=make_timestamp()) -# chats = db.query(find_chats, startkey=[None,params["timestamp"]]).rows -# if(len(chats)): -# timestamp = chats[-1].key -# else: -# timestamp = params["timestamp"] -# -# new_chats = [chat.value for chat in chats if chat.key != params["timestamp"]] -# return json.dumps({"timestamp":timestamp, "chats":new_chats}) -# #return json.dumps(chats) -# #game = Game() -# #render('simple.html',{'board':game.spaces}) + you = get_you() + games = dbview.games(db).rows + + if you: + users = [row for row in dbview.users(db) if row["id"] != you.id] + else: + users = [] + #chats = db.query(find_chats).rows + return render("index", games=games, users=users, you=get_you()) + + +class Game: + def GET(self, game_id): + game = get_game(game_id) + chats = dbview.chats(db, endkey=[game_id, ''], startkey=[game_id, COUCH_MAX], descending=True) + you = get_you() + + if you: + your_players = [key for (key,value) in game["players"].iteritems() if value == you.id] + else: + your_players = [] + + return render('game',game=game, you=get_you(), chats=chats, your_players=your_players) class GameEvents: def GET(self, game_id, timestamp): - you = get_you() - if you: you_id = you.id - else: you_id = None - import json - events = db.query(find_events, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows - if(not len(events)): # no events have happened in this game yet, most likely + + events = dbview.events(db, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows + + if not len(events): # no events have happened in this game yet, most likely return json.dumps({"timestamp":timestamp}) newest_timestamp = events[-1].key[1] # highly dependent on query new_events = [event.value for event in events if event.key[1] != timestamp] - message = json.dumps({"timestamp":newest_timestamp, "events":new_events}) - return message - + if not len(new_events): + return "{}" + + return json.dumps({"timestamp":newest_timestamp, "events":new_events}) -def tag_2d(tag): - return [int(x) for x in tag.split('-')] - +class Games: + def POST(self): + you = require_you() + from setup_board import board + game = {"type":"game", "board":board, "timestamp":make_timestamp(), "turn":0, + "players":{"red":you.id,"blue":you.id}, "order":["red","blue"]} + game_id = db.create(game) + web.seeother("/games/%s" % game_id) + -class Move: +class GameChat: + #def GET(self, game_id): # could just give us the chats, for debug purposes + def POST(self, game_id): - you = get_you() - if not you: # TODO - raise web.notfound() # how about access denied instead? + you = require_you() + game = get_game(game_id) + + params = web.input(text='') + text = params["text"] + if len(text) == 0: + raise http.unacceptable("Chat messages must contain some text") + + chat = {"type":"chat", "text":text, "game":game_id, "user":you.id, "name":you["name"]} - if game_id not in db: - raise web.notfound + # synchronize timestamps + game["timestamp"] = chat["timestamp"] = make_timestamp() + db[game_id] = game + db.create(chat) + return "OK" + + +class GameMove: + def POST(self, game_id): + you = require_you() + game = get_game(game_id) params = web.input(from_space=None, to_space=None) if not (params["from_space"] and params["to_space"]): - web.ctx.status = 400 - return "Moves must include from_space and to_space" + raise http.badrequest("Moves must include from_space and to_space") from_space = tag_2d(params["from_space"]) to_space = tag_2d(params["to_space"]) if not (len(from_space) == len(to_space) == 2): - web.ctx.status = 400 - return "Invalid space tags" - - game = db[game_id] + raise http.badrequest("Invalid space tags") + + # check if it's your turn + player = game["order"][game["turn"] % len(game["order"])] + if game["players"][player] != you.id: + raise http.precondition("It's not your turn") + board = game["board"] attacking_piece = game["board"][from_space[0]][from_space[1]] if attacking_piece == None: - return "No piece to move from %s" % params["from_space"] + raise http.forbidden("No piece to move from %s" % params["from_space"]) - if attacking_piece["player"] != "red": # TODO - return "You don't have a piece on %s" % params["from_space"] + if attacking_piece["player"] != player: + raise http.forbidden("It's not %s's turn" % attacking_piece["player"]) if not valid_move(attacking_piece["kind"], from_space, to_space): - #web.ctx.status = 401 - return "You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"]) + raise http.forbidden("You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"])) defending_piece = game["board"][to_space[0]][to_space[1]] if defending_piece != None: if attacking_piece["player"] == defending_piece["player"]: - #web.ctx.status = 401 - return "You can't attack yourself" - + raise http.forbidden("You can't attack yourself") if not battle(attacking_piece["kind"], defending_piece["kind"]): - #web.ctx.status = 401 - return "You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"]) - - + raise http.forbidden("You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"])) # actually move the piece game["board"][from_space[0]][from_space[1]] = None game["board"][to_space[0]][to_space[1]] = attacking_piece - # TODO: advance the turn? + # advance the turn + game["turn"] += 1 # trigger an event - move = {"type":"move", "game":game_id, "user":you.id, + move = {"type":"move", "game":game_id, "user":you.id, "name":you["name"], "from_space":params["from_space"], "to_space":params["to_space"]} # update timestamps just before saving game["timestamp"] = move["timestamp"] = make_timestamp() db[game_id] = game move_id = db.create(move) return move_id -type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} + +class Settings: + def GET(self): + return render("settings", you=require_you()) + + def POST(self): + you = require_you() + params = web.input(name='') + + + unique = True + name = params['name'] + if name and name != you.get('name',None): + from helper import slugify + slug = slugify(name) + for row in dbview.users(db): + if slug == row.key: + unique = False + break + + if unique: + you['name'] = name + you['slug'] = slug + elif not name and 'name' in you: + # blanking your name makes you anonymous, and makes your page inaccessible + del you['name'] + del you['slug'] + + db[you.id] = you + + if unique: + web.redirect('/') + else: + return render('settings', errors="Sorry, that name's taken!", you=you) + + +urls = ( + '/', Index, + '/login', web.openid.host, + '/settings', Settings, + #'/chat', Chat, + '/games/(.*)/events/(.*)', GameEvents, + '/games/(.*)/moves', GameMove, + '/games/(.*)/chat', GameChat, + '/games/(.*)', Game, + '/games', Games, + ) + +application = web.application(urls, locals()) + + +type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} + +def tag_2d(tag): + return [int(x) for x in tag.split('-')] + def battle(attacker, defender): if attacker == "wizard": return False if defender == "wizard": return True attacker_type = attacker[:-1] defender_type = defender[:-1] if type_advantages[attacker_type] == defender_type: return True if type_advantages[defender_type] == attacker_type: return False attacker_level = int(attacker[-1]) defender_level = int(defender[-1]) if attacker_level > defender_level: return True return False def valid_move(kind, from_space, to_space): if abs(from_space[0] - to_space[0]) + abs(from_space[1] - to_space[1]) == 1: return True # only moved one space - - # if to_space[0] == from_space[0]: - # if abs(to_space[1] - from_space[1]) == 1: - # return True - # elif to_space[1] == from_space[1] - # if abs(to_space[0] - from_space[0]) == 1: - # return True - elif (kind == "wizard") and (abs(from_space[0] - to_space[0]) == 1) and (abs(from_space[1] - to_space[1]) == 1): return True # moved one space on each axis - - - -""" - params = web.input(piece=None,target=None) - if params.piece: - # user selected a piece - game = Game() - game.mark_moves(params.piece) - render('simple.html',{'board':game.spaces}) - - elif params.target: - pass - # user tried to move the piece -""" - -class Game: - def GET(self, game_id): - if game_id not in db: - raise web.notfound() - - game = db[game_id] - if game['type'] != "game": - raise web.notfound() - - - #newest_event = db.query(find_events, startkey=[game_id,None], endkey=[game_id,COUCH_MAX], count=1, descending=True).rows[0] - #timestamp = newest_event - return render('game',game=game, you=get_you()) - - - - -class Games: - def POST(self): - you = get_you() or "TEST" - if not you: return "You must be logged in to create a game" - from setup_board import board - game = {"type":"game", "players":{"red":you}, "board":board, "turn":"red", "timestamp":make_timestamp()} - game_id = db.create(game) - web.seeother("/games/%s" % game_id) - - - -urls = ( - '/', Index, - '/login', web.openid.host, - '/chat', Chat, - '/games/(.*)/events/(.*)', GameEvents, - '/games/(.*)/moves', Move, - '/games/(.*)', Game, - '/games', Games, - ) - -application = web.application(urls, locals()) \ No newline at end of file
nickretallack/elemental-chess-web
520681695998086d23fc5df850e73da7a5d726bb
alright, lets clean up some code
diff --git a/discussion.txt b/discussion.txt index 58f542b..1c20f56 100644 --- a/discussion.txt +++ b/discussion.txt @@ -1,77 +1,81 @@ Board representation: It might be easier to represent the board as a hash of string-named spaces. This works for more kinds of games anyway. It's up to the game logic to decide if something on "space_foo" can move to "space_bar", either by deconstructing it into components or maintaining a border list or whatever. --- Strategy for tolerating multiple events in the same microsecond: 1) fetch all events starting at the requested microsecond 2) construct a new array that skims out all events equal to the requested microsecond 3) if the new array has length zero or one less than the old array, all is well. Return normally. 4) if the new array has length 2 or more less than the old array, return the old array instead 5) on the javascript side, only apply events at our same microsecond that we didn't personally send wait no, this is much simpler: just don't send events back to the client who broadcasted them if they have the same microsecond as requested. Hm, but how do we know which client broadcast them... Perhaps we should use their user id... Yeah, that makes sense. Then we can tell who was controlling a player when they caused an event :D. +Nah this is all crap. I think we should just have the client check if they're receiving an event they already know about...? urgh no. + + + db formats: (type=first word) move(user(id), from(space_tag), to(space_tag)) chat(user(id), text(string), game(id)) game(board(structure), players(color:id), turn(color)) --- Names: generate random silly names and stick them in the session for now. I guess you could change your name pretty easy by posting it to a url, but then we'd have to check that other people aren't using it... Should we represent players in the database? Do we need to know who's in a game? Lets see. Hm. Well we need to know who's allowed to post a new move, so yes. Maybe I should save the avante-guarde simplicity for later. Okay. Database stuff. Game: players, pieces(player_id, kind_tag, space_tag) hm, maybe you have to be logged in to play, but not to watch. Page setup: index: new game form, list of public games (private/public. Invite users?) Hmm, what about chatting directly at people. I guess we could have chat events that are to someone...(private) game/id: in a game. Hmm. How can we make a humane id for this. is.gd style? but what if people start a game at the same time... ah fuckit, we can use guids for now okay, setting up a game. lets use some old code to generate the board... nah fuckit, storing game data as pieces instead of the board just may be too much work. We have to render the board when you refresh anyway. ---------- okay! The event system would be much more efficient if we did not duplicate records, but instead used timestamps. When a player receives a page from the server, it includes a timestamp in a javascript variable. When they ask for events, they pass that timestamp in. The server finds events that have happened since that timestamp but not equal to it. It then passes them back with the timestamp of the latest one. Nothing is mutated on the server side for this reading action. Including a timestamp in the page: we better make sure there's no caching going on! Perhaps keep a record of the last timestamp you've sent and see if you ever regress. (oh god what about multiple windows... Well, they're safer with the timestamp approach at least. Now we know that if we regress on timestamps, it's likely either a caching problem OR multiple game windows.) Okay, events. Lets try out chat events first. Post text to the chat url. what happens if two events happen at the same microsecond? I guess you'd miss one. Hm. I suppose we could return events that even have a timestamp equal to our last, and then check against things we already know about? -old- We shall have a glorious event system! When a user moves a piece, the board in the system is updated And, an event is created for each player detailing the move When a player checks for new events, all new events are sent to them And, (if the handshake succeeds?) they are deleted When a player loads the board view, all their incoming move events are deleted Should we use timestamps in this event system? They have potential to screw things up, so, perhaps only for show. \ No newline at end of file diff --git a/templates/game.html b/templates/game.html index 91abf8d..7e44ee9 100644 --- a/templates/game.html +++ b/templates/game.html @@ -1,39 +1,59 @@ # extends 'base.html' # block head <script type="text/javascript"> var game_id = "{{game.id}}" +var timestamp = "{{game.timestamp}}" $(document).ready(function(){ $(".piece").draggable({helper:"clone"}) $(".space").droppable({accept:".piece", drop:function(event,ui){ piece = ui.draggable from = piece.parents(".space:first").attr("data_location") to = $(this).attr("data_location") data = {from_space:from, to_space:to} - $.post("/games/"+game_id+"/move", data, function(response){ + $.post("/games/"+game_id+"/moves", data, function(response){ console.debug(response) }) }}) + + event_period = 1000 + function checkEvents(){ + $.getJSON('/games/'+game_id+'/events/'+timestamp, function(response){ + timestamp = response.timestamp + if(response.events){ + $.each(response.events ,function(){ + from_space = $("[data_location="+this.from_space+"]") + to_space = $("[data_location="+this.to_space+"]") + to_space.children(".piece").remove() + from_space.children(".piece").appendTo(to_space) + console.debug(from_space.children(".piece"), to_space.children(".piece")) + }) + } + //console.debug(response) + setTimeout(checkEvents, event_period) + }) + } + setTimeout(checkEvents, event_period) }) </script> # endblock # block body <table> # for x in range(game.board|len) <tr> # for y in range(game.board[x]|len) <td class="space" data_location="{{x}}-{{y}}"> # if game.board[x][y] <div class="piece {{game.board[x][y].player}}-player"><img src="/static/pieces/{{game.board[x][y].kind}}.png"></div> # endif </td> # endfor </tr> # endfor </table> # endblock \ No newline at end of file diff --git a/templates/index.html b/templates/index.html index 1643409..55d08b4 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,52 +1,52 @@ # extends 'base.html' # block head <script type="text/javascript"> var timestamp = "{{timestamp}}" /* $(document).ready(function(){ console.debug("Going") $('#chat').submit(function(event){ event.preventDefault() data = $(event.target).serialize() $.post('/chat',data) }) event_period = 1000 function checkEvents(){ data = {timestamp:timestamp,stuff:{things:"hey"}} $.getJSON('/chat', data, function(response){ timestamp = response.timestamp $.each(response.chats,function(){ $('#messages').prepend("<p>New Message: "+this.text+"</p>" ) }) console.debug(response) setTimeout(checkEvents, event_period) }) } setTimeout(checkEvents, event_period) })*/ </script> # endblock # block body -<form action="/game" method="post"> +<form action="/games" method="post"> <input type="submit" value="New Game"> </form> # for game in games <a href="/games/{{game.id}}">{{game.id}}</a> # endfor <form action="/chat" method="post" id="chat"> <input type="text" name="text" /> <input type="submit" value="Chat" /> </form> <div id="messages"> # for chat in chats <p>Message: {{chat.value.text}}</p> # endfor </div> # endblock \ No newline at end of file diff --git a/views.py b/views.py index 995f73f..2bd344e 100644 --- a/views.py +++ b/views.py @@ -1,297 +1,333 @@ import web from database import db #from couch_util import couch_request +COUCH_MAX = u"\u9999" + + import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), line_statement_prefix="#") env.filters['len'] = len def render(template,**args): return env.get_template(template+'.html').render(**args) """ class Piece(object): def __init__(self,options): self.rank = options['rank'] self.kind = options['kind'] self.player = options['player'] self.x, self.y = options['location'] def tag(self): return "%s-%s%d" % (self.player, self.kind, self.rank) def __str__(self): return tag() class Target(object): def __init__(self,piece,x,y): self.piece = piece self.x = x self.y = y def __str__(self): return "%s|%s|%s" % (piece.tag(),x,y) class Game(object): def __init__(self): # retrieve game state game = couch_request('game',200) #self.pieces = game['pieces'] self.width = 5 self.height = 6 # build some local indexes self.spaces = [[{} for x in xrange(self.width)] for y in xrange(self.height)] for piece_opts in game['pieces']: piece = Piece(piece_opts) self.spaces[piece.y][piece.x]['piece'] = piece self.pieces[piece.tag()] = piece def mark_moves(self,piece_tag): piece = self.pieces[piece_tag] x,y = piece.x, piece.y for move in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]: nx,ny = move if nx >= 0 and nx < self.width and ny >= 0 and ny < self.height: # make sure move lands on the board target = self.spaces[ny][nx] # unsafe wording.... if not 'piece' in target or self.battle(piece_tag,target['piece']): # see if move is legal self.spaces[ny][nx]['target'] = Target(piece) def battle(self,attacker_tag,defender_tag): attacker = self.pieces[attacker_tag] defender = self.pieces[defender_tag] if int(attacker['rank']) < int(defender['rank']): True def mark_valid_moves(piece,board): x,y = piece['location'] for move in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]: nx,ny = move if nx >= 0 and nx < len(board[y]) and ny >= 0 and ny < len(board): # make sure move lands on the board target = board[ny][nx] # unsafe wording.... if not 'piece' in target or battle(piece,target['piece']): # see if move is legal board[ny][nx]['target'] = piece """ def get_you(): openid = web.openid.status() if openid: key = "user-%s" % openid if key in db: return db[key] else: you = {'type':'user', 'openids':[openid]} db[key] = you return you def make_timestamp(): from datetime import datetime return datetime.now().isoformat() find_chats = """ function(doc){ if(doc.type == "chat"){ emit(doc.timestamp, {"text":doc.text}) } }""" +find_events = """ +function(doc){ + if(doc.type == "chat"){ + emit([doc.game, doc.timestamp], {"type":"chat", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, + "text":doc.text}) + } else if(doc.type == "move"){ + emit([doc.game, doc.timestamp], {"type":"move", "user":doc.user, "name":doc.name, "timestamp":doc.timestamp, + "from_space":doc.from_space, "to_space":doc.to_space }) + } +}""" + + + find_games = """ function(doc){ if(doc.type == "game"){ emit(doc._id,1) } } """ class Index: def GET(self): games = db.query(find_games).rows chats = db.query(find_chats).rows return render("index", chats=chats, games=games, timestamp=chats[-1].key, you=get_you()) -class Chat: - def POST(self): - # this is an event - params = web.input(text='') - event = {"type":"chat", "timestamp":make_timestamp(), "text":params["text"]} - db.create(event) - return '' - - def GET(self): +# class Chat: +# def POST(self): +# # this is an event +# params = web.input(text='') +# event = {"type":"chat", "timestamp":make_timestamp(), "text":params["text"]} +# db.create(event) +# return '' +# +# def GET(self): +# import json # making a current timestamp is totally meaningless... lets put it in the url +# params = web.input(timestamp=make_timestamp()) +# chats = db.query(find_chats, startkey=[None,params["timestamp"]]).rows +# if(len(chats)): +# timestamp = chats[-1].key +# else: +# timestamp = params["timestamp"] +# +# new_chats = [chat.value for chat in chats if chat.key != params["timestamp"]] +# return json.dumps({"timestamp":timestamp, "chats":new_chats}) +# #return json.dumps(chats) +# #game = Game() +# #render('simple.html',{'board':game.spaces}) + + +class GameEvents: + def GET(self, game_id, timestamp): + you = get_you() + if you: you_id = you.id + else: you_id = None + import json - params = web.input(timestamp=make_timestamp()) - chats = db.query(find_chats, startkey=params["timestamp"]).rows - if(len(chats)): - timestamp = chats[-1].key - else: - timestamp = params["timestamp"] - - new_chats = [chat.value for chat in chats if chat.key != params["timestamp"]] - return json.dumps({"timestamp":timestamp, "chats":new_chats}) - #return json.dumps(chats) - #game = Game() - #render('simple.html',{'board':game.spaces}) - - -class Event: - def GET(self): - events = db.query(find_chats) + events = db.query(find_events, startkey=[game_id, timestamp], endkey=[game_id, COUCH_MAX]).rows + if(not len(events)): # no events have happened in this game yet, most likely + return json.dumps({"timestamp":timestamp}) + + newest_timestamp = events[-1].key[1] # highly dependent on query + new_events = [event.value for event in events if event.key[1] != timestamp] + message = json.dumps({"timestamp":newest_timestamp, "events":new_events}) + return message + def tag_2d(tag): return [int(x) for x in tag.split('-')] class Move: def POST(self, game_id): you = get_you() if not you: # TODO raise web.notfound() # how about access denied instead? if game_id not in db: raise web.notfound params = web.input(from_space=None, to_space=None) if not (params["from_space"] and params["to_space"]): web.ctx.status = 400 return "Moves must include from_space and to_space" from_space = tag_2d(params["from_space"]) to_space = tag_2d(params["to_space"]) if not (len(from_space) == len(to_space) == 2): web.ctx.status = 400 return "Invalid space tags" game = db[game_id] board = game["board"] attacking_piece = game["board"][from_space[0]][from_space[1]] if attacking_piece == None: return "No piece to move from %s" % params["from_space"] if attacking_piece["player"] != "red": # TODO return "You don't have a piece on %s" % params["from_space"] if not valid_move(attacking_piece["kind"], from_space, to_space): #web.ctx.status = 401 return "You can't move %s from %s to %s" % (attacking_piece["kind"], params["from_space"], params["to_space"]) defending_piece = game["board"][to_space[0]][to_space[1]] if defending_piece != None: if attacking_piece["player"] == defending_piece["player"]: #web.ctx.status = 401 return "You can't attack yourself" if not battle(attacking_piece["kind"], defending_piece["kind"]): #web.ctx.status = 401 return "You can't beat %s with %s" % (defending_piece["kind"], attacking_piece["kind"]) + + # actually move the piece game["board"][from_space[0]][from_space[1]] = None game["board"][to_space[0]][to_space[1]] = attacking_piece # TODO: advance the turn? - - db[game_id] = game - + # trigger an event - move = {"type":"move", "user":you.id, "timestamp":make_timestamp(), + move = {"type":"move", "game":game_id, "user":you.id, "from_space":params["from_space"], "to_space":params["to_space"]} - db.create(move) + # update timestamps just before saving + game["timestamp"] = move["timestamp"] = make_timestamp() + db[game_id] = game + move_id = db.create(move) - return "OK" + return move_id type_advantages = {"fire":"plant", "plant":"water", "water":"fire"} def battle(attacker, defender): if attacker == "wizard": return False if defender == "wizard": return True attacker_type = attacker[:-1] defender_type = defender[:-1] if type_advantages[attacker_type] == defender_type: return True if type_advantages[defender_type] == attacker_type: return False attacker_level = int(attacker[-1]) defender_level = int(defender[-1]) if attacker_level > defender_level: return True return False def valid_move(kind, from_space, to_space): if abs(from_space[0] - to_space[0]) + abs(from_space[1] - to_space[1]) == 1: return True # only moved one space # if to_space[0] == from_space[0]: # if abs(to_space[1] - from_space[1]) == 1: # return True # elif to_space[1] == from_space[1] # if abs(to_space[0] - from_space[0]) == 1: # return True elif (kind == "wizard") and (abs(from_space[0] - to_space[0]) == 1) and (abs(from_space[1] - to_space[1]) == 1): return True # moved one space on each axis """ params = web.input(piece=None,target=None) if params.piece: # user selected a piece game = Game() game.mark_moves(params.piece) render('simple.html',{'board':game.spaces}) elif params.target: pass # user tried to move the piece """ class Game: def GET(self, game_id): if game_id not in db: raise web.notfound() game = db[game_id] if game['type'] != "game": raise web.notfound() - return render('game',game=game) + + #newest_event = db.query(find_events, startkey=[game_id,None], endkey=[game_id,COUCH_MAX], count=1, descending=True).rows[0] + #timestamp = newest_event + return render('game',game=game, you=get_you()) class Games: def POST(self): you = get_you() or "TEST" if not you: return "You must be logged in to create a game" from setup_board import board - game = {"type":"game", "players":{"red":you}, "board":board, "turn":"red"} + game = {"type":"game", "players":{"red":you}, "board":board, "turn":"red", "timestamp":make_timestamp()} game_id = db.create(game) - web.seeother("/game/%s" % game_id) + web.seeother("/games/%s" % game_id) urls = ( '/', Index, '/login', web.openid.host, - '/games/(.*)/move', Move, '/chat', Chat, - '/games', Games, + '/games/(.*)/events/(.*)', GameEvents, + '/games/(.*)/moves', Move, '/games/(.*)', Game, + '/games', Games, ) application = web.application(urls, locals()) \ No newline at end of file
nickretallack/elemental-chess-web
fb468ee5945d8904cb117acc4607ad72cebb5419
check-in before major changes
diff --git a/views.py b/views.py index 8abbfda..a11f326 100644 --- a/views.py +++ b/views.py @@ -1,78 +1,90 @@ from couch_util import couch_request from web.cheetah import render import web class Piece(object): def __init__(self,options): self.rank = options['rank'] self.kind = options['kind'] - + self.player = options['player'] + self.x, self.y = options['location'] + + def tag(self): + return "%s-%s%d" % (self.player, self.kind, self.rank) + + def __str__(self): + return tag() class Target(object): - pass + def __init__(self,piece,x,y): + self.piece = piece + self.x = x + self.y = y + def __str__(self): + return "%s|%s|%s" % (piece.tag(),x,y) class Game(object): def __init__(self): # retrieve game state game = couch_request('game',200) - self.pieces = game['pieces'] + #self.pieces = game['pieces'] self.width = 5 self.height = 6 - # set up board view + # build some local indexes self.spaces = [[{} for x in xrange(self.width)] for y in xrange(self.height)] for piece_opts in game['pieces']: piece = Piece(piece_opts) - x,y = game['pieces'][piece]['location'] - self.spaces[y][x] = {'piece':piece} + self.spaces[piece.y][piece.x]['piece'] = piece + self.pieces[piece.tag()] = piece def mark_moves(self,piece_tag): piece = self.pieces[piece_tag] - x,y = piece['location'] + x,y = piece.x, piece.y for move in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]: nx,ny = move if nx >= 0 and nx < self.width and ny >= 0 and ny < self.height: # make sure move lands on the board target = self.spaces[ny][nx] # unsafe wording.... if not 'piece' in target or self.battle(piece_tag,target['piece']): # see if move is legal - self.spaces[ny][nx]['target'] = piece + self.spaces[ny][nx]['target'] = Target(piece) def battle(self,attacker_tag,defender_tag): attacker = self.pieces[attacker_tag] defender = self.pieces[defender_tag] if int(attacker['rank']) < int(defender['rank']): True def mark_valid_moves(piece,board): x,y = piece['location'] for move in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]: nx,ny = move if nx >= 0 and nx < len(board[y]) and ny >= 0 and ny < len(board): # make sure move lands on the board target = board[ny][nx] # unsafe wording.... if not 'piece' in target or battle(piece,target['piece']): # see if move is legal board[ny][nx]['target'] = piece class index: def GET(self): game = Game() render('simple.html',{'board':game.spaces}) class move: def POST(self): params = web.input(piece=None,target=None) if params.piece: # user selected a piece game = Game() game.mark_moves(params.piece) render('simple.html',{'board':game.spaces}) elif params.target: pass # user tried to move the piece \ No newline at end of file
nickretallack/elemental-chess-web
d9feefc44a2444366fa8d4130099cdf438b19dec
augh it is getting too object oriented
diff --git a/static/style.css b/static/style.css index d5a038a..5c4abe3 100644 --- a/static/style.css +++ b/static/style.css @@ -1,2 +1,2 @@ -.space {background-color:blue; margin:1px; width:80px; height:80px; position:relative;} -.piece {width:80px; height:80px; background-color:green; position:absolute; top:0; left:0;} \ No newline at end of file +.space {background-color:blue; margin:1px; width:80px; height:80px;} +input {width:80px; height:80px; background-color:green;} \ No newline at end of file diff --git a/templates/simple.html b/templates/simple.html index efbed26..adf0352 100644 --- a/templates/simple.html +++ b/templates/simple.html @@ -1,30 +1,31 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> - <link rel="stylesheet" type="text/css" href="static/style.css"> -<script type="text/javascript" src="static/mootools-1.2-core-nc.js"></script> -<script type="text/javascript" src="static/mootools-1.2-more.js"></script> -<script type="text/javascript" src="static/boardgame.js"></script> -</head> -<body> -<table> -#for $row in $board -<tr> - -#for $space in $row -<td class="space"> - -#if $space -<div class="piece"> -$space -</div> -#end if - -</td> -#end for - -</tr> -#end for -</table> -</body> -</html> \ No newline at end of file + <title>Elemental Chess</title> + <link rel="stylesheet" type="text/css" href="static/style.css" /> + <!--<script type="text/javascript" src="static/mootools-1.2-core-nc.js"></script> + <script type="text/javascript" src="static/mootools-1.2-more.js"></script> + <script type="text/javascript" src="static/boardgame.js"></script>--> + </head> + <body> + <form action="move" method="post"> + <table> + #for $row in $board + <tr> + #for $space in $row + <td class="space"> + #if 'piece' in $space and 'target' in $space + <input type="submit" value="$space.piece" name="conflict"> + #elif 'target' in $space + <input type="submit" value="$space.target" name="target"> + #elif 'piece' in $space + <input type="submit" value="$space.piece" name="piece"/> + #end if + </td> + #end for + </tr> + #end for + </table> + </form> + </body> + </html> \ No newline at end of file diff --git a/views.py b/views.py index a76f65d..8abbfda 100644 --- a/views.py +++ b/views.py @@ -1,24 +1,78 @@ from couch_util import couch_request from web.cheetah import render +import web -def setup(pieces): - width = 5 - height = 6 - spaces = [[None for x in xrange(width)] for y in xrange(height)] - for piece in pieces: - x,y = pieces[piece]['location'] - spaces[y][x] = piece - return spaces +class Piece(object): + def __init__(self,options): + self.rank = options['rank'] + self.kind = options['kind'] + + +class Target(object): + pass + + +class Game(object): + def __init__(self): + # retrieve game state + game = couch_request('game',200) + self.pieces = game['pieces'] + self.width = 5 + self.height = 6 + + # set up board view + self.spaces = [[{} for x in xrange(self.width)] for y in xrange(self.height)] + for piece_opts in game['pieces']: + piece = Piece(piece_opts) + x,y = game['pieces'][piece]['location'] + self.spaces[y][x] = {'piece':piece} + + def mark_moves(self,piece_tag): + piece = self.pieces[piece_tag] + x,y = piece['location'] + for move in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]: + nx,ny = move + if nx >= 0 and nx < self.width and ny >= 0 and ny < self.height: # make sure move lands on the board + target = self.spaces[ny][nx] + # unsafe wording.... + if not 'piece' in target or self.battle(piece_tag,target['piece']): # see if move is legal + self.spaces[ny][nx]['target'] = piece + + def battle(self,attacker_tag,defender_tag): + attacker = self.pieces[attacker_tag] + defender = self.pieces[defender_tag] + if int(attacker['rank']) < int(defender['rank']): + True + + + +def mark_valid_moves(piece,board): + x,y = piece['location'] + for move in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]: + nx,ny = move + if nx >= 0 and nx < len(board[y]) and ny >= 0 and ny < len(board): # make sure move lands on the board + target = board[ny][nx] + # unsafe wording.... + if not 'piece' in target or battle(piece,target['piece']): # see if move is legal + board[ny][nx]['target'] = piece + + class index: def GET(self): - game = couch_request('game',200) - #print game['pieces'] - board = setup(game['pieces']) - #print pieces - render('simple.html',{'board':board}) + game = Game() + render('simple.html',{'board':game.spaces}) class move: def POST(self): - print "moving" + params = web.input(piece=None,target=None) + if params.piece: + # user selected a piece + game = Game() + game.mark_moves(params.piece) + render('simple.html',{'board':game.spaces}) + + elif params.target: + pass + # user tried to move the piece \ No newline at end of file
nickretallack/elemental-chess-web
83e798a44344c06d0f30061621e7aaa2e840d4c4
doing good. Lets implement the rules on the server first
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c9b568f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.pyc +*.swp diff --git a/couch_util.py b/couch_util.py new file mode 100644 index 0000000..0f74dcb --- /dev/null +++ b/couch_util.py @@ -0,0 +1,13 @@ +from settings import database_url +import simplejson as json +from httplib2 import Http +http = Http() + +def couch_request(path,expected,*args,**kwargs): + url = "%s/%s" % (database_url,path) + if 'body' in kwargs: + kwargs['body'] = json.dumps(kwargs['body']) + response,content = http.request(url, *args, **kwargs ) + if response.status != expected: + print "Unexpected Status %d:%s for %s "%(response.status,response.reason,url) + return json.loads(content) \ No newline at end of file diff --git a/main.py b/main.py new file mode 100755 index 0000000..5086383 --- /dev/null +++ b/main.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python +from views import * +from urls import urls + +import web +if __name__ == "__main__": + web.webapi.internalerror = web.debugerror # enables debugger + web.run(urls, globals(), web.reloader) + diff --git a/settings.py b/settings.py new file mode 100644 index 0000000..b2a7d1d --- /dev/null +++ b/settings.py @@ -0,0 +1,3 @@ +database_host = 'http://localhost:5984' +database_name = 'elementalchess' +database_url = "%s/%s" % (database_host,database_name) \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..3b1881e --- /dev/null +++ b/setup.py @@ -0,0 +1,12 @@ +from settings import database_url + +import simplejson as json +from httplib2 import Http +http = Http() + +#create the database +try: + response, content = http.request(database_url, 'PUT') + print response.reason +except: + print "Connection Refused. Is couchdb running?" \ No newline at end of file diff --git a/setup_board.py b/setup_board.py new file mode 100644 index 0000000..9ea4b04 --- /dev/null +++ b/setup_board.py @@ -0,0 +1,36 @@ +from couch_util import couch_request + +# create the pieces +pieces = {} + +elements = ['fire','water','plant'] +ranks = 3 +players = ['red','blue'] + +for player in players: + for element in elements: + for rank in xrange(1,ranks+1): + tag = "%s-%s%s" % (player,element,rank) + pieces[tag] = {'kind':element,'rank':rank,'player':player} + wiztag = "%s-wizard" % player + pieces[wiztag] = {'kind':'wizard','rank':0,'player':player} + + +setup_string = """ +red-fire2 red-water1 red-wizard red-plant1 red-water3 +red-plant3 red-plant2 red-fire1 red-water2 red-fire3 +- - - - - +- - - - - +blue-fire3 blue-water2 blue-fire1 blue-plant2 blue-plant3 +blue-water3 blue-plant1 blue-wizard blue-water1 blue-fire2 +""" + +setup = [line.strip().split() for line in setup_string.splitlines() if line.strip()] +for y in xrange(len(setup)): + for x in xrange(len(setup[y])): + tag = setup[y][x] + if tag != '-': + pieces[tag]['location'] = [x,y] + +game = {'pieces':pieces, 'turn':'red'} +couch_request('game',201,'PUT',body=game) \ No newline at end of file diff --git a/static/boardgame.js b/static/boardgame.js new file mode 100644 index 0000000..8f31613 --- /dev/null +++ b/static/boardgame.js @@ -0,0 +1,15 @@ +function drop(piece,space){ + console.debug([piece,space]) +} + +window.addEvent('domready', function(event) { + $$(".piece").each(function(piece){ + piece.addEvent('mousedown', function(){ + var clone = piece.clone().set('opacity',0.4).injectBefore(piece) + drag = new Drag.Move(piece,{ + droppables:'.space', + onDrop:drop + }) + }) + }) +}) \ No newline at end of file diff --git a/static/mootools-1.2-core-nc.js b/static/mootools-1.2-core-nc.js new file mode 100644 index 0000000..e88d4ac --- /dev/null +++ b/static/mootools-1.2-core-nc.js @@ -0,0 +1,3816 @@ +/* +Script: Core.js + MooTools - My Object Oriented JavaScript Tools. + +License: + MIT-style license. + +Copyright: + Copyright (c) 2006-2007 [Valerio Proietti](http://mad4milk.net/). + +Code & Documentation: + [The MooTools production team](http://mootools.net/developers/). + +Inspiration: + - Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php) + - Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php) +*/ + +var MooTools = { + 'version': '1.2.0', + 'build': '' +}; + +var Native = function(options){ + options = options || {}; + + var afterImplement = options.afterImplement || function(){}; + var generics = options.generics; + generics = (generics !== false); + var legacy = options.legacy; + var initialize = options.initialize; + var protect = options.protect; + var name = options.name; + + var object = initialize || legacy; + + object.constructor = Native; + object.$family = {name: 'native'}; + if (legacy && initialize) object.prototype = legacy.prototype; + object.prototype.constructor = object; + + if (name){ + var family = name.toLowerCase(); + object.prototype.$family = {name: family}; + Native.typize(object, family); + } + + var add = function(obj, name, method, force){ + if (!protect || force || !obj.prototype[name]) obj.prototype[name] = method; + if (generics) Native.genericize(obj, name, protect); + afterImplement.call(obj, name, method); + return obj; + }; + + object.implement = function(a1, a2, a3){ + if (typeof a1 == 'string') return add(this, a1, a2, a3); + for (var p in a1) add(this, p, a1[p], a2); + return this; + }; + + object.alias = function(a1, a2, a3){ + if (typeof a1 == 'string'){ + a1 = this.prototype[a1]; + if (a1) add(this, a2, a1, a3); + } else { + for (var a in a1) this.alias(a, a1[a], a2); + } + return this; + }; + + return object; +}; + +Native.implement = function(objects, properties){ + for (var i = 0, l = objects.length; i < l; i++) objects[i].implement(properties); +}; + +Native.genericize = function(object, property, check){ + if ((!check || !object[property]) && typeof object.prototype[property] == 'function') object[property] = function(){ + var args = Array.prototype.slice.call(arguments); + return object.prototype[property].apply(args.shift(), args); + }; +}; + +Native.typize = function(object, family){ + if (!object.type) object.type = function(item){ + return ($type(item) === family); + }; +}; + +Native.alias = function(objects, a1, a2, a3){ + for (var i = 0, j = objects.length; i < j; i++) objects[i].alias(a1, a2, a3); +}; + +(function(objects){ + for (var name in objects) Native.typize(objects[name], name); +})({'boolean': Boolean, 'native': Native, 'object': Object}); + +(function(objects){ + for (var name in objects) new Native({name: name, initialize: objects[name], protect: true}); +})({'String': String, 'Function': Function, 'Number': Number, 'Array': Array, 'RegExp': RegExp, 'Date': Date}); + +(function(object, methods){ + for (var i = methods.length; i--; i) Native.genericize(object, methods[i], true); + return arguments.callee; +}) +(Array, ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice', 'toString', 'valueOf', 'indexOf', 'lastIndexOf']) +(String, ['charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'replace', 'search', 'slice', 'split', 'substr', 'substring', 'toLowerCase', 'toUpperCase', 'valueOf']); + +function $chk(obj){ + return !!(obj || obj === 0); +}; + +function $clear(timer){ + clearTimeout(timer); + clearInterval(timer); + return null; +}; + +function $defined(obj){ + return (obj != undefined); +}; + +function $empty(){}; + +function $arguments(i){ + return function(){ + return arguments[i]; + }; +}; + +function $lambda(value){ + return (typeof value == 'function') ? value : function(){ + return value; + }; +}; + +function $extend(original, extended){ + for (var key in (extended || {})) original[key] = extended[key]; + return original; +}; + +function $unlink(object){ + var unlinked; + + switch ($type(object)){ + case 'object': + unlinked = {}; + for (var p in object) unlinked[p] = $unlink(object[p]); + break; + case 'hash': + unlinked = $unlink(object.getClean()); + break; + case 'array': + unlinked = []; + for (var i = 0, l = object.length; i < l; i++) unlinked[i] = $unlink(object[i]); + break; + default: return object; + } + + return unlinked; +}; + +function $merge(){ + var mix = {}; + for (var i = 0, l = arguments.length; i < l; i++){ + var object = arguments[i]; + if ($type(object) != 'object') continue; + for (var key in object){ + var op = object[key], mp = mix[key]; + mix[key] = (mp && $type(op) == 'object' && $type(mp) == 'object') ? $merge(mp, op) : $unlink(op); + } + } + return mix; +}; + +function $pick(){ + for (var i = 0, l = arguments.length; i < l; i++){ + if (arguments[i] != undefined) return arguments[i]; + } + return null; +}; + +function $random(min, max){ + return Math.floor(Math.random() * (max - min + 1) + min); +}; + +function $splat(obj){ + var type = $type(obj); + return (type) ? ((type != 'array' && type != 'arguments') ? [obj] : obj) : []; +}; + +var $time = Date.now || function(){ + return new Date().getTime(); +}; + +function $try(){ + for (var i = 0, l = arguments.length; i < l; i++){ + try { + return arguments[i](); + } catch(e){} + } + return null; +}; + +function $type(obj){ + if (obj == undefined) return false; + if (obj.$family) return (obj.$family.name == 'number' && !isFinite(obj)) ? false : obj.$family.name; + if (obj.nodeName){ + switch (obj.nodeType){ + case 1: return 'element'; + case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace'; + } + } else if (typeof obj.length == 'number'){ + if (obj.callee) return 'arguments'; + else if (obj.item) return 'collection'; + } + return typeof obj; +}; + +var Hash = new Native({ + + name: 'Hash', + + initialize: function(object){ + if ($type(object) == 'hash') object = $unlink(object.getClean()); + for (var key in object) this[key] = object[key]; + return this; + } + +}); + +Hash.implement({ + + getLength: function(){ + var length = 0; + for (var key in this){ + if (this.hasOwnProperty(key)) length++; + } + return length; + }, + + forEach: function(fn, bind){ + for (var key in this){ + if (this.hasOwnProperty(key)) fn.call(bind, this[key], key, this); + } + }, + + getClean: function(){ + var clean = {}; + for (var key in this){ + if (this.hasOwnProperty(key)) clean[key] = this[key]; + } + return clean; + } + +}); + +Hash.alias('forEach', 'each'); + +function $H(object){ + return new Hash(object); +}; + +Array.implement({ + + forEach: function(fn, bind){ + for (var i = 0, l = this.length; i < l; i++) fn.call(bind, this[i], i, this); + } + +}); + +Array.alias('forEach', 'each'); + +function $A(iterable){ + if (iterable.item){ + var array = []; + for (var i = 0, l = iterable.length; i < l; i++) array[i] = iterable[i]; + return array; + } + return Array.prototype.slice.call(iterable); +}; + +function $each(iterable, fn, bind){ + var type = $type(iterable); + ((type == 'arguments' || type == 'collection' || type == 'array') ? Array : Hash).each(iterable, fn, bind); +}; + + +/* +Script: Browser.js + The Browser Core. Contains Browser initialization, Window and Document, and the Browser Hash. + +License: + MIT-style license. +*/ + +var Browser = new Hash({ + Engine: {name: 'unknown', version: ''}, + Platform: {name: (navigator.platform.match(/mac|win|linux/i) || ['other'])[0].toLowerCase()}, + Features: {xpath: !!(document.evaluate), air: !!(window.runtime)}, + Plugins: {} +}); + +if (window.opera) Browser.Engine = {name: 'presto', version: (document.getElementsByClassName) ? 950 : 925}; +else if (window.ActiveXObject) Browser.Engine = {name: 'trident', version: (window.XMLHttpRequest) ? 5 : 4}; +else if (!navigator.taintEnabled) Browser.Engine = {name: 'webkit', version: (Browser.Features.xpath) ? 420 : 419}; +else if (document.getBoxObjectFor != null) Browser.Engine = {name: 'gecko', version: (document.getElementsByClassName) ? 19 : 18}; +Browser.Engine[Browser.Engine.name] = Browser.Engine[Browser.Engine.name + Browser.Engine.version] = true; + +if (window.orientation != undefined) Browser.Platform.name = 'ipod'; + +Browser.Platform[Browser.Platform.name] = true; + +Browser.Request = function(){ + return $try(function(){ + return new XMLHttpRequest(); + }, function(){ + return new ActiveXObject('MSXML2.XMLHTTP'); + }); +}; + +Browser.Features.xhr = !!(Browser.Request()); + +Browser.Plugins.Flash = (function(){ + var version = ($try(function(){ + return navigator.plugins['Shockwave Flash'].description; + }, function(){ + return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); + }) || '0 r0').match(/\d+/g); + return {version: parseInt(version[0] || 0 + '.' + version[1] || 0), build: parseInt(version[2] || 0)}; +})(); + +function $exec(text){ + if (!text) return text; + if (window.execScript){ + window.execScript(text); + } else { + var script = document.createElement('script'); + script.setAttribute('type', 'text/javascript'); + script.text = text; + document.head.appendChild(script); + document.head.removeChild(script); + } + return text; +}; + +Native.UID = 1; + +var $uid = (Browser.Engine.trident) ? function(item){ + return (item.uid || (item.uid = [Native.UID++]))[0]; +} : function(item){ + return item.uid || (item.uid = Native.UID++); +}; + +var Window = new Native({ + + name: 'Window', + + legacy: (Browser.Engine.trident) ? null: window.Window, + + initialize: function(win){ + $uid(win); + if (!win.Element){ + win.Element = $empty; + if (Browser.Engine.webkit) win.document.createElement("iframe"); //fixes safari 2 + win.Element.prototype = (Browser.Engine.webkit) ? window["[[DOMElement.prototype]]"] : {}; + } + return $extend(win, Window.Prototype); + }, + + afterImplement: function(property, value){ + window[property] = Window.Prototype[property] = value; + } + +}); + +Window.Prototype = {$family: {name: 'window'}}; + +new Window(window); + +var Document = new Native({ + + name: 'Document', + + legacy: (Browser.Engine.trident) ? null: window.Document, + + initialize: function(doc){ + $uid(doc); + doc.head = doc.getElementsByTagName('head')[0]; + doc.html = doc.getElementsByTagName('html')[0]; + doc.window = doc.defaultView || doc.parentWindow; + if (Browser.Engine.trident4) $try(function(){ + doc.execCommand("BackgroundImageCache", false, true); + }); + return $extend(doc, Document.Prototype); + }, + + afterImplement: function(property, value){ + document[property] = Document.Prototype[property] = value; + } + +}); + +Document.Prototype = {$family: {name: 'document'}}; + +new Document(document); + +/* +Script: Array.js + Contains Array Prototypes like copy, each, contains, and remove. + +License: + MIT-style license. +*/ + +Array.implement({ + + every: function(fn, bind){ + for (var i = 0, l = this.length; i < l; i++){ + if (!fn.call(bind, this[i], i, this)) return false; + } + return true; + }, + + filter: function(fn, bind){ + var results = []; + for (var i = 0, l = this.length; i < l; i++){ + if (fn.call(bind, this[i], i, this)) results.push(this[i]); + } + return results; + }, + + clean: function() { + return this.filter($defined); + }, + + indexOf: function(item, from){ + var len = this.length; + for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){ + if (this[i] === item) return i; + } + return -1; + }, + + map: function(fn, bind){ + var results = []; + for (var i = 0, l = this.length; i < l; i++) results[i] = fn.call(bind, this[i], i, this); + return results; + }, + + some: function(fn, bind){ + for (var i = 0, l = this.length; i < l; i++){ + if (fn.call(bind, this[i], i, this)) return true; + } + return false; + }, + + associate: function(keys){ + var obj = {}, length = Math.min(this.length, keys.length); + for (var i = 0; i < length; i++) obj[keys[i]] = this[i]; + return obj; + }, + + link: function(object){ + var result = {}; + for (var i = 0, l = this.length; i < l; i++){ + for (var key in object){ + if (object[key](this[i])){ + result[key] = this[i]; + delete object[key]; + break; + } + } + } + return result; + }, + + contains: function(item, from){ + return this.indexOf(item, from) != -1; + }, + + extend: function(array){ + for (var i = 0, j = array.length; i < j; i++) this.push(array[i]); + return this; + }, + + getLast: function(){ + return (this.length) ? this[this.length - 1] : null; + }, + + getRandom: function(){ + return (this.length) ? this[$random(0, this.length - 1)] : null; + }, + + include: function(item){ + if (!this.contains(item)) this.push(item); + return this; + }, + + combine: function(array){ + for (var i = 0, l = array.length; i < l; i++) this.include(array[i]); + return this; + }, + + erase: function(item){ + for (var i = this.length; i--; i){ + if (this[i] === item) this.splice(i, 1); + } + return this; + }, + + empty: function(){ + this.length = 0; + return this; + }, + + flatten: function(){ + var array = []; + for (var i = 0, l = this.length; i < l; i++){ + var type = $type(this[i]); + if (!type) continue; + array = array.concat((type == 'array' || type == 'collection' || type == 'arguments') ? Array.flatten(this[i]) : this[i]); + } + return array; + }, + + hexToRgb: function(array){ + if (this.length != 3) return null; + var rgb = this.map(function(value){ + if (value.length == 1) value += value; + return value.toInt(16); + }); + return (array) ? rgb : 'rgb(' + rgb + ')'; + }, + + rgbToHex: function(array){ + if (this.length < 3) return null; + if (this.length == 4 && this[3] == 0 && !array) return 'transparent'; + var hex = []; + for (var i = 0; i < 3; i++){ + var bit = (this[i] - 0).toString(16); + hex.push((bit.length == 1) ? '0' + bit : bit); + } + return (array) ? hex : '#' + hex.join(''); + } + +}); + +/* +Script: Function.js + Contains Function Prototypes like create, bind, pass, and delay. + +License: + MIT-style license. +*/ + +Function.implement({ + + extend: function(properties){ + for (var property in properties) this[property] = properties[property]; + return this; + }, + + create: function(options){ + var self = this; + options = options || {}; + return function(event){ + var args = options.arguments; + args = (args != undefined) ? $splat(args) : Array.slice(arguments, (options.event) ? 1 : 0); + if (options.event) args = [event || window.event].extend(args); + var returns = function(){ + return self.apply(options.bind || null, args); + }; + if (options.delay) return setTimeout(returns, options.delay); + if (options.periodical) return setInterval(returns, options.periodical); + if (options.attempt) return $try(returns); + return returns(); + }; + }, + + pass: function(args, bind){ + return this.create({arguments: args, bind: bind}); + }, + + attempt: function(args, bind){ + return this.create({arguments: args, bind: bind, attempt: true})(); + }, + + bind: function(bind, args){ + return this.create({bind: bind, arguments: args}); + }, + + bindWithEvent: function(bind, args){ + return this.create({bind: bind, event: true, arguments: args}); + }, + + delay: function(delay, bind, args){ + return this.create({delay: delay, bind: bind, arguments: args})(); + }, + + periodical: function(interval, bind, args){ + return this.create({periodical: interval, bind: bind, arguments: args})(); + }, + + run: function(args, bind){ + return this.apply(bind, $splat(args)); + } + +}); + +/* +Script: Number.js + Contains Number Prototypes like limit, round, times, and ceil. + +License: + MIT-style license. +*/ + +Number.implement({ + + limit: function(min, max){ + return Math.min(max, Math.max(min, this)); + }, + + round: function(precision){ + precision = Math.pow(10, precision || 0); + return Math.round(this * precision) / precision; + }, + + times: function(fn, bind){ + for (var i = 0; i < this; i++) fn.call(bind, i, this); + }, + + toFloat: function(){ + return parseFloat(this); + }, + + toInt: function(base){ + return parseInt(this, base || 10); + } + +}); + +Number.alias('times', 'each'); + +(function(math){ + var methods = {}; + math.each(function(name){ + if (!Number[name]) methods[name] = function(){ + return Math[name].apply(null, [this].concat($A(arguments))); + }; + }); + Number.implement(methods); +})(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']); + +/* +Script: String.js + Contains String Prototypes like camelCase, capitalize, test, and toInt. + +License: + MIT-style license. +*/ + +String.implement({ + + test: function(regex, params){ + return ((typeof regex == 'string') ? new RegExp(regex, params) : regex).test(this); + }, + + contains: function(string, separator){ + return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : this.indexOf(string) > -1; + }, + + trim: function(){ + return this.replace(/^\s+|\s+$/g, ''); + }, + + clean: function(){ + return this.replace(/\s+/g, ' ').trim(); + }, + + camelCase: function(){ + return this.replace(/-\D/g, function(match){ + return match.charAt(1).toUpperCase(); + }); + }, + + hyphenate: function(){ + return this.replace(/[A-Z]/g, function(match){ + return ('-' + match.charAt(0).toLowerCase()); + }); + }, + + capitalize: function(){ + return this.replace(/\b[a-z]/g, function(match){ + return match.toUpperCase(); + }); + }, + + escapeRegExp: function(){ + return this.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1'); + }, + + toInt: function(base){ + return parseInt(this, base || 10); + }, + + toFloat: function(){ + return parseFloat(this); + }, + + hexToRgb: function(array){ + var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); + return (hex) ? hex.slice(1).hexToRgb(array) : null; + }, + + rgbToHex: function(array){ + var rgb = this.match(/\d{1,3}/g); + return (rgb) ? rgb.rgbToHex(array) : null; + }, + + stripScripts: function(option){ + var scripts = ''; + var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){ + scripts += arguments[1] + '\n'; + return ''; + }); + if (option === true) $exec(scripts); + else if ($type(option) == 'function') option(scripts, text); + return text; + }, + + substitute: function(object, regexp){ + return this.replace(regexp || (/\\?\{([^}]+)\}/g), function(match, name){ + if (match.charAt(0) == '\\') return match.slice(1); + return (object[name] != undefined) ? object[name] : ''; + }); + } + +}); + +/* +Script: Hash.js + Contains Hash Prototypes. Provides a means for overcoming the JavaScript practical impossibility of extending native Objects. + +License: + MIT-style license. +*/ + +Hash.implement({ + + has: Object.prototype.hasOwnProperty, + + keyOf: function(value){ + for (var key in this){ + if (this.hasOwnProperty(key) && this[key] === value) return key; + } + return null; + }, + + hasValue: function(value){ + return (Hash.keyOf(this, value) !== null); + }, + + extend: function(properties){ + Hash.each(properties, function(value, key){ + Hash.set(this, key, value); + }, this); + return this; + }, + + combine: function(properties){ + Hash.each(properties, function(value, key){ + Hash.include(this, key, value); + }, this); + return this; + }, + + erase: function(key){ + if (this.hasOwnProperty(key)) delete this[key]; + return this; + }, + + get: function(key){ + return (this.hasOwnProperty(key)) ? this[key] : null; + }, + + set: function(key, value){ + if (!this[key] || this.hasOwnProperty(key)) this[key] = value; + return this; + }, + + empty: function(){ + Hash.each(this, function(value, key){ + delete this[key]; + }, this); + return this; + }, + + include: function(key, value){ + var k = this[key]; + if (k == undefined) this[key] = value; + return this; + }, + + map: function(fn, bind){ + var results = new Hash; + Hash.each(this, function(value, key){ + results.set(key, fn.call(bind, value, key, this)); + }, this); + return results; + }, + + filter: function(fn, bind){ + var results = new Hash; + Hash.each(this, function(value, key){ + if (fn.call(bind, value, key, this)) results.set(key, value); + }, this); + return results; + }, + + every: function(fn, bind){ + for (var key in this){ + if (this.hasOwnProperty(key) && !fn.call(bind, this[key], key)) return false; + } + return true; + }, + + some: function(fn, bind){ + for (var key in this){ + if (this.hasOwnProperty(key) && fn.call(bind, this[key], key)) return true; + } + return false; + }, + + getKeys: function(){ + var keys = []; + Hash.each(this, function(value, key){ + keys.push(key); + }); + return keys; + }, + + getValues: function(){ + var values = []; + Hash.each(this, function(value){ + values.push(value); + }); + return values; + }, + + toQueryString: function(base){ + var queryString = []; + Hash.each(this, function(value, key){ + if (base) key = base + '[' + key + ']'; + var result; + switch ($type(value)){ + case 'object': result = Hash.toQueryString(value, key); break; + case 'array': + var qs = {}; + value.each(function(val, i){ + qs[i] = val; + }); + result = Hash.toQueryString(qs, key); + break; + default: result = key + '=' + encodeURIComponent(value); + } + if (value != undefined) queryString.push(result); + }); + + return queryString.join('&'); + } + +}); + +Hash.alias({keyOf: 'indexOf', hasValue: 'contains'}); + +/* +Script: Event.js + Contains the Event Native, to make the event object completely crossbrowser. + +License: + MIT-style license. +*/ + +var Event = new Native({ + + name: 'Event', + + initialize: function(event, win){ + win = win || window; + var doc = win.document; + event = event || win.event; + if (event.$extended) return event; + this.$extended = true; + var type = event.type; + var target = event.target || event.srcElement; + while (target && target.nodeType == 3) target = target.parentNode; + + if (type.test(/key/)){ + var code = event.which || event.keyCode; + var key = Event.Keys.keyOf(code); + if (type == 'keydown'){ + var fKey = code - 111; + if (fKey > 0 && fKey < 13) key = 'f' + fKey; + } + key = key || String.fromCharCode(code).toLowerCase(); + } else if (type.match(/(click|mouse|menu)/i)){ + doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; + var page = { + x: event.pageX || event.clientX + doc.scrollLeft, + y: event.pageY || event.clientY + doc.scrollTop + }; + var client = { + x: (event.pageX) ? event.pageX - win.pageXOffset : event.clientX, + y: (event.pageY) ? event.pageY - win.pageYOffset : event.clientY + }; + if (type.match(/DOMMouseScroll|mousewheel/)){ + var wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3; + } + var rightClick = (event.which == 3) || (event.button == 2); + var related = null; + if (type.match(/over|out/)){ + switch (type){ + case 'mouseover': related = event.relatedTarget || event.fromElement; break; + case 'mouseout': related = event.relatedTarget || event.toElement; + } + if (!(function(){ + while (related && related.nodeType == 3) related = related.parentNode; + return true; + }).create({attempt: Browser.Engine.gecko})()) related = false; + } + } + + return $extend(this, { + event: event, + type: type, + + page: page, + client: client, + rightClick: rightClick, + + wheel: wheel, + + relatedTarget: related, + target: target, + + code: code, + key: key, + + shift: event.shiftKey, + control: event.ctrlKey, + alt: event.altKey, + meta: event.metaKey + }); + } + +}); + +Event.Keys = new Hash({ + 'enter': 13, + 'up': 38, + 'down': 40, + 'left': 37, + 'right': 39, + 'esc': 27, + 'space': 32, + 'backspace': 8, + 'tab': 9, + 'delete': 46 +}); + +Event.implement({ + + stop: function(){ + return this.stopPropagation().preventDefault(); + }, + + stopPropagation: function(){ + if (this.event.stopPropagation) this.event.stopPropagation(); + else this.event.cancelBubble = true; + return this; + }, + + preventDefault: function(){ + if (this.event.preventDefault) this.event.preventDefault(); + else this.event.returnValue = false; + return this; + } + +}); + +/* +Script: Class.js + Contains the Class Function for easily creating, extending, and implementing reusable Classes. + +License: + MIT-style license. +*/ + +var Class = new Native({ + + name: 'Class', + + initialize: function(properties){ + properties = properties || {}; + var klass = function(empty){ + for (var key in this) this[key] = $unlink(this[key]); + for (var mutator in Class.Mutators){ + if (!this[mutator]) continue; + Class.Mutators[mutator](this, this[mutator]); + delete this[mutator]; + } + + this.constructor = klass; + if (empty === $empty) return this; + + var self = (this.initialize) ? this.initialize.apply(this, arguments) : this; + if (this.options && this.options.initialize) this.options.initialize.call(this); + return self; + }; + + $extend(klass, this); + klass.constructor = Class; + klass.prototype = properties; + return klass; + } + +}); + +Class.implement({ + + implement: function(){ + Class.Mutators.Implements(this.prototype, Array.slice(arguments)); + return this; + } + +}); + +Class.Mutators = { + + Implements: function(self, klasses){ + $splat(klasses).each(function(klass){ + $extend(self, ($type(klass) == 'class') ? new klass($empty) : klass); + }); + }, + + Extends: function(self, klass){ + var instance = new klass($empty); + delete instance.parent; + delete instance.parentOf; + + for (var key in instance){ + var current = self[key], previous = instance[key]; + if (current == undefined){ + self[key] = previous; + continue; + } + + var ctype = $type(current), ptype = $type(previous); + if (ctype != ptype) continue; + + switch (ctype){ + case 'function': + // this code will be only executed if the current browser does not support function.caller (currently only opera). + // we replace the function code with brute force. Not pretty, but it will only be executed if function.caller is not supported. + + if (!arguments.callee.caller) self[key] = eval('(' + String(current).replace(/\bthis\.parent\(\s*(\))?/g, function(full, close){ + return 'arguments.callee._parent_.call(this' + (close || ', '); + }) + ')'); + + // end "opera" code + self[key]._parent_ = previous; + break; + case 'object': self[key] = $merge(previous, current); + } + + } + + self.parent = function(){ + return arguments.callee.caller._parent_.apply(this, arguments); + }; + + self.parentOf = function(descendant){ + return descendant._parent_.apply(this, Array.slice(arguments, 1)); + }; + } + +}; + + +/* +Script: Class.Extras.js + Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks. + +License: + MIT-style license. +*/ + +var Chain = new Class({ + + chain: function(){ + this.$chain = (this.$chain || []).extend(arguments); + return this; + }, + + callChain: function(){ + return (this.$chain && this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false; + }, + + clearChain: function(){ + if (this.$chain) this.$chain.empty(); + return this; + } + +}); + +var Events = new Class({ + + addEvent: function(type, fn, internal){ + type = Events.removeOn(type); + if (fn != $empty){ + this.$events = this.$events || {}; + this.$events[type] = this.$events[type] || []; + this.$events[type].include(fn); + if (internal) fn.internal = true; + } + return this; + }, + + addEvents: function(events){ + for (var type in events) this.addEvent(type, events[type]); + return this; + }, + + fireEvent: function(type, args, delay){ + type = Events.removeOn(type); + if (!this.$events || !this.$events[type]) return this; + this.$events[type].each(function(fn){ + fn.create({'bind': this, 'delay': delay, 'arguments': args})(); + }, this); + return this; + }, + + removeEvent: function(type, fn){ + type = Events.removeOn(type); + if (!this.$events || !this.$events[type]) return this; + if (!fn.internal) this.$events[type].erase(fn); + return this; + }, + + removeEvents: function(type){ + for (var e in this.$events){ + if (type && type != e) continue; + var fns = this.$events[e]; + for (var i = fns.length; i--; i) this.removeEvent(e, fns[i]); + } + return this; + } + +}); + +Events.removeOn = function(string){ + return string.replace(/^on([A-Z])/, function(full, first) { + return first.toLowerCase(); + }); +}; + +var Options = new Class({ + + setOptions: function(){ + this.options = $merge.run([this.options].extend(arguments)); + if (!this.addEvent) return this; + for (var option in this.options){ + if ($type(this.options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue; + this.addEvent(option, this.options[option]); + delete this.options[option]; + } + return this; + } + +}); + +/* +Script: Element.js + One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, + time-saver methods to let you easily work with HTML Elements. + +License: + MIT-style license. +*/ + +Document.implement({ + + newElement: function(tag, props){ + if (Browser.Engine.trident && props){ + ['name', 'type', 'checked'].each(function(attribute){ + if (!props[attribute]) return; + tag += ' ' + attribute + '="' + props[attribute] + '"'; + if (attribute != 'checked') delete props[attribute]; + }); + tag = '<' + tag + '>'; + } + return $.element(this.createElement(tag)).set(props); + }, + + newTextNode: function(text){ + return this.createTextNode(text); + }, + + getDocument: function(){ + return this; + }, + + getWindow: function(){ + return this.defaultView || this.parentWindow; + }, + + purge: function(){ + var elements = this.getElementsByTagName('*'); + for (var i = 0, l = elements.length; i < l; i++) Browser.freeMem(elements[i]); + } + +}); + +var Element = new Native({ + + name: 'Element', + + legacy: window.Element, + + initialize: function(tag, props){ + var konstructor = Element.Constructors.get(tag); + if (konstructor) return konstructor(props); + if (typeof tag == 'string') return document.newElement(tag, props); + return $(tag).set(props); + }, + + afterImplement: function(key, value){ + if (!Array[key]) Elements.implement(key, Elements.multi(key)); + Element.Prototype[key] = value; + } + +}); + +Element.Prototype = {$family: {name: 'element'}}; + +Element.Constructors = new Hash; + +var IFrame = new Native({ + + name: 'IFrame', + + generics: false, + + initialize: function(){ + var params = Array.link(arguments, {properties: Object.type, iframe: $defined}); + var props = params.properties || {}; + var iframe = $(params.iframe) || false; + var onload = props.onload || $empty; + delete props.onload; + props.id = props.name = $pick(props.id, props.name, iframe.id, iframe.name, 'IFrame_' + $time()); + iframe = new Element(iframe || 'iframe', props); + var onFrameLoad = function(){ + var host = $try(function(){ + return iframe.contentWindow.location.host; + }); + if (host && host == window.location.host){ + var win = new Window(iframe.contentWindow); + var doc = new Document(iframe.contentWindow.document); + $extend(win.Element.prototype, Element.Prototype); + } + onload.call(iframe.contentWindow, iframe.contentWindow.document); + }; + (!window.frames[props.id]) ? iframe.addListener('load', onFrameLoad) : onFrameLoad(); + return iframe; + } + +}); + +var Elements = new Native({ + + initialize: function(elements, options){ + options = $extend({ddup: true, cash: true}, options); + elements = elements || []; + if (options.ddup || options.cash){ + var uniques = {}, returned = []; + for (var i = 0, l = elements.length; i < l; i++){ + var el = $.element(elements[i], !options.cash); + if (options.ddup){ + if (uniques[el.uid]) continue; + uniques[el.uid] = true; + } + returned.push(el); + } + elements = returned; + } + return (options.cash) ? $extend(elements, this) : elements; + } + +}); + +Elements.implement({ + + filter: function(filter, bind){ + if (!filter) return this; + return new Elements(Array.filter(this, (typeof filter == 'string') ? function(item){ + return item.match(filter); + } : filter, bind)); + } + +}); + +Elements.multi = function(property){ + return function(){ + var items = []; + var elements = true; + for (var i = 0, j = this.length; i < j; i++){ + var returns = this[i][property].apply(this[i], arguments); + items.push(returns); + if (elements) elements = ($type(returns) == 'element'); + } + return (elements) ? new Elements(items) : items; + }; +}; + +Window.implement({ + + $: function(el, nocash){ + if (el && el.$family && el.uid) return el; + var type = $type(el); + return ($[type]) ? $[type](el, nocash, this.document) : null; + }, + + $$: function(selector){ + if (arguments.length == 1 && typeof selector == 'string') return this.document.getElements(selector); + var elements = []; + var args = Array.flatten(arguments); + for (var i = 0, l = args.length; i < l; i++){ + var item = args[i]; + switch ($type(item)){ + case 'element': item = [item]; break; + case 'string': item = this.document.getElements(item, true); break; + default: item = false; + } + if (item) elements.extend(item); + } + return new Elements(elements); + }, + + getDocument: function(){ + return this.document; + }, + + getWindow: function(){ + return this; + } + +}); + +$.string = function(id, nocash, doc){ + id = doc.getElementById(id); + return (id) ? $.element(id, nocash) : null; +}; + +$.element = function(el, nocash){ + $uid(el); + if (!nocash && !el.$family && !(/^object|embed$/i).test(el.tagName)){ + var proto = Element.Prototype; + for (var p in proto) el[p] = proto[p]; + }; + return el; +}; + +$.object = function(obj, nocash, doc){ + if (obj.toElement) return $.element(obj.toElement(doc), nocash); + return null; +}; + +$.textnode = $.whitespace = $.window = $.document = $arguments(0); + +Native.implement([Element, Document], { + + getElement: function(selector, nocash){ + return $(this.getElements(selector, true)[0] || null, nocash); + }, + + getElements: function(tags, nocash){ + tags = tags.split(','); + var elements = []; + var ddup = (tags.length > 1); + tags.each(function(tag){ + var partial = this.getElementsByTagName(tag.trim()); + (ddup) ? elements.extend(partial) : elements = partial; + }, this); + return new Elements(elements, {ddup: ddup, cash: !nocash}); + } + +}); + +Element.Storage = { + + get: function(uid){ + return (this[uid] || (this[uid] = {})); + } + +}; + +Element.Inserters = new Hash({ + + before: function(context, element){ + if (element.parentNode) element.parentNode.insertBefore(context, element); + }, + + after: function(context, element){ + if (!element.parentNode) return; + var next = element.nextSibling; + (next) ? element.parentNode.insertBefore(context, next) : element.parentNode.appendChild(context); + }, + + bottom: function(context, element){ + element.appendChild(context); + }, + + top: function(context, element){ + var first = element.firstChild; + (first) ? element.insertBefore(context, first) : element.appendChild(context); + } + +}); + +Element.Inserters.inside = Element.Inserters.bottom; + +Element.Inserters.each(function(value, key){ + + var Key = key.capitalize(); + + Element.implement('inject' + Key, function(el){ + value(this, $(el, true)); + return this; + }); + + Element.implement('grab' + Key, function(el){ + value($(el, true), this); + return this; + }); + +}); + +Element.implement({ + + getDocument: function(){ + return this.ownerDocument; + }, + + getWindow: function(){ + return this.ownerDocument.getWindow(); + }, + + getElementById: function(id, nocash){ + var el = this.ownerDocument.getElementById(id); + if (!el) return null; + for (var parent = el.parentNode; parent != this; parent = parent.parentNode){ + if (!parent) return null; + } + return $.element(el, nocash); + }, + + set: function(prop, value){ + switch ($type(prop)){ + case 'object': + for (var p in prop) this.set(p, prop[p]); + break; + case 'string': + var property = Element.Properties.get(prop); + (property && property.set) ? property.set.apply(this, Array.slice(arguments, 1)) : this.setProperty(prop, value); + } + return this; + }, + + get: function(prop){ + var property = Element.Properties.get(prop); + return (property && property.get) ? property.get.apply(this, Array.slice(arguments, 1)) : this.getProperty(prop); + }, + + erase: function(prop){ + var property = Element.Properties.get(prop); + (property && property.erase) ? property.erase.apply(this, Array.slice(arguments, 1)) : this.removeProperty(prop); + return this; + }, + + match: function(tag){ + return (!tag || Element.get(this, 'tag') == tag); + }, + + inject: function(el, where){ + Element.Inserters.get(where || 'bottom')(this, $(el, true)); + return this; + }, + + wraps: function(el, where){ + el = $(el, true); + return this.replaces(el).grab(el, where); + }, + + grab: function(el, where){ + Element.Inserters.get(where || 'bottom')($(el, true), this); + return this; + }, + + appendText: function(text, where){ + return this.grab(this.getDocument().newTextNode(text), where); + }, + + adopt: function(){ + Array.flatten(arguments).each(function(element){ + element = $(element, true); + if (element) this.appendChild(element); + }, this); + return this; + }, + + dispose: function(){ + return (this.parentNode) ? this.parentNode.removeChild(this) : this; + }, + + clone: function(contents, keepid){ + switch ($type(this)){ + case 'element': + var attributes = {}; + for (var j = 0, l = this.attributes.length; j < l; j++){ + var attribute = this.attributes[j], key = attribute.nodeName.toLowerCase(); + if (Browser.Engine.trident && (/input/i).test(this.tagName) && (/width|height/).test(key)) continue; + var value = (key == 'style' && this.style) ? this.style.cssText : attribute.nodeValue; + if (!$chk(value) || key == 'uid' || (key == 'id' && !keepid)) continue; + if (value != 'inherit' && ['string', 'number'].contains($type(value))) attributes[key] = value; + } + var element = new Element(this.nodeName.toLowerCase(), attributes); + if (contents !== false){ + for (var i = 0, k = this.childNodes.length; i < k; i++){ + var child = Element.clone(this.childNodes[i], true, keepid); + if (child) element.grab(child); + } + } + return element; + case 'textnode': return document.newTextNode(this.nodeValue); + } + return null; + }, + + replaces: function(el){ + el = $(el, true); + el.parentNode.replaceChild(this, el); + return this; + }, + + hasClass: function(className){ + return this.className.contains(className, ' '); + }, + + addClass: function(className){ + if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean(); + return this; + }, + + removeClass: function(className){ + this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1').clean(); + return this; + }, + + toggleClass: function(className){ + return this.hasClass(className) ? this.removeClass(className) : this.addClass(className); + }, + + getComputedStyle: function(property){ + if (this.currentStyle) return this.currentStyle[property.camelCase()]; + var computed = this.getWindow().getComputedStyle(this, null); + return (computed) ? computed.getPropertyValue([property.hyphenate()]) : null; + }, + + empty: function(){ + $A(this.childNodes).each(function(node){ + Browser.freeMem(node); + Element.empty(node); + Element.dispose(node); + }, this); + return this; + }, + + destroy: function(){ + Browser.freeMem(this.empty().dispose()); + return null; + }, + + getSelected: function(){ + return new Elements($A(this.options).filter(function(option){ + return option.selected; + })); + }, + + toQueryString: function(){ + var queryString = []; + this.getElements('input, select, textarea').each(function(el){ + if (!el.name || el.disabled) return; + var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){ + return opt.value; + }) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value; + $splat(value).each(function(val){ + if (val) queryString.push(el.name + '=' + encodeURIComponent(val)); + }); + }); + return queryString.join('&'); + }, + + getProperty: function(attribute){ + var EA = Element.Attributes, key = EA.Props[attribute]; + var value = (key) ? this[key] : this.getAttribute(attribute, 2); + return (EA.Bools[attribute]) ? !!value : (key) ? value : value || null; + }, + + getProperties: function(){ + var args = $A(arguments); + return args.map(function(attr){ + return this.getProperty(attr); + }, this).associate(args); + }, + + setProperty: function(attribute, value){ + var EA = Element.Attributes, key = EA.Props[attribute], hasValue = $defined(value); + if (key && EA.Bools[attribute]) value = (value || !hasValue) ? true : false; + else if (!hasValue) return this.removeProperty(attribute); + (key) ? this[key] = value : this.setAttribute(attribute, value); + return this; + }, + + setProperties: function(attributes){ + for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]); + return this; + }, + + removeProperty: function(attribute){ + var EA = Element.Attributes, key = EA.Props[attribute], isBool = (key && EA.Bools[attribute]); + (key) ? this[key] = (isBool) ? false : '' : this.removeAttribute(attribute); + return this; + }, + + removeProperties: function(){ + Array.each(arguments, this.removeProperty, this); + return this; + } + +}); + +(function(){ + +var walk = function(element, walk, start, match, all, nocash){ + var el = element[start || walk]; + var elements = []; + while (el){ + if (el.nodeType == 1 && (!match || Element.match(el, match))){ + elements.push(el); + if (!all) break; + } + el = el[walk]; + } + return (all) ? new Elements(elements, {ddup: false, cash: !nocash}) : $(elements[0], nocash); +}; + +Element.implement({ + + getPrevious: function(match, nocash){ + return walk(this, 'previousSibling', null, match, false, nocash); + }, + + getAllPrevious: function(match, nocash){ + return walk(this, 'previousSibling', null, match, true, nocash); + }, + + getNext: function(match, nocash){ + return walk(this, 'nextSibling', null, match, false, nocash); + }, + + getAllNext: function(match, nocash){ + return walk(this, 'nextSibling', null, match, true, nocash); + }, + + getFirst: function(match, nocash){ + return walk(this, 'nextSibling', 'firstChild', match, false, nocash); + }, + + getLast: function(match, nocash){ + return walk(this, 'previousSibling', 'lastChild', match, false, nocash); + }, + + getParent: function(match, nocash){ + return walk(this, 'parentNode', null, match, false, nocash); + }, + + getParents: function(match, nocash){ + return walk(this, 'parentNode', null, match, true, nocash); + }, + + getChildren: function(match, nocash){ + return walk(this, 'nextSibling', 'firstChild', match, true, nocash); + }, + + hasChild: function(el){ + el = $(el, true); + return (!!el && $A(this.getElementsByTagName(el.tagName)).contains(el)); + } + +}); + +})(); + +Element.Properties = new Hash; + +Element.Properties.style = { + + set: function(style){ + this.style.cssText = style; + }, + + get: function(){ + return this.style.cssText; + }, + + erase: function(){ + this.style.cssText = ''; + } + +}; + +Element.Properties.tag = {get: function(){ + return this.tagName.toLowerCase(); +}}; + +Element.Properties.href = {get: function(){ + return (!this.href) ? null : this.href.replace(new RegExp('^' + document.location.protocol + '\/\/' + document.location.host), ''); +}}; + +Element.Properties.html = {set: function(){ + return this.innerHTML = Array.flatten(arguments).join(''); +}}; + +Native.implement([Element, Window, Document], { + + addListener: function(type, fn){ + if (this.addEventListener) this.addEventListener(type, fn, false); + else this.attachEvent('on' + type, fn); + return this; + }, + + removeListener: function(type, fn){ + if (this.removeEventListener) this.removeEventListener(type, fn, false); + else this.detachEvent('on' + type, fn); + return this; + }, + + retrieve: function(property, dflt){ + var storage = Element.Storage.get(this.uid); + var prop = storage[property]; + if ($defined(dflt) && !$defined(prop)) prop = storage[property] = dflt; + return $pick(prop); + }, + + store: function(property, value){ + var storage = Element.Storage.get(this.uid); + storage[property] = value; + return this; + }, + + eliminate: function(property){ + var storage = Element.Storage.get(this.uid); + delete storage[property]; + return this; + } + +}); + +Element.Attributes = new Hash({ + Props: {'html': 'innerHTML', 'class': 'className', 'for': 'htmlFor', 'text': (Browser.Engine.trident) ? 'innerText' : 'textContent'}, + Bools: ['compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readonly', 'multiple', 'selected', 'noresize', 'defer'], + Camels: ['value', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'maxLength', 'readOnly', 'rowSpan', 'tabIndex', 'useMap'] +}); + +Browser.freeMem = function(item){ + if (!item) return; + if (Browser.Engine.trident && (/object/i).test(item.tagName)){ + for (var p in item){ + if (typeof item[p] == 'function') item[p] = $empty; + } + Element.dispose(item); + } + if (item.uid && item.removeEvents) item.removeEvents(); +}; + +(function(EA){ + + var EAB = EA.Bools, EAC = EA.Camels; + EA.Bools = EAB = EAB.associate(EAB); + Hash.extend(Hash.combine(EA.Props, EAB), EAC.associate(EAC.map(function(v){ + return v.toLowerCase(); + }))); + EA.erase('Camels'); + +})(Element.Attributes); + +window.addListener('unload', function(){ + window.removeListener('unload', arguments.callee); + document.purge(); + if (Browser.Engine.trident) CollectGarbage(); +}); + +/* +Script: Element.Event.js + Contains Element methods for dealing with events, and custom Events. + +License: + MIT-style license. +*/ + +Element.Properties.events = {set: function(events){ + this.addEvents(events); +}}; + +Native.implement([Element, Window, Document], { + + addEvent: function(type, fn){ + var events = this.retrieve('events', {}); + events[type] = events[type] || {'keys': [], 'values': []}; + if (events[type].keys.contains(fn)) return this; + events[type].keys.push(fn); + var realType = type, custom = Element.Events.get(type), condition = fn, self = this; + if (custom){ + if (custom.onAdd) custom.onAdd.call(this, fn); + if (custom.condition){ + condition = function(event){ + if (custom.condition.call(this, event)) return fn.call(this, event); + return false; + }; + } + realType = custom.base || realType; + } + var defn = function(){ + return fn.call(self); + }; + var nativeEvent = Element.NativeEvents[realType] || 0; + if (nativeEvent){ + if (nativeEvent == 2){ + defn = function(event){ + event = new Event(event, self.getWindow()); + if (condition.call(self, event) === false) event.stop(); + }; + } + this.addListener(realType, defn); + } + events[type].values.push(defn); + return this; + }, + + removeEvent: function(type, fn){ + var events = this.retrieve('events'); + if (!events || !events[type]) return this; + var pos = events[type].keys.indexOf(fn); + if (pos == -1) return this; + var key = events[type].keys.splice(pos, 1)[0]; + var value = events[type].values.splice(pos, 1)[0]; + var custom = Element.Events.get(type); + if (custom){ + if (custom.onRemove) custom.onRemove.call(this, fn); + type = custom.base || type; + } + return (Element.NativeEvents[type]) ? this.removeListener(type, value) : this; + }, + + addEvents: function(events){ + for (var event in events) this.addEvent(event, events[event]); + return this; + }, + + removeEvents: function(type){ + var events = this.retrieve('events'); + if (!events) return this; + if (!type){ + for (var evType in events) this.removeEvents(evType); + events = null; + } else if (events[type]){ + while (events[type].keys[0]) this.removeEvent(type, events[type].keys[0]); + events[type] = null; + } + return this; + }, + + fireEvent: function(type, args, delay){ + var events = this.retrieve('events'); + if (!events || !events[type]) return this; + events[type].keys.each(function(fn){ + fn.create({'bind': this, 'delay': delay, 'arguments': args})(); + }, this); + return this; + }, + + cloneEvents: function(from, type){ + from = $(from); + var fevents = from.retrieve('events'); + if (!fevents) return this; + if (!type){ + for (var evType in fevents) this.cloneEvents(from, evType); + } else if (fevents[type]){ + fevents[type].keys.each(function(fn){ + this.addEvent(type, fn); + }, this); + } + return this; + } + +}); + +Element.NativeEvents = { + click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons + mousewheel: 2, DOMMouseScroll: 2, //mouse wheel + mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement + keydown: 2, keypress: 2, keyup: 2, //keyboard + focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements + load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window + error: 1, abort: 1, scroll: 1 //misc +}; + +(function(){ + +var $check = function(event){ + var related = event.relatedTarget; + if (related == undefined) return true; + if (related === false) return false; + return ($type(this) != 'document' && related != this && related.prefix != 'xul' && !this.hasChild(related)); +}; + +Element.Events = new Hash({ + + mouseenter: { + base: 'mouseover', + condition: $check + }, + + mouseleave: { + base: 'mouseout', + condition: $check + }, + + mousewheel: { + base: (Browser.Engine.gecko) ? 'DOMMouseScroll' : 'mousewheel' + } + +}); + +})(); + +/* +Script: Element.Style.js + Contains methods for interacting with the styles of Elements in a fashionable way. + +License: + MIT-style license. +*/ + +Element.Properties.styles = {set: function(styles){ + this.setStyles(styles); +}}; + +Element.Properties.opacity = { + + set: function(opacity, novisibility){ + if (!novisibility){ + if (opacity == 0){ + if (this.style.visibility != 'hidden') this.style.visibility = 'hidden'; + } else { + if (this.style.visibility != 'visible') this.style.visibility = 'visible'; + } + } + if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1; + if (Browser.Engine.trident) this.style.filter = (opacity == 1) ? '' : 'alpha(opacity=' + opacity * 100 + ')'; + this.style.opacity = opacity; + this.store('opacity', opacity); + }, + + get: function(){ + return this.retrieve('opacity', 1); + } + +}; + +Element.implement({ + + setOpacity: function(value){ + return this.set('opacity', value, true); + }, + + getOpacity: function(){ + return this.get('opacity'); + }, + + setStyle: function(property, value){ + switch (property){ + case 'opacity': return this.set('opacity', parseFloat(value)); + case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat'; + } + property = property.camelCase(); + if ($type(value) != 'string'){ + var map = (Element.Styles.get(property) || '@').split(' '); + value = $splat(value).map(function(val, i){ + if (!map[i]) return ''; + return ($type(val) == 'number') ? map[i].replace('@', Math.round(val)) : val; + }).join(' '); + } else if (value == String(Number(value))){ + value = Math.round(value); + } + this.style[property] = value; + return this; + }, + + getStyle: function(property){ + switch (property){ + case 'opacity': return this.get('opacity'); + case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat'; + } + property = property.camelCase(); + var result = this.style[property]; + if (!$chk(result)){ + result = []; + for (var style in Element.ShortStyles){ + if (property != style) continue; + for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s)); + return result.join(' '); + } + result = this.getComputedStyle(property); + } + if (result){ + result = String(result); + var color = result.match(/rgba?\([\d\s,]+\)/); + if (color) result = result.replace(color[0], color[0].rgbToHex()); + } + if (Browser.Engine.presto || (Browser.Engine.trident && !$chk(parseInt(result)))){ + if (property.test(/^(height|width)$/)){ + var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0; + values.each(function(value){ + size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt(); + }, this); + return this['offset' + property.capitalize()] - size + 'px'; + } + if (Browser.Engine.presto && String(result).test('px')) return result; + if (property.test(/(border(.+)Width|margin|padding)/)) return '0px'; + } + return result; + }, + + setStyles: function(styles){ + for (var style in styles) this.setStyle(style, styles[style]); + return this; + }, + + getStyles: function(){ + var result = {}; + Array.each(arguments, function(key){ + result[key] = this.getStyle(key); + }, this); + return result; + } + +}); + +Element.Styles = new Hash({ + left: '@px', top: '@px', bottom: '@px', right: '@px', + width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px', + backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)', + fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)', + margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)', + borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)', + zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@' +}); + +Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}}; + +['Top', 'Right', 'Bottom', 'Left'].each(function(direction){ + var Short = Element.ShortStyles; + var All = Element.Styles; + ['margin', 'padding'].each(function(style){ + var sd = style + direction; + Short[style][sd] = All[sd] = '@px'; + }); + var bd = 'border' + direction; + Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)'; + var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color'; + Short[bd] = {}; + Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px'; + Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@'; + Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)'; +}); + + +/* +Script: Element.Dimensions.js + Contains methods to work with size, scroll, or positioning of Elements and the window object. + +License: + MIT-style license. + +Credits: + - Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html). + - Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html). +*/ + +(function(){ + +Element.implement({ + + scrollTo: function(x, y){ + if (isBody(this)){ + this.getWindow().scrollTo(x, y); + } else { + this.scrollLeft = x; + this.scrollTop = y; + } + return this; + }, + + getSize: function(){ + if (isBody(this)) return this.getWindow().getSize(); + return {x: this.offsetWidth, y: this.offsetHeight}; + }, + + getScrollSize: function(){ + if (isBody(this)) return this.getWindow().getScrollSize(); + return {x: this.scrollWidth, y: this.scrollHeight}; + }, + + getScroll: function(){ + if (isBody(this)) return this.getWindow().getScroll(); + return {x: this.scrollLeft, y: this.scrollTop}; + }, + + getScrolls: function(){ + var element = this, position = {x: 0, y: 0}; + while (element && !isBody(element)){ + position.x += element.scrollLeft; + position.y += element.scrollTop; + element = element.parentNode; + } + return position; + }, + + getOffsetParent: function(){ + var element = this; + if (isBody(element)) return null; + if (!Browser.Engine.trident) return element.offsetParent; + while ((element = element.parentNode) && !isBody(element)){ + if (styleString(element, 'position') != 'static') return element; + } + return null; + }, + + getOffsets: function(){ + var element = this, position = {x: 0, y: 0}; + if (isBody(this)) return position; + + while (element && !isBody(element)){ + position.x += element.offsetLeft; + position.y += element.offsetTop; + + if (Browser.Engine.gecko){ + if (!borderBox(element)){ + position.x += leftBorder(element); + position.y += topBorder(element); + } + var parent = element.parentNode; + if (parent && styleString(parent, 'overflow') != 'visible'){ + position.x += leftBorder(parent); + position.y += topBorder(parent); + } + } else if (element != this && (Browser.Engine.trident || Browser.Engine.webkit)){ + position.x += leftBorder(element); + position.y += topBorder(element); + } + + element = element.offsetParent; + if (Browser.Engine.trident){ + while (element && !element.currentStyle.hasLayout) element = element.offsetParent; + } + } + if (Browser.Engine.gecko && !borderBox(this)){ + position.x -= leftBorder(this); + position.y -= topBorder(this); + } + return position; + }, + + getPosition: function(relative){ + if (isBody(this)) return {x: 0, y: 0}; + var offset = this.getOffsets(), scroll = this.getScrolls(); + var position = {x: offset.x - scroll.x, y: offset.y - scroll.y}; + var relativePosition = (relative && (relative = $(relative))) ? relative.getPosition() : {x: 0, y: 0}; + return {x: position.x - relativePosition.x, y: position.y - relativePosition.y}; + }, + + getCoordinates: function(element){ + if (isBody(this)) return this.getWindow().getCoordinates(); + var position = this.getPosition(element), size = this.getSize(); + var obj = {left: position.x, top: position.y, width: size.x, height: size.y}; + obj.right = obj.left + obj.width; + obj.bottom = obj.top + obj.height; + return obj; + }, + + computePosition: function(obj){ + return {left: obj.x - styleNumber(this, 'margin-left'), top: obj.y - styleNumber(this, 'margin-top')}; + }, + + position: function(obj){ + return this.setStyles(this.computePosition(obj)); + } + +}); + +Native.implement([Document, Window], { + + getSize: function(){ + var win = this.getWindow(); + if (Browser.Engine.presto || Browser.Engine.webkit) return {x: win.innerWidth, y: win.innerHeight}; + var doc = getCompatElement(this); + return {x: doc.clientWidth, y: doc.clientHeight}; + }, + + getScroll: function(){ + var win = this.getWindow(); + var doc = getCompatElement(this); + return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop}; + }, + + getScrollSize: function(){ + var doc = getCompatElement(this); + var min = this.getSize(); + return {x: Math.max(doc.scrollWidth, min.x), y: Math.max(doc.scrollHeight, min.y)}; + }, + + getPosition: function(){ + return {x: 0, y: 0}; + }, + + getCoordinates: function(){ + var size = this.getSize(); + return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x}; + } + +}); + +// private methods + +var styleString = Element.getComputedStyle; + +function styleNumber(element, style){ + return styleString(element, style).toInt() || 0; +}; + +function borderBox(element){ + return styleString(element, '-moz-box-sizing') == 'border-box'; +}; + +function topBorder(element){ + return styleNumber(element, 'border-top-width'); +}; + +function leftBorder(element){ + return styleNumber(element, 'border-left-width'); +}; + +function isBody(element){ + return (/^(?:body|html)$/i).test(element.tagName); +}; + +function getCompatElement(element){ + var doc = element.getDocument(); + return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; +}; + +})(); + +//aliases + +Native.implement([Window, Document, Element], { + + getHeight: function(){ + return this.getSize().y; + }, + + getWidth: function(){ + return this.getSize().x; + }, + + getScrollTop: function(){ + return this.getScroll().y; + }, + + getScrollLeft: function(){ + return this.getScroll().x; + }, + + getScrollHeight: function(){ + return this.getScrollSize().y; + }, + + getScrollWidth: function(){ + return this.getScrollSize().x; + }, + + getTop: function(){ + return this.getPosition().y; + }, + + getLeft: function(){ + return this.getPosition().x; + } + +}); + +/* +Script: Selectors.js + Adds advanced CSS Querying capabilities for targeting elements. Also includes pseudoselectors support. + +License: + MIT-style license. +*/ + +Native.implement([Document, Element], { + + getElements: function(expression, nocash){ + expression = expression.split(','); + var items, local = {}; + for (var i = 0, l = expression.length; i < l; i++){ + var selector = expression[i], elements = Selectors.Utils.search(this, selector, local); + if (i != 0 && elements.item) elements = $A(elements); + items = (i == 0) ? elements : (items.item) ? $A(items).concat(elements) : items.concat(elements); + } + return new Elements(items, {ddup: (expression.length > 1), cash: !nocash}); + } + +}); + +Element.implement({ + + match: function(selector){ + if (!selector) return true; + var tagid = Selectors.Utils.parseTagAndID(selector); + var tag = tagid[0], id = tagid[1]; + if (!Selectors.Filters.byID(this, id) || !Selectors.Filters.byTag(this, tag)) return false; + var parsed = Selectors.Utils.parseSelector(selector); + return (parsed) ? Selectors.Utils.filter(this, parsed, {}) : true; + } + +}); + +var Selectors = {Cache: {nth: {}, parsed: {}}}; + +Selectors.RegExps = { + id: (/#([\w-]+)/), + tag: (/^(\w+|\*)/), + quick: (/^(\w+|\*)$/), + splitter: (/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g), + combined: (/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)["']?(.*?)["']?)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g) +}; + +Selectors.Utils = { + + chk: function(item, uniques){ + if (!uniques) return true; + var uid = $uid(item); + if (!uniques[uid]) return uniques[uid] = true; + return false; + }, + + parseNthArgument: function(argument){ + if (Selectors.Cache.nth[argument]) return Selectors.Cache.nth[argument]; + var parsed = argument.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/); + if (!parsed) return false; + var inta = parseInt(parsed[1]); + var a = (inta || inta === 0) ? inta : 1; + var special = parsed[2] || false; + var b = parseInt(parsed[3]) || 0; + if (a != 0){ + b--; + while (b < 1) b += a; + while (b >= a) b -= a; + } else { + a = b; + special = 'index'; + } + switch (special){ + case 'n': parsed = {a: a, b: b, special: 'n'}; break; + case 'odd': parsed = {a: 2, b: 0, special: 'n'}; break; + case 'even': parsed = {a: 2, b: 1, special: 'n'}; break; + case 'first': parsed = {a: 0, special: 'index'}; break; + case 'last': parsed = {special: 'last-child'}; break; + case 'only': parsed = {special: 'only-child'}; break; + default: parsed = {a: (a - 1), special: 'index'}; + } + + return Selectors.Cache.nth[argument] = parsed; + }, + + parseSelector: function(selector){ + if (Selectors.Cache.parsed[selector]) return Selectors.Cache.parsed[selector]; + var m, parsed = {classes: [], pseudos: [], attributes: []}; + while ((m = Selectors.RegExps.combined.exec(selector))){ + var cn = m[1], an = m[2], ao = m[3], av = m[4], pn = m[5], pa = m[6]; + if (cn){ + parsed.classes.push(cn); + } else if (pn){ + var parser = Selectors.Pseudo.get(pn); + if (parser) parsed.pseudos.push({parser: parser, argument: pa}); + else parsed.attributes.push({name: pn, operator: '=', value: pa}); + } else if (an){ + parsed.attributes.push({name: an, operator: ao, value: av}); + } + } + if (!parsed.classes.length) delete parsed.classes; + if (!parsed.attributes.length) delete parsed.attributes; + if (!parsed.pseudos.length) delete parsed.pseudos; + if (!parsed.classes && !parsed.attributes && !parsed.pseudos) parsed = null; + return Selectors.Cache.parsed[selector] = parsed; + }, + + parseTagAndID: function(selector){ + var tag = selector.match(Selectors.RegExps.tag); + var id = selector.match(Selectors.RegExps.id); + return [(tag) ? tag[1] : '*', (id) ? id[1] : false]; + }, + + filter: function(item, parsed, local){ + var i; + if (parsed.classes){ + for (i = parsed.classes.length; i--; i){ + var cn = parsed.classes[i]; + if (!Selectors.Filters.byClass(item, cn)) return false; + } + } + if (parsed.attributes){ + for (i = parsed.attributes.length; i--; i){ + var att = parsed.attributes[i]; + if (!Selectors.Filters.byAttribute(item, att.name, att.operator, att.value)) return false; + } + } + if (parsed.pseudos){ + for (i = parsed.pseudos.length; i--; i){ + var psd = parsed.pseudos[i]; + if (!Selectors.Filters.byPseudo(item, psd.parser, psd.argument, local)) return false; + } + } + return true; + }, + + getByTagAndID: function(ctx, tag, id){ + if (id){ + var item = (ctx.getElementById) ? ctx.getElementById(id, true) : Element.getElementById(ctx, id, true); + return (item && Selectors.Filters.byTag(item, tag)) ? [item] : []; + } else { + return ctx.getElementsByTagName(tag); + } + }, + + search: function(self, expression, local){ + var splitters = []; + + var selectors = expression.trim().replace(Selectors.RegExps.splitter, function(m0, m1, m2){ + splitters.push(m1); + return ':)' + m2; + }).split(':)'); + + var items, match, filtered, item; + + for (var i = 0, l = selectors.length; i < l; i++){ + + var selector = selectors[i]; + + if (i == 0 && Selectors.RegExps.quick.test(selector)){ + items = self.getElementsByTagName(selector); + continue; + } + + var splitter = splitters[i - 1]; + + var tagid = Selectors.Utils.parseTagAndID(selector); + var tag = tagid[0], id = tagid[1]; + + if (i == 0){ + items = Selectors.Utils.getByTagAndID(self, tag, id); + } else { + var uniques = {}, found = []; + for (var j = 0, k = items.length; j < k; j++) found = Selectors.Getters[splitter](found, items[j], tag, id, uniques); + items = found; + } + + var parsed = Selectors.Utils.parseSelector(selector); + + if (parsed){ + filtered = []; + for (var m = 0, n = items.length; m < n; m++){ + item = items[m]; + if (Selectors.Utils.filter(item, parsed, local)) filtered.push(item); + } + items = filtered; + } + + } + + return items; + + } + +}; + +Selectors.Getters = { + + ' ': function(found, self, tag, id, uniques){ + var items = Selectors.Utils.getByTagAndID(self, tag, id); + for (var i = 0, l = items.length; i < l; i++){ + var item = items[i]; + if (Selectors.Utils.chk(item, uniques)) found.push(item); + } + return found; + }, + + '>': function(found, self, tag, id, uniques){ + var children = Selectors.Utils.getByTagAndID(self, tag, id); + for (var i = 0, l = children.length; i < l; i++){ + var child = children[i]; + if (child.parentNode == self && Selectors.Utils.chk(child, uniques)) found.push(child); + } + return found; + }, + + '+': function(found, self, tag, id, uniques){ + while ((self = self.nextSibling)){ + if (self.nodeType == 1){ + if (Selectors.Utils.chk(self, uniques) && Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); + break; + } + } + return found; + }, + + '~': function(found, self, tag, id, uniques){ + + while ((self = self.nextSibling)){ + if (self.nodeType == 1){ + if (!Selectors.Utils.chk(self, uniques)) break; + if (Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); + } + } + return found; + } + +}; + +Selectors.Filters = { + + byTag: function(self, tag){ + return (tag == '*' || (self.tagName && self.tagName.toLowerCase() == tag)); + }, + + byID: function(self, id){ + return (!id || (self.id && self.id == id)); + }, + + byClass: function(self, klass){ + return (self.className && self.className.contains(klass, ' ')); + }, + + byPseudo: function(self, parser, argument, local){ + return parser.call(self, argument, local); + }, + + byAttribute: function(self, name, operator, value){ + var result = Element.prototype.getProperty.call(self, name); + if (!result) return false; + if (!operator || value == undefined) return true; + switch (operator){ + case '=': return (result == value); + case '*=': return (result.contains(value)); + case '^=': return (result.substr(0, value.length) == value); + case '$=': return (result.substr(result.length - value.length) == value); + case '!=': return (result != value); + case '~=': return result.contains(value, ' '); + case '|=': return result.contains(value, '-'); + } + return false; + } + +}; + +Selectors.Pseudo = new Hash({ + + // w3c pseudo selectors + + empty: function(){ + return !(this.innerText || this.textContent || '').length; + }, + + not: function(selector){ + return !Element.match(this, selector); + }, + + contains: function(text){ + return (this.innerText || this.textContent || '').contains(text); + }, + + 'first-child': function(){ + return Selectors.Pseudo.index.call(this, 0); + }, + + 'last-child': function(){ + var element = this; + while ((element = element.nextSibling)){ + if (element.nodeType == 1) return false; + } + return true; + }, + + 'only-child': function(){ + var prev = this; + while ((prev = prev.previousSibling)){ + if (prev.nodeType == 1) return false; + } + var next = this; + while ((next = next.nextSibling)){ + if (next.nodeType == 1) return false; + } + return true; + }, + + 'nth-child': function(argument, local){ + argument = (argument == undefined) ? 'n' : argument; + var parsed = Selectors.Utils.parseNthArgument(argument); + if (parsed.special != 'n') return Selectors.Pseudo[parsed.special].call(this, parsed.a, local); + var count = 0; + local.positions = local.positions || {}; + var uid = $uid(this); + if (!local.positions[uid]){ + var self = this; + while ((self = self.previousSibling)){ + if (self.nodeType != 1) continue; + count ++; + var position = local.positions[$uid(self)]; + if (position != undefined){ + count = position + count; + break; + } + } + local.positions[uid] = count; + } + return (local.positions[uid] % parsed.a == parsed.b); + }, + + // custom pseudo selectors + + index: function(index){ + var element = this, count = 0; + while ((element = element.previousSibling)){ + if (element.nodeType == 1 && ++count > index) return false; + } + return (count == index); + }, + + even: function(argument, local){ + return Selectors.Pseudo['nth-child'].call(this, '2n+1', local); + }, + + odd: function(argument, local){ + return Selectors.Pseudo['nth-child'].call(this, '2n', local); + } + +}); + +/* +Script: Domready.js + Contains the domready custom event. + +License: + MIT-style license. +*/ + +Element.Events.domready = { + + onAdd: function(fn){ + if (Browser.loaded) fn.call(this); + } + +}; + +(function(){ + + var domready = function(){ + if (Browser.loaded) return; + Browser.loaded = true; + window.fireEvent('domready'); + document.fireEvent('domready'); + }; + + switch (Browser.Engine.name){ + + case 'webkit': (function(){ + (['loaded', 'complete'].contains(document.readyState)) ? domready() : arguments.callee.delay(50); + })(); break; + + case 'trident': + var temp = document.createElement('div'); + (function(){ + ($try(function(){ + temp.doScroll('left'); + return $(temp).inject(document.body).set('html', 'temp').dispose(); + })) ? domready() : arguments.callee.delay(50); + })(); + break; + + default: + window.addEvent('load', domready); + document.addEvent('DOMContentLoaded', domready); + + } + +})(); + +/* +Script: JSON.js + JSON encoder and decoder. + +License: + MIT-style license. + +See Also: + <http://www.json.org/> +*/ + +var JSON = new Hash({ + + encode: function(obj){ + switch ($type(obj)){ + case 'string': + return '"' + obj.replace(/[\x00-\x1f\\"]/g, JSON.$replaceChars) + '"'; + case 'array': + return '[' + String(obj.map(JSON.encode).filter($defined)) + ']'; + case 'object': case 'hash': + var string = []; + Hash.each(obj, function(value, key){ + var json = JSON.encode(value); + if (json) string.push(JSON.encode(key) + ':' + json); + }); + return '{' + string + '}'; + case 'number': case 'boolean': return String(obj); + case false: return 'null'; + } + return null; + }, + + $specialChars: {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'}, + + $replaceChars: function(chr){ + return JSON.$specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16); + }, + + decode: function(string, secure){ + if ($type(string) != 'string' || !string.length) return null; + if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null; + return eval('(' + string + ')'); + } + +}); + +Native.implement([Hash, Array, String, Number], { + + toJSON: function(){ + return JSON.encode(this); + } + +}); + + +/* +Script: Cookie.js + Class for creating, loading, and saving browser Cookies. + +License: + MIT-style license. + +Credits: + Based on the functions by Peter-Paul Koch (http://quirksmode.org). +*/ + +var Cookie = new Class({ + + Implements: Options, + + options: { + path: false, + domain: false, + duration: false, + secure: false, + document: document + }, + + initialize: function(key, options){ + this.key = key; + this.setOptions(options); + }, + + write: function(value){ + value = encodeURIComponent(value); + if (this.options.domain) value += '; domain=' + this.options.domain; + if (this.options.path) value += '; path=' + this.options.path; + if (this.options.duration){ + var date = new Date(); + date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000); + value += '; expires=' + date.toGMTString(); + } + if (this.options.secure) value += '; secure'; + this.options.document.cookie = this.key + '=' + value; + return this; + }, + + read: function(){ + var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)'); + return (value) ? decodeURIComponent(value[1]) : null; + }, + + dispose: function(){ + new Cookie(this.key, $merge(this.options, {duration: -1})).write(''); + return this; + } + +}); + +Cookie.write = function(key, value, options){ + return new Cookie(key, options).write(value); +}; + +Cookie.read = function(key){ + return new Cookie(key).read(); +}; + +Cookie.dispose = function(key, options){ + return new Cookie(key, options).dispose(); +}; + +/* +Script: Swiff.js + Wrapper for embedding SWF movies. Supports (and fixes) External Interface Communication. + +License: + MIT-style license. + +Credits: + Flash detection & Internet Explorer + Flash Player 9 fix inspired by SWFObject. +*/ + +var Swiff = new Class({ + + Implements: [Options], + + options: { + id: null, + height: 1, + width: 1, + container: null, + properties: {}, + params: { + quality: 'high', + allowScriptAccess: 'always', + wMode: 'transparent', + swLiveConnect: true + }, + callBacks: {}, + vars: {} + }, + + toElement: function(){ + return this.object; + }, + + initialize: function(path, options){ + this.instance = 'Swiff_' + $time(); + + this.setOptions(options); + options = this.options; + var id = this.id = options.id || this.instance; + var container = $(options.container); + + Swiff.CallBacks[this.instance] = {}; + + var params = options.params, vars = options.vars, callBacks = options.callBacks; + var properties = $extend({height: options.height, width: options.width}, options.properties); + + var self = this; + + for (var callBack in callBacks){ + Swiff.CallBacks[this.instance][callBack] = (function(option){ + return function(){ + return option.apply(self.object, arguments); + }; + })(callBacks[callBack]); + vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack; + } + + params.flashVars = Hash.toQueryString(vars); + if (Browser.Engine.trident){ + properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; + params.movie = path; + } else { + properties.type = 'application/x-shockwave-flash'; + properties.data = path; + } + var build = '<object id="' + id + '"'; + for (var property in properties) build += ' ' + property + '="' + properties[property] + '"'; + build += '>'; + for (var param in params){ + if (params[param]) build += '<param name="' + param + '" value="' + params[param] + '" />'; + } + build += '</object>'; + this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild; + }, + + replaces: function(element){ + element = $(element, true); + element.parentNode.replaceChild(this.toElement(), element); + return this; + }, + + inject: function(element){ + $(element, true).appendChild(this.toElement()); + return this; + }, + + remote: function(){ + return Swiff.remote.apply(Swiff, [this.toElement()].extend(arguments)); + } + +}); + +Swiff.CallBacks = {}; + +Swiff.remote = function(obj, fn){ + var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + __flash__argumentsToXML(arguments, 2) + '</invoke>'); + return eval(rs); +}; + +/* +Script: Fx.js + Contains the basic animation logic to be extended by all other Fx Classes. + +License: + MIT-style license. +*/ + +var Fx = new Class({ + + Implements: [Chain, Events, Options], + + options: { + /* + onStart: $empty, + onCancel: $empty, + onComplete: $empty, + */ + fps: 50, + unit: false, + duration: 500, + link: 'ignore', + transition: function(p){ + return -(Math.cos(Math.PI * p) - 1) / 2; + } + }, + + initialize: function(options){ + this.subject = this.subject || this; + this.setOptions(options); + this.options.duration = Fx.Durations[this.options.duration] || this.options.duration.toInt(); + var wait = this.options.wait; + if (wait === false) this.options.link = 'cancel'; + }, + + step: function(){ + var time = $time(); + if (time < this.time + this.options.duration){ + var delta = this.options.transition((time - this.time) / this.options.duration); + this.set(this.compute(this.from, this.to, delta)); + } else { + this.set(this.compute(this.from, this.to, 1)); + this.complete(); + } + }, + + set: function(now){ + return now; + }, + + compute: function(from, to, delta){ + return Fx.compute(from, to, delta); + }, + + check: function(caller){ + if (!this.timer) return true; + switch (this.options.link){ + case 'cancel': this.cancel(); return true; + case 'chain': this.chain(caller.bind(this, Array.slice(arguments, 1))); return false; + } + return false; + }, + + start: function(from, to){ + if (!this.check(arguments.callee, from, to)) return this; + this.from = from; + this.to = to; + this.time = 0; + this.startTimer(); + this.onStart(); + return this; + }, + + complete: function(){ + if (this.stopTimer()) this.onComplete(); + return this; + }, + + cancel: function(){ + if (this.stopTimer()) this.onCancel(); + return this; + }, + + onStart: function(){ + this.fireEvent('start', this.subject); + }, + + onComplete: function(){ + this.fireEvent('complete', this.subject); + if (!this.callChain()) this.fireEvent('chainComplete', this.subject); + }, + + onCancel: function(){ + this.fireEvent('cancel', this.subject).clearChain(); + }, + + pause: function(){ + this.stopTimer(); + return this; + }, + + resume: function(){ + this.startTimer(); + return this; + }, + + stopTimer: function(){ + if (!this.timer) return false; + this.time = $time() - this.time; + this.timer = $clear(this.timer); + return true; + }, + + startTimer: function(){ + if (this.timer) return false; + this.time = $time() - this.time; + this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this); + return true; + } + +}); + +Fx.compute = function(from, to, delta){ + return (to - from) * delta + from; +}; + +Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000}; + + +/* +Script: Fx.CSS.js + Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements. + +License: + MIT-style license. +*/ + +Fx.CSS = new Class({ + + Extends: Fx, + + //prepares the base from/to object + + prepare: function(element, property, values){ + values = $splat(values); + var values1 = values[1]; + if (!$chk(values1)){ + values[1] = values[0]; + values[0] = element.getStyle(property); + } + var parsed = values.map(this.parse); + return {from: parsed[0], to: parsed[1]}; + }, + + //parses a value into an array + + parse: function(value){ + value = $lambda(value)(); + value = (typeof value == 'string') ? value.split(' ') : $splat(value); + return value.map(function(val){ + val = String(val); + var found = false; + Fx.CSS.Parsers.each(function(parser, key){ + if (found) return; + var parsed = parser.parse(val); + if ($chk(parsed)) found = {value: parsed, parser: parser}; + }); + found = found || {value: val, parser: Fx.CSS.Parsers.String}; + return found; + }); + }, + + //computes by a from and to prepared objects, using their parsers. + + compute: function(from, to, delta){ + var computed = []; + (Math.min(from.length, to.length)).times(function(i){ + computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser}); + }); + computed.$family = {name: 'fx:css:value'}; + return computed; + }, + + //serves the value as settable + + serve: function(value, unit){ + if ($type(value) != 'fx:css:value') value = this.parse(value); + var returned = []; + value.each(function(bit){ + returned = returned.concat(bit.parser.serve(bit.value, unit)); + }); + return returned; + }, + + //renders the change to an element + + render: function(element, property, value, unit){ + element.setStyle(property, this.serve(value, unit)); + }, + + //searches inside the page css to find the values for a selector + + search: function(selector){ + if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector]; + var to = {}; + Array.each(document.styleSheets, function(sheet, j){ + var href = sheet.href; + if (href && href.contains('://') && !href.contains(document.domain)) return; + var rules = sheet.rules || sheet.cssRules; + Array.each(rules, function(rule, i){ + if (!rule.style) return; + var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){ + return m.toLowerCase(); + }) : null; + if (!selectorText || !selectorText.test('^' + selector + '$')) return; + Element.Styles.each(function(value, style){ + if (!rule.style[style] || Element.ShortStyles[style]) return; + value = String(rule.style[style]); + to[style] = (value.test(/^rgb/)) ? value.rgbToHex() : value; + }); + }); + }); + return Fx.CSS.Cache[selector] = to; + } + +}); + +Fx.CSS.Cache = {}; + +Fx.CSS.Parsers = new Hash({ + + Color: { + parse: function(value){ + if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true); + return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false; + }, + compute: function(from, to, delta){ + return from.map(function(value, i){ + return Math.round(Fx.compute(from[i], to[i], delta)); + }); + }, + serve: function(value){ + return value.map(Number); + } + }, + + Number: { + parse: parseFloat, + compute: Fx.compute, + serve: function(value, unit){ + return (unit) ? value + unit : value; + } + }, + + String: { + parse: $lambda(false), + compute: $arguments(1), + serve: $arguments(0) + } + +}); + + +/* +Script: Fx.Tween.js + Formerly Fx.Style, effect to transition any CSS property for an element. + +License: + MIT-style license. +*/ + +Fx.Tween = new Class({ + + Extends: Fx.CSS, + + initialize: function(element, options){ + this.element = this.subject = $(element); + this.parent(options); + }, + + set: function(property, now){ + if (arguments.length == 1){ + now = property; + property = this.property || this.options.property; + } + this.render(this.element, property, now, this.options.unit); + return this; + }, + + start: function(property, from, to){ + if (!this.check(arguments.callee, property, from, to)) return this; + var args = Array.flatten(arguments); + this.property = this.options.property || args.shift(); + var parsed = this.prepare(this.element, this.property, args); + return this.parent(parsed.from, parsed.to); + } + +}); + +Element.Properties.tween = { + + set: function(options){ + var tween = this.retrieve('tween'); + if (tween) tween.cancel(); + return this.eliminate('tween').store('tween:options', $extend({link: 'cancel'}, options)); + }, + + get: function(options){ + if (options || !this.retrieve('tween')){ + if (options || !this.retrieve('tween:options')) this.set('tween', options); + this.store('tween', new Fx.Tween(this, this.retrieve('tween:options'))); + } + return this.retrieve('tween'); + } + +}; + +Element.implement({ + + tween: function(property, from, to){ + this.get('tween').start(arguments); + return this; + }, + + fade: function(how){ + var fade = this.get('tween'), o = 'opacity', toggle; + how = $pick(how, 'toggle'); + switch (how){ + case 'in': fade.start(o, 1); break; + case 'out': fade.start(o, 0); break; + case 'show': fade.set(o, 1); break; + case 'hide': fade.set(o, 0); break; + case 'toggle': + var flag = this.retrieve('fade:flag', this.get('opacity') == 1); + fade.start(o, (flag) ? 0 : 1); + this.store('fade:flag', !flag); + toggle = true; + break; + default: fade.start(o, arguments); + } + if (!toggle) this.eliminate('fade:flag'); + return this; + }, + + highlight: function(start, end){ + if (!end){ + end = this.retrieve('highlight:original', this.getStyle('background-color')); + end = (end == 'transparent') ? '#fff' : end; + } + var tween = this.get('tween'); + tween.start('background-color', start || '#ffff88', end).chain(function(){ + this.setStyle('background-color', this.retrieve('highlight:original')); + tween.callChain(); + }.bind(this)); + return this; + } + +}); + + +/* +Script: Fx.Morph.js + Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules. + +License: + MIT-style license. +*/ + +Fx.Morph = new Class({ + + Extends: Fx.CSS, + + initialize: function(element, options){ + this.element = this.subject = $(element); + this.parent(options); + }, + + set: function(now){ + if (typeof now == 'string') now = this.search(now); + for (var p in now) this.render(this.element, p, now[p], this.options.unit); + return this; + }, + + compute: function(from, to, delta){ + var now = {}; + for (var p in from) now[p] = this.parent(from[p], to[p], delta); + return now; + }, + + start: function(properties){ + if (!this.check(arguments.callee, properties)) return this; + if (typeof properties == 'string') properties = this.search(properties); + var from = {}, to = {}; + for (var p in properties){ + var parsed = this.prepare(this.element, p, properties[p]); + from[p] = parsed.from; + to[p] = parsed.to; + } + return this.parent(from, to); + } + +}); + +Element.Properties.morph = { + + set: function(options){ + var morph = this.retrieve('morph'); + if (morph) morph.cancel(); + return this.eliminate('morph').store('morph:options', $extend({link: 'cancel'}, options)); + }, + + get: function(options){ + if (options || !this.retrieve('morph')){ + if (options || !this.retrieve('morph:options')) this.set('morph', options); + this.store('morph', new Fx.Morph(this, this.retrieve('morph:options'))); + } + return this.retrieve('morph'); + } + +}; + +Element.implement({ + + morph: function(props){ + this.get('morph').start(props); + return this; + } + +}); + +/* +Script: Fx.Transitions.js + Contains a set of advanced transitions to be used with any of the Fx Classes. + +License: + MIT-style license. + +Credits: + Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools. +*/ + +(function(){ + + var old = Fx.prototype.initialize; + + Fx.prototype.initialize = function(options){ + old.call(this, options); + var trans = this.options.transition; + if (typeof trans == 'string' && (trans = trans.split(':'))){ + var base = Fx.Transitions; + base = base[trans[0]] || base[trans[0].capitalize()]; + if (trans[1]) base = base['ease' + trans[1].capitalize() + (trans[2] ? trans[2].capitalize() : '')]; + this.options.transition = base; + } + }; + +})(); + +Fx.Transition = function(transition, params){ + params = $splat(params); + return $extend(transition, { + easeIn: function(pos){ + return transition(pos, params); + }, + easeOut: function(pos){ + return 1 - transition(1 - pos, params); + }, + easeInOut: function(pos){ + return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2; + } + }); +}; + +Fx.Transitions = new Hash({ + + linear: $arguments(0) + +}); + +Fx.Transitions.extend = function(transitions){ + for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]); +}; + +Fx.Transitions.extend({ + + Pow: function(p, x){ + return Math.pow(p, x[0] || 6); + }, + + Expo: function(p){ + return Math.pow(2, 8 * (p - 1)); + }, + + Circ: function(p){ + return 1 - Math.sin(Math.acos(p)); + }, + + Sine: function(p){ + return 1 - Math.sin((1 - p) * Math.PI / 2); + }, + + Back: function(p, x){ + x = x[0] || 1.618; + return Math.pow(p, 2) * ((x + 1) * p - x); + }, + + Bounce: function(p){ + var value; + for (var a = 0, b = 1; 1; a += b, b /= 2){ + if (p >= (7 - 4 * a) / 11){ + value = - Math.pow((11 - 6 * a - 11 * p) / 4, 2) + b * b; + break; + } + } + return value; + }, + + Elastic: function(p, x){ + return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3); + } + +}); + +['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){ + Fx.Transitions[transition] = new Fx.Transition(function(p){ + return Math.pow(p, [i + 2]); + }); +}); + + +/* +Script: Request.js + Powerful all purpose Request Class. Uses XMLHTTPRequest. + +License: + MIT-style license. +*/ + +var Request = new Class({ + + Implements: [Chain, Events, Options], + + options: { + /*onRequest: $empty, + onSuccess: $empty, + onFailure: $empty, + onException: $empty,*/ + url: '', + data: '', + headers: { + 'X-Requested-With': 'XMLHttpRequest', + 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' + }, + async: true, + format: false, + method: 'post', + link: 'ignore', + isSuccess: null, + emulation: true, + urlEncoded: true, + encoding: 'utf-8', + evalScripts: false, + evalResponse: false + }, + + initialize: function(options){ + this.xhr = new Browser.Request(); + this.setOptions(options); + this.options.isSuccess = this.options.isSuccess || this.isSuccess; + this.headers = new Hash(this.options.headers); + }, + + onStateChange: function(){ + if (this.xhr.readyState != 4 || !this.running) return; + this.running = false; + this.status = 0; + $try(function(){ + this.status = this.xhr.status; + }.bind(this)); + if (this.options.isSuccess.call(this, this.status)){ + this.response = {text: this.xhr.responseText, xml: this.xhr.responseXML}; + this.success(this.response.text, this.response.xml); + } else { + this.response = {text: null, xml: null}; + this.failure(); + } + this.xhr.onreadystatechange = $empty; + }, + + isSuccess: function(){ + return ((this.status >= 200) && (this.status < 300)); + }, + + processScripts: function(text){ + if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text); + return text.stripScripts(this.options.evalScripts); + }, + + success: function(text, xml){ + this.onSuccess(this.processScripts(text), xml); + }, + + onSuccess: function(){ + this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain(); + }, + + failure: function(){ + this.onFailure(); + }, + + onFailure: function(){ + this.fireEvent('complete').fireEvent('failure', this.xhr); + }, + + setHeader: function(name, value){ + this.headers.set(name, value); + return this; + }, + + getHeader: function(name){ + return $try(function(){ + return this.xhr.getResponseHeader(name); + }.bind(this)); + }, + + check: function(caller){ + if (!this.running) return true; + switch (this.options.link){ + case 'cancel': this.cancel(); return true; + case 'chain': this.chain(caller.bind(this, Array.slice(arguments, 1))); return false; + } + return false; + }, + + send: function(options){ + if (!this.check(arguments.callee, options)) return this; + this.running = true; + + var type = $type(options); + if (type == 'string' || type == 'element') options = {data: options}; + + var old = this.options; + options = $extend({data: old.data, url: old.url, method: old.method}, options); + var data = options.data, url = options.url, method = options.method; + + switch ($type(data)){ + case 'element': data = $(data).toQueryString(); break; + case 'object': case 'hash': data = Hash.toQueryString(data); + } + + if (this.options.format){ + var format = 'format=' + this.options.format; + data = (data) ? format + '&' + data : format; + } + + if (this.options.emulation && ['put', 'delete'].contains(method)){ + var _method = '_method=' + method; + data = (data) ? _method + '&' + data : _method; + method = 'post'; + } + + if (this.options.urlEncoded && method == 'post'){ + var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : ''; + this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding); + } + + if (data && method == 'get'){ + url = url + (url.contains('?') ? '&' : '?') + data; + data = null; + } + + this.xhr.open(method.toUpperCase(), url, this.options.async); + + this.xhr.onreadystatechange = this.onStateChange.bind(this); + + this.headers.each(function(value, key){ + if (!$try(function(){ + this.xhr.setRequestHeader(key, value); + return true; + }.bind(this))) this.fireEvent('exception', [key, value]); + }, this); + + this.fireEvent('request'); + this.xhr.send(data); + if (!this.options.async) this.onStateChange(); + return this; + }, + + cancel: function(){ + if (!this.running) return this; + this.running = false; + this.xhr.abort(); + this.xhr.onreadystatechange = $empty; + this.xhr = new Browser.Request(); + this.fireEvent('cancel'); + return this; + } + +}); + +(function(){ + +var methods = {}; +['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){ + methods[method] = function(){ + var params = Array.link(arguments, {url: String.type, data: $defined}); + return this.send($extend(params, {method: method.toLowerCase()})); + }; +}); + +Request.implement(methods); + +})(); + +Element.Properties.send = { + + set: function(options){ + var send = this.retrieve('send'); + if (send) send.cancel(); + return this.eliminate('send').store('send:options', $extend({ + data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action') + }, options)); + }, + + get: function(options){ + if (options || !this.retrieve('send')){ + if (options || !this.retrieve('send:options')) this.set('send', options); + this.store('send', new Request(this.retrieve('send:options'))); + } + return this.retrieve('send'); + } + +}; + +Element.implement({ + + send: function(url){ + var sender = this.get('send'); + sender.send({data: this, url: url || sender.options.url}); + return this; + } + +}); + + +/* +Script: Request.HTML.js + Extends the basic Request Class with additional methods for interacting with HTML responses. + +License: + MIT-style license. +*/ + +Request.HTML = new Class({ + + Extends: Request, + + options: { + update: false, + evalScripts: true, + filter: false + }, + + processHTML: function(text){ + var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i); + text = (match) ? match[1] : text; + + var container = new Element('div'); + + return $try(function(){ + var root = '<root>' + text + '</root>', doc; + if (Browser.Engine.trident){ + doc = new ActiveXObject('Microsoft.XMLDOM'); + doc.async = false; + doc.loadXML(root); + } else { + doc = new DOMParser().parseFromString(root, 'text/xml'); + } + root = doc.getElementsByTagName('root')[0]; + for (var i = 0, k = root.childNodes.length; i < k; i++){ + var child = Element.clone(root.childNodes[i], true, true); + if (child) container.grab(child); + } + return container; + }) || container.set('html', text); + }, + + success: function(text){ + var options = this.options, response = this.response; + + response.html = text.stripScripts(function(script){ + response.javascript = script; + }); + + var temp = this.processHTML(response.html); + + response.tree = temp.childNodes; + response.elements = temp.getElements('*'); + + if (options.filter) response.tree = response.elements.filter(options.filter); + if (options.update) $(options.update).empty().adopt(response.tree); + if (options.evalScripts) $exec(response.javascript); + + this.onSuccess(response.tree, response.elements, response.html, response.javascript); + } + +}); + +Element.Properties.load = { + + set: function(options){ + var load = this.retrieve('load'); + if (load) send.cancel(); + return this.eliminate('load').store('load:options', $extend({data: this, link: 'cancel', update: this, method: 'get'}, options)); + }, + + get: function(options){ + if (options || ! this.retrieve('load')){ + if (options || !this.retrieve('load:options')) this.set('load', options); + this.store('load', new Request.HTML(this.retrieve('load:options'))); + } + return this.retrieve('load'); + } + +}; + +Element.implement({ + + load: function(){ + this.get('load').send(Array.link(arguments, {data: Object.type, url: String.type})); + return this; + } + +}); + + +/* +Script: Request.JSON.js + Extends the basic Request Class with additional methods for sending and receiving JSON data. + +License: + MIT-style license. +*/ + +Request.JSON = new Class({ + + Extends: Request, + + options: { + secure: true + }, + + initialize: function(options){ + this.parent(options); + this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'}); + }, + + success: function(text){ + this.response.json = JSON.decode(text, this.options.secure); + this.onSuccess(this.response.json, text); + } + +}); diff --git a/static/mootools-1.2-more.js b/static/mootools-1.2-more.js new file mode 100644 index 0000000..64f68ac --- /dev/null +++ b/static/mootools-1.2-more.js @@ -0,0 +1,240 @@ +//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License. + +/* +Script: Drag.js + The base Drag Class. Can be used to drag and resize Elements using mouse events. + +License: + MIT-style license. +*/ + +var Drag = new Class({ + + Implements: [Events, Options], + + options: {/* + onBeforeStart: $empty, + onStart: $empty, + onDrag: $empty, + onCancel: $empty, + onComplete: $empty,*/ + snap: 6, + unit: 'px', + grid: false, + style: true, + limit: false, + handle: false, + invert: false, + preventDefault: false, + modifiers: {x: 'left', y: 'top'} + }, + + initialize: function(){ + var params = Array.link(arguments, {'options': Object.type, 'element': $defined}); + this.element = $(params.element); + this.document = this.element.getDocument(); + this.setOptions(params.options || {}); + var htype = $type(this.options.handle); + this.handles = (htype == 'array' || htype == 'collection') ? $$(this.options.handle) : $(this.options.handle) || this.element; + this.mouse = {'now': {}, 'pos': {}}; + this.value = {'start': {}, 'now': {}}; + + this.selection = (Browser.Engine.trident) ? 'selectstart' : 'mousedown'; + + this.bound = { + start: this.start.bind(this), + check: this.check.bind(this), + drag: this.drag.bind(this), + stop: this.stop.bind(this), + cancel: this.cancel.bind(this), + eventStop: $lambda(false) + }; + this.attach(); + }, + + attach: function(){ + this.handles.addEvent('mousedown', this.bound.start); + return this; + }, + + detach: function(){ + this.handles.removeEvent('mousedown', this.bound.start); + return this; + }, + + start: function(event){ + if (this.options.preventDefault) event.preventDefault(); + this.fireEvent('beforeStart', this.element); + this.mouse.start = event.page; + var limit = this.options.limit; + this.limit = {'x': [], 'y': []}; + for (var z in this.options.modifiers){ + if (!this.options.modifiers[z]) continue; + if (this.options.style) this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt(); + else this.value.now[z] = this.element[this.options.modifiers[z]]; + if (this.options.invert) this.value.now[z] *= -1; + this.mouse.pos[z] = event.page[z] - this.value.now[z]; + if (limit && limit[z]){ + for (var i = 2; i--; i){ + if ($chk(limit[z][i])) this.limit[z][i] = $lambda(limit[z][i])(); + } + } + } + if ($type(this.options.grid) == 'number') this.options.grid = {'x': this.options.grid, 'y': this.options.grid}; + this.document.addEvents({mousemove: this.bound.check, mouseup: this.bound.cancel}); + this.document.addEvent(this.selection, this.bound.eventStop); + }, + + check: function(event){ + if (this.options.preventDefault) event.preventDefault(); + var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2))); + if (distance > this.options.snap){ + this.cancel(); + this.document.addEvents({ + mousemove: this.bound.drag, + mouseup: this.bound.stop + }); + this.fireEvent('start', this.element).fireEvent('snap', this.element); + } + }, + + drag: function(event){ + if (this.options.preventDefault) event.preventDefault(); + this.mouse.now = event.page; + for (var z in this.options.modifiers){ + if (!this.options.modifiers[z]) continue; + this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z]; + if (this.options.invert) this.value.now[z] *= -1; + if (this.options.limit && this.limit[z]){ + if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){ + this.value.now[z] = this.limit[z][1]; + } else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){ + this.value.now[z] = this.limit[z][0]; + } + } + if (this.options.grid[z]) this.value.now[z] -= (this.value.now[z] % this.options.grid[z]); + if (this.options.style) this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.unit); + else this.element[this.options.modifiers[z]] = this.value.now[z]; + } + this.fireEvent('drag', this.element); + }, + + cancel: function(event){ + this.document.removeEvent('mousemove', this.bound.check); + this.document.removeEvent('mouseup', this.bound.cancel); + if (event){ + this.document.removeEvent(this.selection, this.bound.eventStop); + this.fireEvent('cancel', this.element); + } + }, + + stop: function(event){ + this.document.removeEvent(this.selection, this.bound.eventStop); + this.document.removeEvent('mousemove', this.bound.drag); + this.document.removeEvent('mouseup', this.bound.stop); + if (event) this.fireEvent('complete', this.element); + } + +}); + +Element.implement({ + + makeResizable: function(options){ + return new Drag(this, $merge({modifiers: {'x': 'width', 'y': 'height'}}, options)); + } + +}); + +/* +Script: Drag.Move.js + A Drag extension that provides support for the constraining of draggables to containers and droppables. + +License: + MIT-style license. +*/ + +Drag.Move = new Class({ + + Extends: Drag, + + options: { + droppables: [], + container: false + }, + + initialize: function(element, options){ + this.parent(element, options); + this.droppables = $$(this.options.droppables); + this.container = $(this.options.container); + if (this.container && $type(this.container) != 'element') this.container = $(this.container.getDocument().body); + element = this.element; + + var current = element.getStyle('position'); + var position = (current != 'static') ? current : 'absolute'; + if (element.getStyle('left') == 'auto' || element.getStyle('top') == 'auto') element.position(element.getPosition(element.offsetParent)); + + element.setStyle('position', position); + + this.addEvent('start', function(){ + this.checkDroppables(); + }, true); + }, + + start: function(event){ + if (this.container){ + var el = this.element, cont = this.container, ccoo = cont.getCoordinates(el.offsetParent), cps = {}, ems = {}; + + ['top', 'right', 'bottom', 'left'].each(function(pad){ + cps[pad] = cont.getStyle('padding-' + pad).toInt(); + ems[pad] = el.getStyle('margin-' + pad).toInt(); + }, this); + + var width = el.offsetWidth + ems.left + ems.right, height = el.offsetHeight + ems.top + ems.bottom; + var x = [ccoo.left + cps.left, ccoo.right - cps.right - width]; + var y = [ccoo.top + cps.top, ccoo.bottom - cps.bottom - height]; + + this.options.limit = {x: x, y: y}; + } + this.parent(event); + }, + + checkAgainst: function(el){ + el = el.getCoordinates(); + var now = this.mouse.now; + return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top); + }, + + checkDroppables: function(){ + var overed = this.droppables.filter(this.checkAgainst, this).getLast(); + if (this.overed != overed){ + if (this.overed) this.fireEvent('leave', [this.element, this.overed]); + if (overed){ + this.overed = overed; + this.fireEvent('enter', [this.element, overed]); + } else { + this.overed = null; + } + } + }, + + drag: function(event){ + this.parent(event); + if (this.droppables.length) this.checkDroppables(); + }, + + stop: function(event){ + this.checkDroppables(); + this.fireEvent('drop', [this.element, this.overed]); + this.overed = null; + return this.parent(event); + } + +}); + +Element.implement({ + + makeDraggable: function(options){ + return new Drag.Move(this, options); + } + +}); diff --git a/static/script.js b/static/script.js new file mode 100644 index 0000000..e69de29 diff --git a/static/style.css b/static/style.css new file mode 100644 index 0000000..d5a038a --- /dev/null +++ b/static/style.css @@ -0,0 +1,2 @@ +.space {background-color:blue; margin:1px; width:80px; height:80px; position:relative;} +.piece {width:80px; height:80px; background-color:green; position:absolute; top:0; left:0;} \ No newline at end of file diff --git a/templates/simple.html b/templates/simple.html new file mode 100644 index 0000000..efbed26 --- /dev/null +++ b/templates/simple.html @@ -0,0 +1,30 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> + <link rel="stylesheet" type="text/css" href="static/style.css"> +<script type="text/javascript" src="static/mootools-1.2-core-nc.js"></script> +<script type="text/javascript" src="static/mootools-1.2-more.js"></script> +<script type="text/javascript" src="static/boardgame.js"></script> +</head> +<body> +<table> +#for $row in $board +<tr> + +#for $space in $row +<td class="space"> + +#if $space +<div class="piece"> +$space +</div> +#end if + +</td> +#end for + +</tr> +#end for +</table> +</body> +</html> \ No newline at end of file diff --git a/urls.py b/urls.py new file mode 100644 index 0000000..c3bb48b --- /dev/null +++ b/urls.py @@ -0,0 +1,4 @@ +urls = ( + '/', 'index', + '/move', 'move', + ) \ No newline at end of file diff --git a/views.py b/views.py new file mode 100644 index 0000000..a76f65d --- /dev/null +++ b/views.py @@ -0,0 +1,24 @@ +from couch_util import couch_request + +from web.cheetah import render + +def setup(pieces): + width = 5 + height = 6 + spaces = [[None for x in xrange(width)] for y in xrange(height)] + for piece in pieces: + x,y = pieces[piece]['location'] + spaces[y][x] = piece + return spaces + +class index: + def GET(self): + game = couch_request('game',200) + #print game['pieces'] + board = setup(game['pieces']) + #print pieces + render('simple.html',{'board':board}) + +class move: + def POST(self): + print "moving"
Elleo/gst-opencv
c767c38c847b0ee32b0a743319883d1c3478efb9
cvlaplace: adds new cvlaplace element
diff --git a/src/basicfilters/Makefile.am b/src/basicfilters/Makefile.am index e71c668..45a5dc4 100644 --- a/src/basicfilters/Makefile.am +++ b/src/basicfilters/Makefile.am @@ -1,23 +1,25 @@ noinst_LTLIBRARIES = libgstbasicfilters.la # sources used to compile this plug-in libgstbasicfilters_la_SOURCES = gstcvsmooth.c \ gstcvdilateerode.c \ gstcvdilate.c \ gstcvequalizehist.c \ + gstcvlaplace.c \ gstcverode.c \ gstcvsobel.c # flags used to compile this pyramidsegment # add other _CFLAGS and _LIBS as needed libgstbasicfilters_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) -I.. libgstbasicfilters_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS) libgstbasicfilters_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS) # headers we need but don't want installed noinst_HEADERS = gstcvsmooth.h \ gstcvdilateerode.h \ gstcvdilate.h \ gstcvequalizehist.h \ gstcverode.h \ - gstcvsobel.c + gstcvlaplace.h \ + gstcvsobel.h diff --git a/src/basicfilters/gstcvlaplace.c b/src/basicfilters/gstcvlaplace.c new file mode 100644 index 0000000..31cb4da --- /dev/null +++ b/src/basicfilters/gstcvlaplace.c @@ -0,0 +1,296 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include <gst/gst.h> + +#include "gstcvlaplace.h" + +GST_DEBUG_CATEGORY_STATIC (gst_cv_laplace_debug); +#define GST_CAT_DEFAULT gst_cv_laplace_debug + +static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("video/x-raw-gray, depth=(int)8, bpp=(int)8") + ); + +static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS + ("video/x-raw-gray, depth=(int)16, bpp=(int)16, endianness=(int)4321") + ); + +/* Filter signals and args */ +enum +{ + /* FILL ME */ + LAST_SIGNAL +}; +enum +{ + PROP_0, + PROP_APERTURE_SIZE +}; + +#define DEFAULT_APERTURE_SIZE 3 + +GST_BOILERPLATE (GstCvLaplace, gst_cv_laplace, GstOpencvBaseTransform, + GST_TYPE_OPENCV_BASE_TRANSFORM); + +static void gst_cv_laplace_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec); +static void gst_cv_laplace_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec); + +static GstCaps *gst_cv_laplace_transform_caps (GstBaseTransform * trans, + GstPadDirection dir, GstCaps * caps); + +static GstFlowReturn gst_cv_laplace_transform (GstOpencvBaseTransform * filter, + GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg); + +static gboolean gst_cv_laplace_cv_set_caps (GstOpencvBaseTransform * trans, + gint in_width, gint in_height, gint in_depth, gint in_channels, + gint out_width, gint out_height, gint out_depth, gint out_channels); + +/* Clean up */ +static void +gst_cv_laplace_finalize (GObject * obj) +{ + GstCvLaplace *filter = GST_CV_LAPLACE (obj); + + if (filter->intermediary_img) + cvReleaseImage (&filter->intermediary_img); + + G_OBJECT_CLASS (parent_class)->finalize (obj); +} + +/* GObject vmethod implementations */ + +static void +gst_cv_laplace_base_init (gpointer gclass) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (gclass); + + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&src_factory)); + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&sink_factory)); + + gst_element_class_set_details_simple (element_class, + "cvlaplace", + "Transform/Effect/Video", + "Applies cvLaplace OpenCV function to the image", + "Thiago Santos<thiago.sousa.santos@collabora.co.uk>"); +} + +/* initialize the cvlaplace's class */ +static void +gst_cv_laplace_class_init (GstCvLaplaceClass * klass) +{ + GObjectClass *gobject_class; + GstBaseTransformClass *gstbasetransform_class; + GstOpencvBaseTransformClass *gstopencvbasefilter_class; + GstElementClass *gstelement_class; + + gobject_class = (GObjectClass *) klass; + gstelement_class = (GstElementClass *) klass; + gstbasetransform_class = (GstBaseTransformClass *) klass; + gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass; + + parent_class = g_type_class_peek_parent (klass); + + gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_cv_laplace_finalize); + gobject_class->set_property = gst_cv_laplace_set_property; + gobject_class->get_property = gst_cv_laplace_get_property; + + gstbasetransform_class->transform_caps = gst_cv_laplace_transform_caps; + + gstopencvbasefilter_class->cv_trans_func = gst_cv_laplace_transform; + gstopencvbasefilter_class->cv_set_caps = gst_cv_laplace_cv_set_caps; + + g_object_class_install_property (gobject_class, PROP_APERTURE_SIZE, + g_param_spec_int ("aperture-size", "aperture size", + "Size of the extended Laplace Kernel (1, 3, 5 or 7)", 1, 7, + DEFAULT_APERTURE_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gst_cv_laplace_init (GstCvLaplace * filter, GstCvLaplaceClass * gclass) +{ + filter->aperture_size = DEFAULT_APERTURE_SIZE; + + gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE); +} + +static gboolean +gst_cv_laplace_cv_set_caps (GstOpencvBaseTransform * trans, gint in_width, + gint in_height, gint in_depth, gint in_channels, gint out_width, + gint out_height, gint out_depth, gint out_channels) +{ + GstCvLaplace *filter = GST_CV_LAPLACE (trans); + gint intermediary_depth; + + /* cvLaplace needs an signed output, so we create our intermediary step + * image here */ + switch (out_depth) { + case IPL_DEPTH_16U: + intermediary_depth = IPL_DEPTH_16S; + break; + default: + GST_WARNING_OBJECT (filter, "Unsupported output depth %d", out_depth); + return FALSE; + } + + if (filter->intermediary_img) { + cvReleaseImage (&filter->intermediary_img); + } + + filter->intermediary_img = cvCreateImage (cvSize (out_width, out_height), + intermediary_depth, out_channels); + + return TRUE; +} + +static GstCaps * +gst_cv_laplace_transform_caps (GstBaseTransform * trans, GstPadDirection dir, + GstCaps * caps) +{ + GstCaps *output = NULL; + GstStructure *structure; + gint i; + + output = gst_caps_copy (caps); + + /* we accept anything from the template caps for either side */ + switch (dir) { + case GST_PAD_SINK: + for (i = 0; i < gst_caps_get_size (output); i++) { + structure = gst_caps_get_structure (output, i); + gst_structure_set (structure, + "depth", G_TYPE_INT, 16, + "bpp", G_TYPE_INT, 16, "endianness", G_TYPE_INT, 4321, NULL); + } + break; + case GST_PAD_SRC: + for (i = 0; i < gst_caps_get_size (output); i++) { + structure = gst_caps_get_structure (output, i); + gst_structure_set (structure, + "depth", G_TYPE_INT, 8, "bpp", G_TYPE_INT, 8, NULL); + gst_structure_remove_field (structure, "endianness"); + } + break; + default: + gst_caps_unref (output); + output = NULL; + g_assert_not_reached (); + break; + } + + return output; +} + +static void +gst_cv_laplace_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstCvLaplace *filter = GST_CV_LAPLACE (object); + + switch (prop_id) { + case PROP_APERTURE_SIZE:{ + gint as = g_value_get_int (value); + + if (as % 2 != 1) { + GST_WARNING_OBJECT (filter, "Invalid value %d for aperture size", as); + } else + filter->aperture_size = g_value_get_int (value); + } + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_cv_laplace_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec) +{ + GstCvLaplace *filter = GST_CV_LAPLACE (object); + + switch (prop_id) { + case PROP_APERTURE_SIZE: + g_value_set_int (value, filter->aperture_size); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static GstFlowReturn +gst_cv_laplace_transform (GstOpencvBaseTransform * base, GstBuffer * buf, + IplImage * img, GstBuffer * outbuf, IplImage * outimg) +{ + GstCvLaplace *filter = GST_CV_LAPLACE (base); + + g_assert (filter->intermediary_img); + + cvLaplace (img, filter->intermediary_img, filter->aperture_size); + cvConvertScale (filter->intermediary_img, outimg, 1, 0); + + return GST_FLOW_OK; +} + +gboolean +gst_cv_laplace_plugin_init (GstPlugin * plugin) +{ + GST_DEBUG_CATEGORY_INIT (gst_cv_laplace_debug, "cvlaplace", 0, "cvlaplace"); + + return gst_element_register (plugin, "cvlaplace", GST_RANK_NONE, + GST_TYPE_CV_LAPLACE); +} diff --git a/src/basicfilters/gstcvlaplace.h b/src/basicfilters/gstcvlaplace.h new file mode 100644 index 0000000..74fe3d7 --- /dev/null +++ b/src/basicfilters/gstcvlaplace.h @@ -0,0 +1,88 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifndef __GST_CV_LAPLACE_H__ +#define __GST_CV_LAPLACE_H__ + +#include <gst/gst.h> +#include <cv.h> +#include <gstopencvbasetrans.h> + +G_BEGIN_DECLS + +/* #defines don't like whitespacey bits */ +#define GST_TYPE_CV_LAPLACE \ + (gst_cv_laplace_get_type()) +#define GST_CV_LAPLACE(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_CV_LAPLACE,GstCvLaplace)) +#define GST_CV_LAPLACE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_CV_LAPLACE,GstCvLaplaceClass)) +#define GST_IS_CV_LAPLACE(obj) \ + (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_CV_LAPLACE)) +#define GST_IS_CV_LAPLACE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_CV_LAPLACE)) + +typedef struct _GstCvLaplace GstCvLaplace; +typedef struct _GstCvLaplaceClass GstCvLaplaceClass; + +struct _GstCvLaplace +{ + GstOpencvBaseTransform element; + + gint aperture_size; + + IplImage *intermediary_img; +}; + +struct _GstCvLaplaceClass +{ + GstOpencvBaseTransformClass parent_class; +}; + +GType gst_cv_laplace_get_type (void); + +gboolean gst_cv_laplace_plugin_init (GstPlugin * plugin); + +G_END_DECLS + +#endif /* __GST_CV_LAPLACE_H__ */ diff --git a/src/gstopencv.c b/src/gstopencv.c index 42fb04d..8159bd9 100644 --- a/src/gstopencv.c +++ b/src/gstopencv.c @@ -1,81 +1,85 @@ /* GStreamer * Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com> * * gstopencv.c: plugin registering * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstcvdilate.h" #include "gstcvequalizehist.h" #include "gstcverode.h" +#include "gstcvlaplace.h" #include "gstcvsmooth.h" #include "gstcvsobel.h" #include "gstedgedetect.h" #include "gstfaceblur.h" #include "gstfacedetect.h" #include "gstpyramidsegment.h" #include "gsttemplatematch.h" #include "gsttextwrite.h" static gboolean plugin_init (GstPlugin * plugin) { if (!gst_cv_dilate_plugin_init (plugin)) return FALSE; if (!gst_cv_equalize_hist_plugin_init (plugin)) return FALSE; if (!gst_cv_erode_plugin_init (plugin)) return FALSE; + if (!gst_cv_laplace_plugin_init (plugin)) + return FALSE; + if (!gst_cv_smooth_plugin_init (plugin)) return FALSE; if (!gst_cv_sobel_plugin_init (plugin)) return FALSE; if (!gst_edgedetect_plugin_init (plugin)) return FALSE; if (!gst_faceblur_plugin_init (plugin)) return FALSE; if (!gst_facedetect_plugin_init (plugin)) return FALSE; if (!gst_pyramidsegment_plugin_init (plugin)) return FALSE; if (!gst_templatematch_plugin_init (plugin)) return FALSE; if (!gst_textwrite_plugin_init (plugin)) return FALSE; return TRUE; } GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR, "opencv", "GStreamer OpenCV Plugins", plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com") diff --git a/src/gstopencvbasetrans.c b/src/gstopencvbasetrans.c index 2af72a7..f47a5dd 100644 --- a/src/gstopencvbasetrans.c +++ b/src/gstopencvbasetrans.c @@ -1,304 +1,312 @@ /* * GStreamer * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Alternatively, the contents of this file may be used under the * GNU Lesser General Public License Version 2.1 (the "LGPL"), in * which case the following provisions apply instead of the ones * mentioned above: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* TODO opencv can do scaling for some cases */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <gst/gst.h> #include "gstopencvbasetrans.h" #include "gstopencvutils.h" GST_DEBUG_CATEGORY_STATIC (gst_opencv_base_transform_debug); #define GST_CAT_DEFAULT gst_opencv_base_transform_debug /* Filter signals and args */ enum { /* FILL ME */ LAST_SIGNAL }; enum { PROP_0 }; static GstElementClass *parent_class = NULL; static void gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass * klass); static void gst_opencv_base_transform_init (GstOpencvBaseTransform * trans, GstOpencvBaseTransformClass * klass); static void gst_opencv_base_transform_base_init (gpointer gclass); static gboolean gst_opencv_base_transform_set_caps (GstBaseTransform * trans, GstCaps * incaps, GstCaps * outcaps); static GstFlowReturn gst_opencv_base_transform_transform_ip (GstBaseTransform * trans, GstBuffer * buf); static GstFlowReturn gst_opencv_base_transform_transform (GstBaseTransform * trans, GstBuffer * inbuf, GstBuffer * outbuf); static gboolean gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans, GstCaps * caps, guint * size); static void gst_opencv_base_transform_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_opencv_base_transform_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); GType gst_opencv_base_transform_get_type (void) { static volatile gsize opencv_base_transform_type = 0; if (g_once_init_enter (&opencv_base_transform_type)) { GType _type; static const GTypeInfo opencv_base_transform_info = { sizeof (GstOpencvBaseTransformClass), (GBaseInitFunc) gst_opencv_base_transform_base_init, NULL, (GClassInitFunc) gst_opencv_base_transform_class_init, NULL, NULL, sizeof (GstOpencvBaseTransform), 0, (GInstanceInitFunc) gst_opencv_base_transform_init, }; _type = g_type_register_static (GST_TYPE_BASE_TRANSFORM, "GstOpencvBaseTransform", &opencv_base_transform_info, G_TYPE_FLAG_ABSTRACT); g_once_init_leave (&opencv_base_transform_type, _type); } return opencv_base_transform_type; } /* Clean up */ static void gst_opencv_base_transform_finalize (GObject * obj) { GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (obj); if (transform->cvImage) cvReleaseImage (&transform->cvImage); G_OBJECT_CLASS (parent_class)->finalize (obj); } /* GObject vmethod implementations */ static void gst_opencv_base_transform_base_init (gpointer gclass) { } static void gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; GstBaseTransformClass *basetrans_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; basetrans_class = (GstBaseTransformClass *) klass; parent_class = g_type_class_peek_parent (klass); GST_DEBUG_CATEGORY_INIT (gst_opencv_base_transform_debug, "opencvbasetransform", 0, "opencvbasetransform element"); gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_opencv_base_transform_finalize); gobject_class->set_property = gst_opencv_base_transform_set_property; gobject_class->get_property = gst_opencv_base_transform_get_property; basetrans_class->transform = gst_opencv_base_transform_transform; basetrans_class->transform_ip = gst_opencv_base_transform_transform_ip; basetrans_class->set_caps = gst_opencv_base_transform_set_caps; basetrans_class->get_unit_size = gst_opencv_base_transform_get_unit_size; } static void gst_opencv_base_transform_init (GstOpencvBaseTransform * transform, GstOpencvBaseTransformClass * bclass) { } static GstFlowReturn gst_opencv_base_transform_transform (GstBaseTransform * trans, GstBuffer * inbuf, GstBuffer * outbuf) { GstOpencvBaseTransform *transform; GstOpencvBaseTransformClass *fclass; transform = GST_OPENCV_BASE_TRANSFORM (trans); fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform); g_return_val_if_fail (fclass->cv_trans_func != NULL, GST_FLOW_ERROR); g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR); g_return_val_if_fail (transform->out_cvImage != NULL, GST_FLOW_ERROR); transform->cvImage->imageData = (char *) GST_BUFFER_DATA (inbuf); transform->out_cvImage->imageData = (char *) GST_BUFFER_DATA (outbuf); return fclass->cv_trans_func (transform, inbuf, transform->cvImage, outbuf, transform->out_cvImage); } static GstFlowReturn gst_opencv_base_transform_transform_ip (GstBaseTransform * trans, GstBuffer * buffer) { GstOpencvBaseTransform *transform; GstOpencvBaseTransformClass *fclass; transform = GST_OPENCV_BASE_TRANSFORM (trans); fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform); g_return_val_if_fail (fclass->cv_trans_ip_func != NULL, GST_FLOW_ERROR); g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR); buffer = gst_buffer_make_writable (buffer); transform->cvImage->imageData = (char *) GST_BUFFER_DATA (buffer); /* FIXME how to release buffer? */ return fclass->cv_trans_ip_func (transform, buffer, transform->cvImage); } static gboolean gst_opencv_base_transform_set_caps (GstBaseTransform * trans, GstCaps * incaps, GstCaps * outcaps) { GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (trans); + GstOpencvBaseTransformClass *klass = + GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform); gint in_width, in_height; gint in_depth, in_channels; gint out_width, out_height; gint out_depth, out_channels; GError *in_err = NULL; GError *out_err = NULL; if (!gst_opencv_parse_iplimage_params_from_caps (incaps, &in_width, &in_height, &in_depth, &in_channels, &in_err)) { GST_WARNING_OBJECT (transform, "Failed to parse input caps: %s", in_err->message); g_error_free (in_err); return FALSE; } if (!gst_opencv_parse_iplimage_params_from_caps (outcaps, &out_width, &out_height, &out_depth, &out_channels, &out_err)) { GST_WARNING_OBJECT (transform, "Failed to parse output caps: %s", out_err->message); g_error_free (out_err); return FALSE; } + if (klass->cv_set_caps) { + if (!klass->cv_set_caps(transform, in_width, in_height, in_depth, + in_channels, out_width, out_height, out_depth, out_channels)) + return FALSE; + } + if (transform->cvImage) { cvReleaseImage (&transform->cvImage); } if (transform->out_cvImage) { cvReleaseImage (&transform->out_cvImage); } transform->cvImage = cvCreateImageHeader (cvSize (in_width, in_height), in_depth, in_channels); transform->out_cvImage = cvCreateImageHeader (cvSize (out_width, out_height), out_depth, out_channels); gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform), transform->in_place); return TRUE; } static gboolean gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans, GstCaps * caps, guint * size) { gint width, height; gint bpp; GstStructure *structure; structure = gst_caps_get_structure (caps, 0); if (!gst_structure_get_int (structure, "width", &width) || !gst_structure_get_int (structure, "height", &height) || !gst_structure_get_int (structure, "bpp", &bpp)) { return FALSE; } *size = width * height * bpp / 8; return TRUE; } static void gst_opencv_base_transform_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { switch (prop_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_opencv_base_transform_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { switch (prop_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } void gst_opencv_base_transform_set_in_place (GstOpencvBaseTransform * transform, gboolean ip) { transform->in_place = ip; gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform), ip); } diff --git a/src/gstopencvbasetrans.h b/src/gstopencvbasetrans.h index db808a8..5ab3ddb 100644 --- a/src/gstopencvbasetrans.h +++ b/src/gstopencvbasetrans.h @@ -1,98 +1,105 @@ /* * GStreamer * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Alternatively, the contents of this file may be used under the * GNU Lesser General Public License Version 2.1 (the "LGPL"), in * which case the following provisions apply instead of the ones * mentioned above: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __GST_OPENCV_BASE_TRANSFORM_H__ #define __GST_OPENCV_BASE_TRANSFORM_H__ #include <gst/gst.h> #include <gst/base/gstbasetransform.h> #include <cv.h> G_BEGIN_DECLS /* #defines don't like whitespacey bits */ #define GST_TYPE_OPENCV_BASE_TRANSFORM \ (gst_opencv_base_transform_get_type()) #define GST_OPENCV_BASE_TRANSFORM(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_OPENCV_BASE_TRANSFORM,GstOpencvBaseTransform)) #define GST_OPENCV_BASE_TRANSFORM_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_OPENCV_BASE_TRANSFORM,GstOpencvBaseTransformClass)) #define GST_IS_OPENCV_BASE_TRANSFORM(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_OPENCV_BASE_TRANSFORM)) #define GST_IS_OPENCV_BASE_TRANSFORM_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_OPENCV_BASE_TRANSFORM)) #define GST_OPENCV_BASE_TRANSFORM_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj),GST_TYPE_OPENCV_BASE_TRANSFORM,GstOpencvBaseTransformClass)) typedef struct _GstOpencvBaseTransform GstOpencvBaseTransform; typedef struct _GstOpencvBaseTransformClass GstOpencvBaseTransformClass; typedef GstFlowReturn (*GstOpencvBaseTransformTransformIPFunc) (GstOpencvBaseTransform * transform, GstBuffer * buffer, IplImage * img); typedef GstFlowReturn (*GstOpencvBaseTransformTransformFunc) (GstOpencvBaseTransform * transform, GstBuffer * buffer, IplImage * img, GstBuffer * outbuf, IplImage * outimg); +typedef gboolean (*GstOpencvBaseTransformSetCaps) + (GstOpencvBaseTransform * transform, gint in_width, gint in_height, + gint in_depth, gint in_channels, gint out_width, gint out_height, + gint out_depth, gint out_channels); + struct _GstOpencvBaseTransform { GstBaseTransform trans; gboolean in_place; IplImage *cvImage; IplImage *out_cvImage; }; struct _GstOpencvBaseTransformClass { GstBaseTransformClass parent_class; GstOpencvBaseTransformTransformFunc cv_trans_func; GstOpencvBaseTransformTransformIPFunc cv_trans_ip_func; + + GstOpencvBaseTransformSetCaps cv_set_caps; }; GType gst_opencv_base_transform_get_type (void); void gst_opencv_base_transform_set_in_place (GstOpencvBaseTransform * transform, gboolean ip); G_END_DECLS #endif /* __GST_OPENCV_BASE_TRANSFORM_H__ */
Elleo/gst-opencv
4f722547392008c87a541f6340f30200928fe8dc
Adds new element cvsobel
diff --git a/src/basicfilters/Makefile.am b/src/basicfilters/Makefile.am index 4980beb..e71c668 100644 --- a/src/basicfilters/Makefile.am +++ b/src/basicfilters/Makefile.am @@ -1,21 +1,23 @@ noinst_LTLIBRARIES = libgstbasicfilters.la # sources used to compile this plug-in libgstbasicfilters_la_SOURCES = gstcvsmooth.c \ gstcvdilateerode.c \ gstcvdilate.c \ gstcvequalizehist.c \ - gstcverode.c + gstcverode.c \ + gstcvsobel.c # flags used to compile this pyramidsegment # add other _CFLAGS and _LIBS as needed libgstbasicfilters_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) -I.. libgstbasicfilters_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS) libgstbasicfilters_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS) # headers we need but don't want installed noinst_HEADERS = gstcvsmooth.h \ gstcvdilateerode.h \ gstcvdilate.h \ gstcvequalizehist.h \ - gstcverode.h + gstcverode.h \ + gstcvsobel.c diff --git a/src/basicfilters/gstcvsobel.c b/src/basicfilters/gstcvsobel.c new file mode 100644 index 0000000..dcbf01b --- /dev/null +++ b/src/basicfilters/gstcvsobel.c @@ -0,0 +1,281 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include <gst/gst.h> + +#include "gstcvsobel.h" + +GST_DEBUG_CATEGORY_STATIC (gst_cv_sobel_debug); +#define GST_CAT_DEFAULT gst_cv_sobel_debug + +static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("video/x-raw-gray, depth=(int)8, bpp=(int)8") + ); + +static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS + ("video/x-raw-gray, depth=(int)16, bpp=(int)16, endianness=(int)4321") + ); + +/* Filter signals and args */ +enum +{ + /* FILL ME */ + LAST_SIGNAL +}; +enum +{ + PROP_0, + PROP_X_ORDER, + PROP_Y_ORDER, + PROP_APERTURE_SIZE +}; + +#define DEFAULT_X_ORDER 1 +#define DEFAULT_Y_ORDER 0 +#define DEFAULT_APERTURE_SIZE 3 + +GST_BOILERPLATE (GstCvSobel, gst_cv_sobel, GstOpencvBaseTransform, + GST_TYPE_OPENCV_BASE_TRANSFORM); + +static void gst_cv_sobel_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec); +static void gst_cv_sobel_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec); + +static GstCaps *gst_cv_sobel_transform_caps (GstBaseTransform * trans, + GstPadDirection dir, GstCaps * caps); + +static GstFlowReturn gst_cv_sobel_transform (GstOpencvBaseTransform * filter, + GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg); + +/* Clean up */ +static void +gst_cv_sobel_finalize (GObject * obj) +{ + G_OBJECT_CLASS (parent_class)->finalize (obj); +} + +/* GObject vmethod implementations */ + +static void +gst_cv_sobel_base_init (gpointer gclass) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (gclass); + + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&src_factory)); + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&sink_factory)); + + gst_element_class_set_details_simple (element_class, + "cvsobel", + "Transform/Effect/Video", + "Applies cvSobel OpenCV function to the image", + "Thiago Santos<thiago.sousa.santos@collabora.co.uk>"); +} + +/* initialize the cvsobel's class */ +static void +gst_cv_sobel_class_init (GstCvSobelClass * klass) +{ + GObjectClass *gobject_class; + GstBaseTransformClass *gstbasetransform_class; + GstOpencvBaseTransformClass *gstopencvbasefilter_class; + GstElementClass *gstelement_class; + + gobject_class = (GObjectClass *) klass; + gstelement_class = (GstElementClass *) klass; + gstbasetransform_class = (GstBaseTransformClass *) klass; + gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass; + + parent_class = g_type_class_peek_parent (klass); + + gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_cv_sobel_finalize); + gobject_class->set_property = gst_cv_sobel_set_property; + gobject_class->get_property = gst_cv_sobel_get_property; + + gstbasetransform_class->transform_caps = gst_cv_sobel_transform_caps; + + gstopencvbasefilter_class->cv_trans_func = gst_cv_sobel_transform; + + g_object_class_install_property (gobject_class, PROP_X_ORDER, + g_param_spec_int ("x-order", "x order", + "Order of the derivative x", -1, G_MAXINT, + DEFAULT_X_ORDER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + g_object_class_install_property (gobject_class, PROP_Y_ORDER, + g_param_spec_int ("y-order", "y order", + "Order of the derivative y", -1, G_MAXINT, + DEFAULT_Y_ORDER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + g_object_class_install_property (gobject_class, PROP_APERTURE_SIZE, + g_param_spec_int ("aperture-size", "aperture size", + "Size of the extended Sobel Kernel (1, 3, 5 or 7)", 1, 7, + DEFAULT_APERTURE_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gst_cv_sobel_init (GstCvSobel * filter, GstCvSobelClass * gclass) +{ + filter->x_order = DEFAULT_X_ORDER; + filter->y_order = DEFAULT_Y_ORDER; + filter->aperture_size = DEFAULT_APERTURE_SIZE; + + gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE); +} + +static GstCaps * +gst_cv_sobel_transform_caps (GstBaseTransform * trans, GstPadDirection dir, + GstCaps * caps) +{ + GstCaps *output = NULL; + GstStructure *structure; + gint i; + + output = gst_caps_copy (caps); + + /* we accept anything from the template caps for either side */ + switch (dir) { + case GST_PAD_SINK: + for (i = 0; i < gst_caps_get_size (output); i++) { + structure = gst_caps_get_structure (output, i); + gst_structure_set (structure, + "depth", G_TYPE_INT, 16, + "bpp", G_TYPE_INT, 16, "endianness", G_TYPE_INT, 4321, NULL); + } + break; + case GST_PAD_SRC: + for (i = 0; i < gst_caps_get_size (output); i++) { + structure = gst_caps_get_structure (output, i); + gst_structure_set (structure, + "depth", G_TYPE_INT, 8, "bpp", G_TYPE_INT, 8, NULL); + gst_structure_remove_field (structure, "endianness"); + } + break; + default: + gst_caps_unref (output); + output = NULL; + g_assert_not_reached (); + break; + } + + return output; +} + +static void +gst_cv_sobel_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstCvSobel *filter = GST_CV_SOBEL (object); + + switch (prop_id) { + case PROP_X_ORDER: + filter->x_order = g_value_get_int (value); + break; + case PROP_Y_ORDER: + filter->y_order = g_value_get_int (value); + break; + case PROP_APERTURE_SIZE:{ + gint as = g_value_get_int (value); + + if (as % 2 != 1) { + GST_WARNING_OBJECT (filter, "Invalid value %d for aperture size", as); + } else + filter->aperture_size = g_value_get_int (value); + } + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_cv_sobel_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec) +{ + GstCvSobel *filter = GST_CV_SOBEL (object); + + switch (prop_id) { + case PROP_X_ORDER: + g_value_set_int (value, filter->x_order); + break; + case PROP_Y_ORDER: + g_value_set_int (value, filter->y_order); + break; + case PROP_APERTURE_SIZE: + g_value_set_int (value, filter->aperture_size); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static GstFlowReturn +gst_cv_sobel_transform (GstOpencvBaseTransform * base, GstBuffer * buf, + IplImage * img, GstBuffer * outbuf, IplImage * outimg) +{ + GstCvSobel *filter = GST_CV_SOBEL (base); + + cvSobel (img, outimg, filter->x_order, filter->y_order, + filter->aperture_size); + + return GST_FLOW_OK; +} + +gboolean +gst_cv_sobel_plugin_init (GstPlugin * plugin) +{ + GST_DEBUG_CATEGORY_INIT (gst_cv_sobel_debug, "cvsobel", 0, "cvsobel"); + + return gst_element_register (plugin, "cvsobel", GST_RANK_NONE, + GST_TYPE_CV_SOBEL); +} diff --git a/src/basicfilters/gstcvsobel.h b/src/basicfilters/gstcvsobel.h new file mode 100644 index 0000000..d9effd6 --- /dev/null +++ b/src/basicfilters/gstcvsobel.h @@ -0,0 +1,88 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifndef __GST_CV_SOBEL_H__ +#define __GST_CV_SOBEL_H__ + +#include <gst/gst.h> +#include <cv.h> +#include <gstopencvbasetrans.h> + +G_BEGIN_DECLS + +/* #defines don't like whitespacey bits */ +#define GST_TYPE_CV_SOBEL \ + (gst_cv_sobel_get_type()) +#define GST_CV_SOBEL(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_CV_SOBEL,GstCvSobel)) +#define GST_CV_SOBEL_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_CV_SOBEL,GstCvSobelClass)) +#define GST_IS_CV_SOBEL(obj) \ + (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_CV_SOBEL)) +#define GST_IS_CV_SOBEL_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_CV_SOBEL)) + +typedef struct _GstCvSobel GstCvSobel; +typedef struct _GstCvSobelClass GstCvSobelClass; + +struct _GstCvSobel +{ + GstOpencvBaseTransform element; + + gint x_order; + gint y_order; + gint aperture_size; +}; + +struct _GstCvSobelClass +{ + GstOpencvBaseTransformClass parent_class; +}; + +GType gst_cv_sobel_get_type (void); + +gboolean gst_cv_sobel_plugin_init (GstPlugin * plugin); + +G_END_DECLS + +#endif /* __GST_CV_SOBEL_H__ */ diff --git a/src/gstopencv.c b/src/gstopencv.c index 77653a8..42fb04d 100644 --- a/src/gstopencv.c +++ b/src/gstopencv.c @@ -1,78 +1,81 @@ /* GStreamer * Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com> * * gstopencv.c: plugin registering * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstcvdilate.h" #include "gstcvequalizehist.h" #include "gstcverode.h" #include "gstcvsmooth.h" +#include "gstcvsobel.h" #include "gstedgedetect.h" #include "gstfaceblur.h" #include "gstfacedetect.h" #include "gstpyramidsegment.h" #include "gsttemplatematch.h" #include "gsttextwrite.h" static gboolean plugin_init (GstPlugin * plugin) { - if (!gst_cv_dilate_plugin_init (plugin)) return FALSE; if (!gst_cv_equalize_hist_plugin_init (plugin)) return FALSE; if (!gst_cv_erode_plugin_init (plugin)) return FALSE; if (!gst_cv_smooth_plugin_init (plugin)) return FALSE; + if (!gst_cv_sobel_plugin_init (plugin)) + return FALSE; + if (!gst_edgedetect_plugin_init (plugin)) return FALSE; if (!gst_faceblur_plugin_init (plugin)) return FALSE; if (!gst_facedetect_plugin_init (plugin)) return FALSE; if (!gst_pyramidsegment_plugin_init (plugin)) return FALSE; if (!gst_templatematch_plugin_init (plugin)) return FALSE; if (!gst_textwrite_plugin_init (plugin)) return FALSE; return TRUE; } GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR, "opencv", "GStreamer OpenCV Plugins", plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com") diff --git a/src/gstopencvutils.c b/src/gstopencvutils.c index 0b58397..2848141 100644 --- a/src/gstopencvutils.c +++ b/src/gstopencvutils.c @@ -1,91 +1,94 @@ /* GStreamer * Copyright (C) <2010> Thiago Santos <thiago.sousa.santos@collabora.co.uk> * * gstopencvutils.c: miscellaneous utility functions * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "gstopencvutils.h" gboolean gst_opencv_get_ipl_depth_and_channels (GstStructure * structure, gint * ipldepth, gint * channels, GError ** err) { gint depth, bpp; if (!gst_structure_get_int (structure, "depth", &depth) || !gst_structure_get_int (structure, "bpp", &bpp)) { g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION, "No depth/bpp in caps"); return FALSE; } if (depth != bpp) { g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION, "Depth and bpp should be equal"); return FALSE; } if (gst_structure_has_name (structure, "video/x-raw-rgb")) { *channels = 3; } else if (gst_structure_has_name (structure, "video/x-raw-gray")) { *channels = 1; } else { g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION, "Unsupported caps %s", gst_structure_get_name (structure)); return FALSE; } if (depth / *channels == 8) { /* TODO signdness? */ *ipldepth = IPL_DEPTH_8U; + } else if (depth / *channels == 16) { + *ipldepth = IPL_DEPTH_16U; } else { g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION, "Unsupported depth/channels %d/%d", depth, *channels); return FALSE; } return TRUE; } gboolean gst_opencv_parse_iplimage_params_from_structure (GstStructure * structure, gint * width, gint * height, gint * ipldepth, gint * channels, GError ** err) { if (!gst_opencv_get_ipl_depth_and_channels (structure, ipldepth, channels, err)) { return FALSE; } if (!gst_structure_get_int (structure, "width", width) || !gst_structure_get_int (structure, "height", height)) { g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION, "No width/height in caps"); return FALSE; } return TRUE; } gboolean gst_opencv_parse_iplimage_params_from_caps (GstCaps * caps, gint * width, gint * height, gint * ipldepth, gint * channels, GError ** err) { - return gst_opencv_parse_iplimage_params_from_structure ( - gst_caps_get_structure (caps, 0), width, height, ipldepth, channels, err); + return + gst_opencv_parse_iplimage_params_from_structure (gst_caps_get_structure + (caps, 0), width, height, ipldepth, channels, err); }
Elleo/gst-opencv
19e82cf9076dbb219d595707e4387c850354158a
Adds new element cvequalizehist
diff --git a/src/basicfilters/Makefile.am b/src/basicfilters/Makefile.am index 61b703e..4980beb 100644 --- a/src/basicfilters/Makefile.am +++ b/src/basicfilters/Makefile.am @@ -1,19 +1,21 @@ noinst_LTLIBRARIES = libgstbasicfilters.la # sources used to compile this plug-in libgstbasicfilters_la_SOURCES = gstcvsmooth.c \ gstcvdilateerode.c \ gstcvdilate.c \ + gstcvequalizehist.c \ gstcverode.c # flags used to compile this pyramidsegment # add other _CFLAGS and _LIBS as needed libgstbasicfilters_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) -I.. libgstbasicfilters_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS) libgstbasicfilters_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS) # headers we need but don't want installed noinst_HEADERS = gstcvsmooth.h \ gstcvdilateerode.h \ gstcvdilate.h \ + gstcvequalizehist.h \ gstcverode.h diff --git a/src/basicfilters/gstcvequalizehist.c b/src/basicfilters/gstcvequalizehist.c new file mode 100644 index 0000000..f891e5e --- /dev/null +++ b/src/basicfilters/gstcvequalizehist.c @@ -0,0 +1,134 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include <gst/gst.h> + +#include "gstcvequalizehist.h" + +GST_DEBUG_CATEGORY_STATIC (gst_cv_equalize_hist_debug); +#define GST_CAT_DEFAULT gst_cv_equalize_hist_debug + +static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("video/x-raw-gray, depth=(int)8, bpp=(int)8")); + +static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("video/x-raw-gray, depth=(int)8, bpp=(int)8")); + +GST_BOILERPLATE (GstCvEqualizeHist, gst_cv_equalize_hist, + GstOpencvBaseTransform, GST_TYPE_OPENCV_BASE_TRANSFORM); + +static GstFlowReturn gst_cv_equalize_hist_transform ( + GstOpencvBaseTransform * filter, GstBuffer * buf, IplImage * img, + GstBuffer * outbuf, IplImage * outimg); + +/* Clean up */ +static void +gst_cv_equalize_hist_finalize (GObject * obj) +{ + G_OBJECT_CLASS (parent_class)->finalize (obj); +} + + +/* GObject vmethod implementations */ +static void +gst_cv_equalize_hist_base_init (gpointer gclass) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (gclass); + + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&src_factory)); + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&sink_factory)); + + gst_element_class_set_details_simple (element_class, + "cvequalizehist", + "Transform/Effect/Video", + "Applies cvEqualizeHist OpenCV function to the image", + "Thiago Santos<thiago.sousa.santos@collabora.co.uk>"); +} + +static void +gst_cv_equalize_hist_class_init (GstCvEqualizeHistClass * klass) +{ + GObjectClass *gobject_class; + GstOpencvBaseTransformClass *gstopencvbasefilter_class; + + gobject_class = (GObjectClass *) klass; + gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass; + + parent_class = g_type_class_peek_parent (klass); + gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_cv_equalize_hist_finalize); + gstopencvbasefilter_class->cv_trans_func = gst_cv_equalize_hist_transform; +} + +static void +gst_cv_equalize_hist_init (GstCvEqualizeHist * filter, + GstCvEqualizeHistClass * gclass) +{ + gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE); +} + +static GstFlowReturn +gst_cv_equalize_hist_transform (GstOpencvBaseTransform * base, + GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg) +{ + cvEqualizeHist (img, outimg); + return GST_FLOW_OK; +} + +gboolean +gst_cv_equalize_hist_plugin_init (GstPlugin * plugin) +{ + GST_DEBUG_CATEGORY_INIT (gst_cv_equalize_hist_debug, "cvequalizehist", 0, + "cvequalizehist"); + return gst_element_register (plugin, "cvequalizehist", GST_RANK_NONE, + GST_TYPE_CV_EQUALIZE_HIST); +} diff --git a/src/basicfilters/gstcvequalizehist.h b/src/basicfilters/gstcvequalizehist.h new file mode 100644 index 0000000..fe22981 --- /dev/null +++ b/src/basicfilters/gstcvequalizehist.h @@ -0,0 +1,84 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifndef __GST_CV_EQUALIZE_HIST_H__ +#define __GST_CV_EQUALIZE_HIST_H__ + +#include <gst/gst.h> +#include <cv.h> +#include <gstopencvbasetrans.h> + +G_BEGIN_DECLS + +/* #defines don't like whitespacey bits */ +#define GST_TYPE_CV_EQUALIZE_HIST \ + (gst_cv_equalize_hist_get_type()) +#define GST_CV_EQUALIZE_HIST(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_CV_EQUALIZE_HIST,GstCvEqualizeHist)) +#define GST_CV_EQUALIZE_HIST_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_CV_EQUALIZE_HIST,GstCvEqualizeHistClass)) +#define GST_IS_CV_EQUALIZE_HIST(obj) \ + (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_CV_EQUALIZE_HIST)) +#define GST_IS_CV_EQUALIZE_HIST_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_CV_EQUALIZE_HIST)) + +typedef struct _GstCvEqualizeHist GstCvEqualizeHist; +typedef struct _GstCvEqualizeHistClass GstCvEqualizeHistClass; + +struct _GstCvEqualizeHist +{ + GstOpencvBaseTransform element; +}; + +struct _GstCvEqualizeHistClass +{ + GstOpencvBaseTransformClass parent_class; +}; + +GType gst_cv_equalize_hist_get_type (void); + +gboolean gst_cv_equalize_hist_plugin_init (GstPlugin * plugin); + +G_END_DECLS + +#endif /* __GST_CV_EQUALIZE_HIST_H__ */ diff --git a/src/gstopencv.c b/src/gstopencv.c index 084e675..77653a8 100644 --- a/src/gstopencv.c +++ b/src/gstopencv.c @@ -1,74 +1,78 @@ /* GStreamer * Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com> * * gstopencv.c: plugin registering * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstcvdilate.h" +#include "gstcvequalizehist.h" #include "gstcverode.h" #include "gstcvsmooth.h" #include "gstedgedetect.h" #include "gstfaceblur.h" #include "gstfacedetect.h" #include "gstpyramidsegment.h" #include "gsttemplatematch.h" #include "gsttextwrite.h" static gboolean plugin_init (GstPlugin * plugin) { if (!gst_cv_dilate_plugin_init (plugin)) return FALSE; + if (!gst_cv_equalize_hist_plugin_init (plugin)) + return FALSE; + if (!gst_cv_erode_plugin_init (plugin)) return FALSE; if (!gst_cv_smooth_plugin_init (plugin)) return FALSE; if (!gst_edgedetect_plugin_init (plugin)) return FALSE; if (!gst_faceblur_plugin_init (plugin)) return FALSE; if (!gst_facedetect_plugin_init (plugin)) return FALSE; if (!gst_pyramidsegment_plugin_init (plugin)) return FALSE; if (!gst_templatematch_plugin_init (plugin)) return FALSE; if (!gst_textwrite_plugin_init (plugin)) return FALSE; return TRUE; } GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR, "opencv", "GStreamer OpenCV Plugins", plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com")
Elleo/gst-opencv
010c19788b03caacf2b2f0568a504741fc97f4d0
Adds new elements cvdilate and cverode
diff --git a/src/basicfilters/Makefile.am b/src/basicfilters/Makefile.am index fba6ba6..61b703e 100644 --- a/src/basicfilters/Makefile.am +++ b/src/basicfilters/Makefile.am @@ -1,13 +1,19 @@ noinst_LTLIBRARIES = libgstbasicfilters.la # sources used to compile this plug-in -libgstbasicfilters_la_SOURCES = gstcvsmooth.c +libgstbasicfilters_la_SOURCES = gstcvsmooth.c \ + gstcvdilateerode.c \ + gstcvdilate.c \ + gstcverode.c # flags used to compile this pyramidsegment # add other _CFLAGS and _LIBS as needed libgstbasicfilters_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) -I.. libgstbasicfilters_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS) libgstbasicfilters_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS) # headers we need but don't want installed -noinst_HEADERS = gstcvsmooth.h +noinst_HEADERS = gstcvsmooth.h \ + gstcvdilateerode.h \ + gstcvdilate.h \ + gstcverode.h diff --git a/src/basicfilters/gstcvdilate.c b/src/basicfilters/gstcvdilate.c new file mode 100644 index 0000000..6170fcd --- /dev/null +++ b/src/basicfilters/gstcvdilate.c @@ -0,0 +1,130 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include <gst/gst.h> + +#include "gstcvdilate.h" + +GST_DEBUG_CATEGORY_STATIC (gst_cv_dilate_debug); +#define GST_CAT_DEFAULT gst_cv_dilate_debug + +GST_BOILERPLATE (GstCvDilate, gst_cv_dilate, GstCvDilateErode, + GST_TYPE_CV_DILATE_ERODE); + +static GstFlowReturn gst_cv_dilate_transform_ip (GstOpencvBaseTransform * + filter, GstBuffer * buf, IplImage * img); +static GstFlowReturn gst_cv_dilate_transform (GstOpencvBaseTransform * filter, + GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg); + +/* GObject vmethod implementations */ +static void +gst_cv_dilate_base_init (gpointer gclass) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (gclass); + + gst_element_class_set_details_simple (element_class, + "cvdilate", + "Transform/Effect/Video", + "Applies cvDilate OpenCV function to the image", + "Thiago Santos<thiago.sousa.santos@collabora.co.uk>"); +} + +/* initialize the cvdilate's class */ +static void +gst_cv_dilate_class_init (GstCvDilateClass * klass) +{ + GstOpencvBaseTransformClass *gstopencvbasefilter_class; + + gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass; + + parent_class = g_type_class_peek_parent (klass); + + gstopencvbasefilter_class->cv_trans_ip_func = gst_cv_dilate_transform_ip; + gstopencvbasefilter_class->cv_trans_func = gst_cv_dilate_transform; +} + +/* initialize the new element + * instantiate pads and add them to element + * set pad calback functions + * initialize instance structure + */ +static void +gst_cv_dilate_init (GstCvDilate * filter, GstCvDilateClass * gclass) +{ +} + +static GstFlowReturn +gst_cv_dilate_transform (GstOpencvBaseTransform * base, GstBuffer * buf, + IplImage * img, GstBuffer * outbuf, IplImage * outimg) +{ + GstCvDilateErode *filter = GST_CV_DILATE_ERODE (base); + + /* TODO support kernel as a parameter */ + cvDilate (img, outimg, NULL, filter->iterations); + + return GST_FLOW_OK; +} + +static GstFlowReturn +gst_cv_dilate_transform_ip (GstOpencvBaseTransform * base, GstBuffer * buf, + IplImage * img) +{ + GstCvDilateErode *filter = GST_CV_DILATE_ERODE (base); + + cvDilate (img, img, NULL, filter->iterations); + + return GST_FLOW_OK; +} + +gboolean +gst_cv_dilate_plugin_init (GstPlugin * plugin) +{ + GST_DEBUG_CATEGORY_INIT (gst_cv_dilate_debug, "cvdilate", 0, "cvdilate"); + + return gst_element_register (plugin, "cvdilate", GST_RANK_NONE, + GST_TYPE_CV_DILATE); +} diff --git a/src/basicfilters/gstcvdilate.h b/src/basicfilters/gstcvdilate.h new file mode 100644 index 0000000..c0a3b00 --- /dev/null +++ b/src/basicfilters/gstcvdilate.h @@ -0,0 +1,84 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifndef __GST_CV_DILATE_H__ +#define __GST_CV_DILATE_H__ + +#include <gst/gst.h> +#include <cv.h> +#include "gstcvdilateerode.h" + +G_BEGIN_DECLS + +/* #defines don't like whitespacey bits */ +#define GST_TYPE_CV_DILATE \ + (gst_cv_dilate_get_type()) +#define GST_CV_DILATE(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_CV_DILATE,GstCvDilate)) +#define GST_CV_DILATE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_CV_DILATE,GstCvDilateClass)) +#define GST_IS_CV_DILATE(obj) \ + (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_CV_DILATE)) +#define GST_IS_CV_DILATE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_CV_DILATE)) + +typedef struct _GstCvDilate GstCvDilate; +typedef struct _GstCvDilateClass GstCvDilateClass; + +struct _GstCvDilate +{ + GstCvDilateErode element; +}; + +struct _GstCvDilateClass +{ + GstCvDilateErodeClass parent_class; +}; + +GType gst_cv_dilate_get_type (void); + +gboolean gst_cv_dilate_plugin_init (GstPlugin * plugin); + +G_END_DECLS + +#endif /* __GST_CV_DILATE_H__ */ diff --git a/src/basicfilters/gstcvdilateerode.c b/src/basicfilters/gstcvdilateerode.c new file mode 100644 index 0000000..4f99ea9 --- /dev/null +++ b/src/basicfilters/gstcvdilateerode.c @@ -0,0 +1,221 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/* + * As cvdilate_erode and cverode are all the same, except for the transform function, + * we hope this base class should keep maintenance easier. + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include <gst/gst.h> + +#include "gstcvdilateerode.h" + +/* +GST_DEBUG_CATEGORY_STATIC (gst_cv_dilate_erode_debug); +#define GST_CAT_DEFAULT gst_cv_dilate_erode_debug +*/ + +static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24;" + "video/x-raw-gray") + ); + +static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24;" + "video/x-raw-gray") + ); + +/* Filter signals and args */ +enum +{ + /* FILL ME */ + LAST_SIGNAL +}; +enum +{ + PROP_0, + PROP_ITERATIONS, +}; + +#define DEFAULT_ITERATIONS 1 + +static GstElementClass *parent_class = NULL; + +static void gst_cv_dilate_erode_base_init (gpointer gclass); +static void gst_cv_dilate_erode_class_init (GstCvDilateErodeClass * klass); +static void gst_cv_dilate_erode_init (GstCvDilateErode * filter, + GstCvDilateErodeClass * gclass); + +static void gst_cv_dilate_erode_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec); +static void gst_cv_dilate_erode_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec); + +GType +gst_cv_dilate_erode_get_type (void) +{ + static volatile gsize opencv_dilate_erode_type = 0; + + if (g_once_init_enter (&opencv_dilate_erode_type)) { + GType _type; + static const GTypeInfo opencv_dilate_erode_info = { + sizeof (GstCvDilateErodeClass), + (GBaseInitFunc) gst_cv_dilate_erode_base_init, + NULL, + (GClassInitFunc) gst_cv_dilate_erode_class_init, + NULL, + NULL, + sizeof (GstCvDilateErode), + 0, + (GInstanceInitFunc) gst_cv_dilate_erode_init, + }; + + _type = g_type_register_static (GST_TYPE_OPENCV_BASE_TRANSFORM, + "GstCvDilateErode", &opencv_dilate_erode_info, + G_TYPE_FLAG_ABSTRACT); +/* + GST_DEBUG_CATEGORY_INIT (gst_cv_dilate_erode_debug, "cvdilateerode", 0, + "cvdilateerode"); +*/ + g_once_init_leave (&opencv_dilate_erode_type, _type); + } + return opencv_dilate_erode_type; +} + +/* Clean up */ +static void +gst_cv_dilate_erode_finalize (GObject * obj) +{ + G_OBJECT_CLASS (parent_class)->finalize (obj); +} + + +/* GObject vmethod implementations */ + +static void +gst_cv_dilate_erode_base_init (gpointer gclass) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (gclass); + + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&src_factory)); + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&sink_factory)); +} + +/* initialize the cvdilate_erode's class */ +static void +gst_cv_dilate_erode_class_init (GstCvDilateErodeClass * klass) +{ + GObjectClass *gobject_class; + GstOpencvBaseTransformClass *gstopencvbasefilter_class; + GstElementClass *gstelement_class; + + gobject_class = (GObjectClass *) klass; + gstelement_class = (GstElementClass *) klass; + gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass; + + parent_class = g_type_class_peek_parent (klass); + + gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_cv_dilate_erode_finalize); + gobject_class->set_property = gst_cv_dilate_erode_set_property; + gobject_class->get_property = gst_cv_dilate_erode_get_property; + + g_object_class_install_property (gobject_class, PROP_ITERATIONS, + g_param_spec_int ("iterations", "iterations", + "Number of iterations to run the algorithm", 1, G_MAXINT, + DEFAULT_ITERATIONS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +/* initialize the new element + * instantiate pads and add them to element + * set pad calback functions + * initialize instance structure + */ +static void +gst_cv_dilate_erode_init (GstCvDilateErode * filter, + GstCvDilateErodeClass * gclass) +{ + filter->iterations = DEFAULT_ITERATIONS; + gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), TRUE); +} + +static void +gst_cv_dilate_erode_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstCvDilateErode *filter = GST_CV_DILATE_ERODE (object); + + switch (prop_id) { + case PROP_ITERATIONS: + filter->iterations = g_value_get_int (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_cv_dilate_erode_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec) +{ + GstCvDilateErode *filter = GST_CV_DILATE_ERODE (object); + + switch (prop_id) { + case PROP_ITERATIONS: + g_value_set_int (value, filter->iterations); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} diff --git a/src/basicfilters/gstcvdilateerode.h b/src/basicfilters/gstcvdilateerode.h new file mode 100644 index 0000000..4db07d7 --- /dev/null +++ b/src/basicfilters/gstcvdilateerode.h @@ -0,0 +1,84 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifndef __GST_CV_DILATE_ERODE_H__ +#define __GST_CV_DILATE_ERODE_H__ + +#include <gst/gst.h> +#include <cv.h> +#include <gstopencvbasetrans.h> + +G_BEGIN_DECLS + +/* #defines don't like whitespacey bits */ +#define GST_TYPE_CV_DILATE_ERODE \ + (gst_cv_dilate_erode_get_type()) +#define GST_CV_DILATE_ERODE(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_CV_DILATE_ERODE,GstCvDilateErode)) +#define GST_CV_DILATE_ERODE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_CV_DILATE_ERODE,GstCvDilateErodeClass)) +#define GST_IS_CV_DILATE_ERODE(obj) \ + (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_CV_DILATE_ERODE)) +#define GST_IS_CV_DILATE_ERODE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_CV_DILATE_ERODE)) + +typedef struct _GstCvDilateErode GstCvDilateErode; +typedef struct _GstCvDilateErodeClass GstCvDilateErodeClass; + +struct _GstCvDilateErode +{ + GstOpencvBaseTransform element; + + gint iterations; +}; + +struct _GstCvDilateErodeClass +{ + GstOpencvBaseTransformClass parent_class; +}; + +GType gst_cv_dilate_erode_get_type (void); + +G_END_DECLS + +#endif /* __GST_CV_DILATE_ERODE_H__ */ diff --git a/src/basicfilters/gstcverode.c b/src/basicfilters/gstcverode.c new file mode 100644 index 0000000..5478af4 --- /dev/null +++ b/src/basicfilters/gstcverode.c @@ -0,0 +1,130 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include <gst/gst.h> + +#include "gstcverode.h" + +GST_DEBUG_CATEGORY_STATIC (gst_cv_erode_debug); +#define GST_CAT_DEFAULT gst_cv_erode_debug + +GST_BOILERPLATE (GstCvErode, gst_cv_erode, GstCvDilateErode, + GST_TYPE_CV_DILATE_ERODE); + +static GstFlowReturn gst_cv_erode_transform_ip (GstOpencvBaseTransform * + filter, GstBuffer * buf, IplImage * img); +static GstFlowReturn gst_cv_erode_transform (GstOpencvBaseTransform * filter, + GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg); + +/* GObject vmethod implementations */ +static void +gst_cv_erode_base_init (gpointer gclass) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (gclass); + + gst_element_class_set_details_simple (element_class, + "cverode", + "Transform/Effect/Video", + "Applies cvErode OpenCV function to the image", + "Thiago Santos<thiago.sousa.santos@collabora.co.uk>"); +} + +/* initialize the cverode's class */ +static void +gst_cv_erode_class_init (GstCvErodeClass * klass) +{ + GstOpencvBaseTransformClass *gstopencvbasefilter_class; + + gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass; + + parent_class = g_type_class_peek_parent (klass); + + gstopencvbasefilter_class->cv_trans_ip_func = gst_cv_erode_transform_ip; + gstopencvbasefilter_class->cv_trans_func = gst_cv_erode_transform; +} + +/* initialize the new element + * instantiate pads and add them to element + * set pad calback functions + * initialize instance structure + */ +static void +gst_cv_erode_init (GstCvErode * filter, GstCvErodeClass * gclass) +{ +} + +static GstFlowReturn +gst_cv_erode_transform (GstOpencvBaseTransform * base, GstBuffer * buf, + IplImage * img, GstBuffer * outbuf, IplImage * outimg) +{ + GstCvDilateErode *filter = GST_CV_DILATE_ERODE (base); + + /* TODO support kernel as a parameter */ + cvErode (img, outimg, NULL, filter->iterations); + + return GST_FLOW_OK; +} + +static GstFlowReturn +gst_cv_erode_transform_ip (GstOpencvBaseTransform * base, GstBuffer * buf, + IplImage * img) +{ + GstCvDilateErode *filter = GST_CV_DILATE_ERODE (base); + + cvErode (img, img, NULL, filter->iterations); + + return GST_FLOW_OK; +} + +gboolean +gst_cv_erode_plugin_init (GstPlugin * plugin) +{ + GST_DEBUG_CATEGORY_INIT (gst_cv_erode_debug, "cverode", 0, "cverode"); + + return gst_element_register (plugin, "cverode", GST_RANK_NONE, + GST_TYPE_CV_ERODE); +} diff --git a/src/basicfilters/gstcverode.h b/src/basicfilters/gstcverode.h new file mode 100644 index 0000000..0c5055e --- /dev/null +++ b/src/basicfilters/gstcverode.h @@ -0,0 +1,84 @@ +/* + * GStreamer + * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifndef __GST_CV_ERODE_H__ +#define __GST_CV_ERODE_H__ + +#include <gst/gst.h> +#include <cv.h> +#include "gstcvdilateerode.h" + +G_BEGIN_DECLS + +/* #defines don't like whitespacey bits */ +#define GST_TYPE_CV_ERODE \ + (gst_cv_erode_get_type()) +#define GST_CV_ERODE(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_CV_ERODE,GstCvErode)) +#define GST_CV_ERODE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_CV_ERODE,GstCvErodeClass)) +#define GST_IS_CV_ERODE(obj) \ + (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_CV_ERODE)) +#define GST_IS_CV_ERODE_CLASS(klass) \ + (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_CV_ERODE)) + +typedef struct _GstCvErode GstCvErode; +typedef struct _GstCvErodeClass GstCvErodeClass; + +struct _GstCvErode +{ + GstCvDilateErode element; +}; + +struct _GstCvErodeClass +{ + GstCvDilateErodeClass parent_class; +}; + +GType gst_cv_erode_get_type (void); + +gboolean gst_cv_erode_plugin_init (GstPlugin * plugin); + +G_END_DECLS + +#endif /* __GST_CV_ERODE_H__ */ diff --git a/src/gstopencv.c b/src/gstopencv.c index 1c31f29..084e675 100644 --- a/src/gstopencv.c +++ b/src/gstopencv.c @@ -1,65 +1,74 @@ /* GStreamer * Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com> * * gstopencv.c: plugin registering * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif +#include "gstcvdilate.h" +#include "gstcverode.h" #include "gstcvsmooth.h" #include "gstedgedetect.h" #include "gstfaceblur.h" #include "gstfacedetect.h" #include "gstpyramidsegment.h" #include "gsttemplatematch.h" #include "gsttextwrite.h" static gboolean plugin_init (GstPlugin * plugin) { + + if (!gst_cv_dilate_plugin_init (plugin)) + return FALSE; + + if (!gst_cv_erode_plugin_init (plugin)) + return FALSE; + if (!gst_cv_smooth_plugin_init (plugin)) return FALSE; if (!gst_edgedetect_plugin_init (plugin)) return FALSE; if (!gst_faceblur_plugin_init (plugin)) return FALSE; if (!gst_facedetect_plugin_init (plugin)) return FALSE; if (!gst_pyramidsegment_plugin_init (plugin)) return FALSE; if (!gst_templatematch_plugin_init (plugin)) return FALSE; if (!gst_textwrite_plugin_init (plugin)) return FALSE; return TRUE; } GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR, "opencv", "GStreamer OpenCV Plugins", plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com")
Elleo/gst-opencv
2d83043bf314ca2bdf237b455f233a23514511f6
cvsmooth: Improve parameters docs
diff --git a/src/basicfilters/gstcvsmooth.c b/src/basicfilters/gstcvsmooth.c index 35ad5ab..d4228f1 100644 --- a/src/basicfilters/gstcvsmooth.c +++ b/src/basicfilters/gstcvsmooth.c @@ -1,347 +1,361 @@ /* * GStreamer * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Alternatively, the contents of this file may be used under the * GNU Lesser General Public License Version 2.1 (the "LGPL"), in * which case the following provisions apply instead of the ones * mentioned above: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <gst/gst.h> #include "gstcvsmooth.h" GST_DEBUG_CATEGORY_STATIC (gst_cv_smooth_debug); #define GST_CAT_DEFAULT gst_cv_smooth_debug static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24;" "video/x-raw-gray, depth=(int)8, bpp=(int)8") ); static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24;" "video/x-raw-gray, depth=(int)8, bpp=(int)8") ); /* Filter signals and args */ enum { /* FILL ME */ LAST_SIGNAL }; enum { PROP_0, PROP_SMOOTH_TYPE, PROP_PARAM1, PROP_PARAM2, PROP_PARAM3, PROP_PARAM4 }; /* blur-no-scale only handle: gray 8bits -> gray 16bits * FIXME there is no way in base transform to override pad's getcaps * to be property-sensitive, instead of using the template caps as * the base caps, this might lead us to negotiating rgb in this * smooth type. * * Keep it deactivated for now. */ #define GST_TYPE_CV_SMOOTH_TYPE (gst_cv_smooth_type_get_type ()) static GType gst_cv_smooth_type_get_type (void) { static GType cv_smooth_type_type = 0; static const GEnumValue smooth_types[] = { /* {CV_BLUR_NO_SCALE, "CV Blur No Scale", "blur-no-scale"}, */ {CV_BLUR, "CV Blur", "blur"}, {CV_GAUSSIAN, "CV Gaussian", "gaussian"}, {CV_MEDIAN, "CV Median", "median"}, {CV_BILATERAL, "CV Bilateral", "bilateral"}, {0, NULL, NULL}, }; if (!cv_smooth_type_type) { cv_smooth_type_type = g_enum_register_static ("GstCvSmoothTypeType", smooth_types); } return cv_smooth_type_type; } #define DEFAULT_CV_SMOOTH_TYPE CV_GAUSSIAN #define DEFAULT_PARAM1 3 #define DEFAULT_PARAM2 0.0 #define DEFAULT_PARAM3 0.0 #define DEFAULT_PARAM4 0.0 GST_BOILERPLATE (GstCvSmooth, gst_cv_smooth, GstOpencvBaseTransform, GST_TYPE_OPENCV_BASE_TRANSFORM); static void gst_cv_smooth_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_cv_smooth_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); -static GstFlowReturn gst_cv_smooth_transform_ip (GstOpencvBaseTransform * filter, - GstBuffer * buf, IplImage * img); +static GstFlowReturn gst_cv_smooth_transform_ip (GstOpencvBaseTransform * + filter, GstBuffer * buf, IplImage * img); static GstFlowReturn gst_cv_smooth_transform (GstOpencvBaseTransform * filter, GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg); /* Clean up */ static void gst_cv_smooth_finalize (GObject * obj) { G_OBJECT_CLASS (parent_class)->finalize (obj); } /* GObject vmethod implementations */ static void gst_cv_smooth_base_init (gpointer gclass) { GstElementClass *element_class = GST_ELEMENT_CLASS (gclass); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&src_factory)); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&sink_factory)); gst_element_class_set_details_simple (element_class, "cvsmooth", "Transform/Effect/Video", "Applies cvSmooth OpenCV function to the image", "Thiago Santos<thiago.sousa.santos@collabora.co.uk>"); } /* initialize the cvsmooth's class */ static void gst_cv_smooth_class_init (GstCvSmoothClass * klass) { GObjectClass *gobject_class; GstOpencvBaseTransformClass *gstopencvbasefilter_class; GstElementClass *gstelement_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass; parent_class = g_type_class_peek_parent (klass); gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_cv_smooth_finalize); gobject_class->set_property = gst_cv_smooth_set_property; gobject_class->get_property = gst_cv_smooth_get_property; gstopencvbasefilter_class->cv_trans_ip_func = gst_cv_smooth_transform_ip; gstopencvbasefilter_class->cv_trans_func = gst_cv_smooth_transform; g_object_class_install_property (gobject_class, PROP_SMOOTH_TYPE, g_param_spec_enum ("type", "type", "Smooth Type", GST_TYPE_CV_SMOOTH_TYPE, DEFAULT_CV_SMOOTH_TYPE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS) ); g_object_class_install_property (gobject_class, PROP_PARAM1, - g_param_spec_int ("param1", "param1", - "Param1 (Check cvSmooth OpenCV docs)", 1, G_MAXINT, DEFAULT_PARAM1, - G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + g_param_spec_int ("param1", "param1 (aperture width)", + "The aperture width (Must be positive and odd)." + "Check cvSmooth OpenCV docs: http://opencv.willowgarage.com" + "/documentation/image_filtering.html#cvSmooth", 1, G_MAXINT, + DEFAULT_PARAM1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PARAM2, - g_param_spec_int ("param2", "param2", - "Param2 (Check cvSmooth OpenCV docs)", 0, G_MAXINT, DEFAULT_PARAM2, - G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + g_param_spec_int ("param2", "param2 (aperture height)", + "The aperture height, if zero, the width is used." + "(Must be positive and odd or zero, unuset in median and bilateral " + "types). Check cvSmooth OpenCV docs: http://opencv.willowgarage.com" + "/documentation/image_filtering.html#cvSmooth", 0, G_MAXINT, + DEFAULT_PARAM2, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PARAM3, - g_param_spec_double ("param3", "param3", - "Param3 (Check cvSmooth OpenCV docs)", 0, G_MAXDOUBLE, DEFAULT_PARAM3, + g_param_spec_double ("param3", "param3 (gaussian standard deviation or " + "color sigma", + "If type is gaussian, this means the standard deviation." + "If type is bilateral, this means the color-sigma. If zero, " + "Default values are used." + "Check cvSmooth OpenCV docs: http://opencv.willowgarage.com" + "/documentation/image_filtering.html#cvSmooth", + 0, G_MAXDOUBLE, DEFAULT_PARAM3, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PARAM4, - g_param_spec_double ("param4", "param4", - "Param4 (Check cvSmooth OpenCV docs)", 0, G_MAXDOUBLE, DEFAULT_PARAM4, + g_param_spec_double ("param4", "param4 (spatial sigma, bilateral only)", + "Only used in bilateral type, means the spatial-sigma." + "Check cvSmooth OpenCV docs: http://opencv.willowgarage.com" + "/documentation/image_filtering.html#cvSmooth", + 0, G_MAXDOUBLE, DEFAULT_PARAM4, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); } /* initialize the new element * instantiate pads and add them to element * set pad calback functions * initialize instance structure */ static void gst_cv_smooth_init (GstCvSmooth * filter, GstCvSmoothClass * gclass) { filter->type = DEFAULT_CV_SMOOTH_TYPE; filter->param1 = DEFAULT_PARAM1; filter->param2 = DEFAULT_PARAM2; filter->param3 = DEFAULT_PARAM3; filter->param4 = DEFAULT_PARAM4; gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE); } static void gst_cv_smooth_change_type (GstCvSmooth * filter, gint value) { GST_DEBUG_OBJECT (filter, "Changing type from %d to %d", filter->type, value); if (filter->type == value) return; filter->type = value; switch (value) { case CV_GAUSSIAN: case CV_BLUR: gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), TRUE); break; default: gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE); break; } } static void gst_cv_smooth_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstCvSmooth *filter = GST_CV_SMOOTH (object); switch (prop_id) { case PROP_SMOOTH_TYPE: gst_cv_smooth_change_type (filter, g_value_get_enum (value)); break; case PROP_PARAM1:{ gint prop = g_value_get_int (value); if (prop % 2 == 1) { filter->param1 = prop; } else { GST_WARNING_OBJECT (filter, "Ignoring value for param1, not odd" "(%d)", prop); } } break; case PROP_PARAM2:{ gint prop = g_value_get_int (value); if (prop % 2 == 1 || prop == 0) { filter->param1 = prop; } else { GST_WARNING_OBJECT (filter, "Ignoring value for param2, not odd" " nor zero (%d)", prop); } } break; case PROP_PARAM3: filter->param3 = g_value_get_double (value); break; case PROP_PARAM4: filter->param4 = g_value_get_double (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_cv_smooth_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstCvSmooth *filter = GST_CV_SMOOTH (object); switch (prop_id) { case PROP_SMOOTH_TYPE: g_value_set_enum (value, filter->type); break; case PROP_PARAM1: g_value_set_int (value, filter->param1); break; case PROP_PARAM2: g_value_set_int (value, filter->param2); break; case PROP_PARAM3: g_value_set_double (value, filter->param3); break; case PROP_PARAM4: g_value_set_double (value, filter->param4); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static GstFlowReturn gst_cv_smooth_transform (GstOpencvBaseTransform * base, GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg) { GstCvSmooth *filter = GST_CV_SMOOTH (base); cvSmooth (img, outimg, filter->type, filter->param1, filter->param2, filter->param3, filter->param4); return GST_FLOW_OK; } static GstFlowReturn gst_cv_smooth_transform_ip (GstOpencvBaseTransform * base, GstBuffer * buf, IplImage * img) { GstCvSmooth *filter = GST_CV_SMOOTH (base); cvSmooth (img, img, filter->type, filter->param1, filter->param2, filter->param3, filter->param4); return GST_FLOW_OK; } gboolean gst_cv_smooth_plugin_init (GstPlugin * plugin) { GST_DEBUG_CATEGORY_INIT (gst_cv_smooth_debug, "cvsmooth", 0, "cvsmooth"); return gst_element_register (plugin, "cvsmooth", GST_RANK_NONE, GST_TYPE_CV_SMOOTH); } diff --git a/src/gstopencvbasetrans.c b/src/gstopencvbasetrans.c index 747d250..2af72a7 100644 --- a/src/gstopencvbasetrans.c +++ b/src/gstopencvbasetrans.c @@ -1,301 +1,304 @@ /* * GStreamer * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Alternatively, the contents of this file may be used under the * GNU Lesser General Public License Version 2.1 (the "LGPL"), in * which case the following provisions apply instead of the ones * mentioned above: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* TODO opencv can do scaling for some cases */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <gst/gst.h> #include "gstopencvbasetrans.h" #include "gstopencvutils.h" GST_DEBUG_CATEGORY_STATIC (gst_opencv_base_transform_debug); #define GST_CAT_DEFAULT gst_opencv_base_transform_debug /* Filter signals and args */ enum { /* FILL ME */ LAST_SIGNAL }; enum { PROP_0 }; static GstElementClass *parent_class = NULL; static void gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass * klass); static void gst_opencv_base_transform_init (GstOpencvBaseTransform * trans, GstOpencvBaseTransformClass * klass); static void gst_opencv_base_transform_base_init (gpointer gclass); static gboolean gst_opencv_base_transform_set_caps (GstBaseTransform * trans, GstCaps * incaps, GstCaps * outcaps); static GstFlowReturn gst_opencv_base_transform_transform_ip (GstBaseTransform * trans, GstBuffer * buf); -static GstFlowReturn gst_opencv_base_transform_transform (GstBaseTransform * trans, - GstBuffer * inbuf, GstBuffer * outbuf); -static gboolean gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans, - GstCaps * caps, guint * size); +static GstFlowReturn gst_opencv_base_transform_transform (GstBaseTransform * + trans, GstBuffer * inbuf, GstBuffer * outbuf); +static gboolean gst_opencv_base_transform_get_unit_size (GstBaseTransform * + trans, GstCaps * caps, guint * size); static void gst_opencv_base_transform_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_opencv_base_transform_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); GType gst_opencv_base_transform_get_type (void) { static volatile gsize opencv_base_transform_type = 0; if (g_once_init_enter (&opencv_base_transform_type)) { GType _type; static const GTypeInfo opencv_base_transform_info = { sizeof (GstOpencvBaseTransformClass), (GBaseInitFunc) gst_opencv_base_transform_base_init, NULL, (GClassInitFunc) gst_opencv_base_transform_class_init, NULL, NULL, sizeof (GstOpencvBaseTransform), 0, (GInstanceInitFunc) gst_opencv_base_transform_init, }; _type = g_type_register_static (GST_TYPE_BASE_TRANSFORM, - "GstOpencvBaseTransform", &opencv_base_transform_info, G_TYPE_FLAG_ABSTRACT); + "GstOpencvBaseTransform", &opencv_base_transform_info, + G_TYPE_FLAG_ABSTRACT); g_once_init_leave (&opencv_base_transform_type, _type); } return opencv_base_transform_type; } /* Clean up */ static void gst_opencv_base_transform_finalize (GObject * obj) { GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (obj); if (transform->cvImage) cvReleaseImage (&transform->cvImage); G_OBJECT_CLASS (parent_class)->finalize (obj); } /* GObject vmethod implementations */ static void gst_opencv_base_transform_base_init (gpointer gclass) { } static void gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; GstBaseTransformClass *basetrans_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; basetrans_class = (GstBaseTransformClass *) klass; parent_class = g_type_class_peek_parent (klass); - GST_DEBUG_CATEGORY_INIT (gst_opencv_base_transform_debug, "opencvbasetransform", 0, - "opencvbasetransform element"); + GST_DEBUG_CATEGORY_INIT (gst_opencv_base_transform_debug, + "opencvbasetransform", 0, "opencvbasetransform element"); - gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_opencv_base_transform_finalize); + gobject_class->finalize = + GST_DEBUG_FUNCPTR (gst_opencv_base_transform_finalize); gobject_class->set_property = gst_opencv_base_transform_set_property; gobject_class->get_property = gst_opencv_base_transform_get_property; basetrans_class->transform = gst_opencv_base_transform_transform; basetrans_class->transform_ip = gst_opencv_base_transform_transform_ip; basetrans_class->set_caps = gst_opencv_base_transform_set_caps; basetrans_class->get_unit_size = gst_opencv_base_transform_get_unit_size; } static void gst_opencv_base_transform_init (GstOpencvBaseTransform * transform, GstOpencvBaseTransformClass * bclass) { } static GstFlowReturn -gst_opencv_base_transform_transform (GstBaseTransform * trans, GstBuffer * inbuf, - GstBuffer * outbuf) +gst_opencv_base_transform_transform (GstBaseTransform * trans, + GstBuffer * inbuf, GstBuffer * outbuf) { GstOpencvBaseTransform *transform; GstOpencvBaseTransformClass *fclass; transform = GST_OPENCV_BASE_TRANSFORM (trans); fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform); g_return_val_if_fail (fclass->cv_trans_func != NULL, GST_FLOW_ERROR); g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR); g_return_val_if_fail (transform->out_cvImage != NULL, GST_FLOW_ERROR); transform->cvImage->imageData = (char *) GST_BUFFER_DATA (inbuf); transform->out_cvImage->imageData = (char *) GST_BUFFER_DATA (outbuf); return fclass->cv_trans_func (transform, inbuf, transform->cvImage, outbuf, transform->out_cvImage); } static GstFlowReturn gst_opencv_base_transform_transform_ip (GstBaseTransform * trans, GstBuffer * buffer) { GstOpencvBaseTransform *transform; GstOpencvBaseTransformClass *fclass; transform = GST_OPENCV_BASE_TRANSFORM (trans); fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform); g_return_val_if_fail (fclass->cv_trans_ip_func != NULL, GST_FLOW_ERROR); g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR); buffer = gst_buffer_make_writable (buffer); transform->cvImage->imageData = (char *) GST_BUFFER_DATA (buffer); /* FIXME how to release buffer? */ return fclass->cv_trans_ip_func (transform, buffer, transform->cvImage); } static gboolean gst_opencv_base_transform_set_caps (GstBaseTransform * trans, GstCaps * incaps, GstCaps * outcaps) { GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (trans); gint in_width, in_height; gint in_depth, in_channels; gint out_width, out_height; gint out_depth, out_channels; GError *in_err = NULL; GError *out_err = NULL; if (!gst_opencv_parse_iplimage_params_from_caps (incaps, &in_width, - &in_height, &in_depth, &in_channels, &in_err)) { + &in_height, &in_depth, &in_channels, &in_err)) { GST_WARNING_OBJECT (transform, "Failed to parse input caps: %s", in_err->message); g_error_free (in_err); return FALSE; } if (!gst_opencv_parse_iplimage_params_from_caps (outcaps, &out_width, - &out_height, &out_depth, &out_channels, &out_err)) { + &out_height, &out_depth, &out_channels, &out_err)) { GST_WARNING_OBJECT (transform, "Failed to parse output caps: %s", out_err->message); g_error_free (out_err); return FALSE; } if (transform->cvImage) { cvReleaseImage (&transform->cvImage); } if (transform->out_cvImage) { cvReleaseImage (&transform->out_cvImage); } transform->cvImage = cvCreateImageHeader (cvSize (in_width, in_height), in_depth, in_channels); transform->out_cvImage = cvCreateImageHeader (cvSize (out_width, out_height), out_depth, - out_channels); + out_channels); gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform), transform->in_place); return TRUE; } static gboolean gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans, GstCaps * caps, guint * size) { gint width, height; gint bpp; GstStructure *structure; structure = gst_caps_get_structure (caps, 0); if (!gst_structure_get_int (structure, "width", &width) || !gst_structure_get_int (structure, "height", &height) || !gst_structure_get_int (structure, "bpp", &bpp)) { return FALSE; } *size = width * height * bpp / 8; return TRUE; } static void gst_opencv_base_transform_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { switch (prop_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_opencv_base_transform_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { switch (prop_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } void -gst_opencv_base_transform_set_in_place (GstOpencvBaseTransform * transform, gboolean ip) +gst_opencv_base_transform_set_in_place (GstOpencvBaseTransform * transform, + gboolean ip) { transform->in_place = ip; gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform), ip); }
Elleo/gst-opencv
f77a6ea5de99e0af47ec8dcde87585ed84918d49
cvsmooth: Deactivating blur-no-scale
diff --git a/src/basicfilters/gstcvsmooth.c b/src/basicfilters/gstcvsmooth.c index ec24b2c..35ad5ab 100644 --- a/src/basicfilters/gstcvsmooth.c +++ b/src/basicfilters/gstcvsmooth.c @@ -1,338 +1,347 @@ /* * GStreamer * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Alternatively, the contents of this file may be used under the * GNU Lesser General Public License Version 2.1 (the "LGPL"), in * which case the following provisions apply instead of the ones * mentioned above: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <gst/gst.h> #include "gstcvsmooth.h" GST_DEBUG_CATEGORY_STATIC (gst_cv_smooth_debug); #define GST_CAT_DEFAULT gst_cv_smooth_debug static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24;" "video/x-raw-gray, depth=(int)8, bpp=(int)8") ); static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24;" "video/x-raw-gray, depth=(int)8, bpp=(int)8") ); /* Filter signals and args */ enum { /* FILL ME */ LAST_SIGNAL }; enum { PROP_0, PROP_SMOOTH_TYPE, PROP_PARAM1, PROP_PARAM2, PROP_PARAM3, PROP_PARAM4 }; +/* blur-no-scale only handle: gray 8bits -> gray 16bits + * FIXME there is no way in base transform to override pad's getcaps + * to be property-sensitive, instead of using the template caps as + * the base caps, this might lead us to negotiating rgb in this + * smooth type. + * + * Keep it deactivated for now. + */ + #define GST_TYPE_CV_SMOOTH_TYPE (gst_cv_smooth_type_get_type ()) static GType gst_cv_smooth_type_get_type (void) { static GType cv_smooth_type_type = 0; static const GEnumValue smooth_types[] = { - {CV_BLUR_NO_SCALE, "CV Blur No Scale", "blur-no-scale"}, +/* {CV_BLUR_NO_SCALE, "CV Blur No Scale", "blur-no-scale"}, */ {CV_BLUR, "CV Blur", "blur"}, {CV_GAUSSIAN, "CV Gaussian", "gaussian"}, {CV_MEDIAN, "CV Median", "median"}, {CV_BILATERAL, "CV Bilateral", "bilateral"}, {0, NULL, NULL}, }; if (!cv_smooth_type_type) { cv_smooth_type_type = g_enum_register_static ("GstCvSmoothTypeType", smooth_types); } return cv_smooth_type_type; } #define DEFAULT_CV_SMOOTH_TYPE CV_GAUSSIAN #define DEFAULT_PARAM1 3 #define DEFAULT_PARAM2 0.0 #define DEFAULT_PARAM3 0.0 #define DEFAULT_PARAM4 0.0 GST_BOILERPLATE (GstCvSmooth, gst_cv_smooth, GstOpencvBaseTransform, GST_TYPE_OPENCV_BASE_TRANSFORM); static void gst_cv_smooth_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_cv_smooth_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static GstFlowReturn gst_cv_smooth_transform_ip (GstOpencvBaseTransform * filter, GstBuffer * buf, IplImage * img); static GstFlowReturn gst_cv_smooth_transform (GstOpencvBaseTransform * filter, GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg); /* Clean up */ static void gst_cv_smooth_finalize (GObject * obj) { G_OBJECT_CLASS (parent_class)->finalize (obj); } /* GObject vmethod implementations */ static void gst_cv_smooth_base_init (gpointer gclass) { GstElementClass *element_class = GST_ELEMENT_CLASS (gclass); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&src_factory)); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&sink_factory)); gst_element_class_set_details_simple (element_class, "cvsmooth", "Transform/Effect/Video", "Applies cvSmooth OpenCV function to the image", "Thiago Santos<thiago.sousa.santos@collabora.co.uk>"); } /* initialize the cvsmooth's class */ static void gst_cv_smooth_class_init (GstCvSmoothClass * klass) { GObjectClass *gobject_class; GstOpencvBaseTransformClass *gstopencvbasefilter_class; GstElementClass *gstelement_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass; parent_class = g_type_class_peek_parent (klass); gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_cv_smooth_finalize); gobject_class->set_property = gst_cv_smooth_set_property; gobject_class->get_property = gst_cv_smooth_get_property; gstopencvbasefilter_class->cv_trans_ip_func = gst_cv_smooth_transform_ip; gstopencvbasefilter_class->cv_trans_func = gst_cv_smooth_transform; g_object_class_install_property (gobject_class, PROP_SMOOTH_TYPE, g_param_spec_enum ("type", "type", "Smooth Type", GST_TYPE_CV_SMOOTH_TYPE, DEFAULT_CV_SMOOTH_TYPE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS) ); g_object_class_install_property (gobject_class, PROP_PARAM1, g_param_spec_int ("param1", "param1", "Param1 (Check cvSmooth OpenCV docs)", 1, G_MAXINT, DEFAULT_PARAM1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PARAM2, g_param_spec_int ("param2", "param2", "Param2 (Check cvSmooth OpenCV docs)", 0, G_MAXINT, DEFAULT_PARAM2, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PARAM3, g_param_spec_double ("param3", "param3", "Param3 (Check cvSmooth OpenCV docs)", 0, G_MAXDOUBLE, DEFAULT_PARAM3, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PARAM4, g_param_spec_double ("param4", "param4", "Param4 (Check cvSmooth OpenCV docs)", 0, G_MAXDOUBLE, DEFAULT_PARAM4, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); } /* initialize the new element * instantiate pads and add them to element * set pad calback functions * initialize instance structure */ static void gst_cv_smooth_init (GstCvSmooth * filter, GstCvSmoothClass * gclass) { filter->type = DEFAULT_CV_SMOOTH_TYPE; filter->param1 = DEFAULT_PARAM1; filter->param2 = DEFAULT_PARAM2; filter->param3 = DEFAULT_PARAM3; filter->param4 = DEFAULT_PARAM4; gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE); } static void gst_cv_smooth_change_type (GstCvSmooth * filter, gint value) { GST_DEBUG_OBJECT (filter, "Changing type from %d to %d", filter->type, value); if (filter->type == value) return; filter->type = value; switch (value) { case CV_GAUSSIAN: case CV_BLUR: gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), TRUE); break; default: gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE); break; } } static void gst_cv_smooth_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstCvSmooth *filter = GST_CV_SMOOTH (object); switch (prop_id) { case PROP_SMOOTH_TYPE: gst_cv_smooth_change_type (filter, g_value_get_enum (value)); break; case PROP_PARAM1:{ gint prop = g_value_get_int (value); if (prop % 2 == 1) { filter->param1 = prop; } else { GST_WARNING_OBJECT (filter, "Ignoring value for param1, not odd" "(%d)", prop); } } break; case PROP_PARAM2:{ gint prop = g_value_get_int (value); if (prop % 2 == 1 || prop == 0) { filter->param1 = prop; } else { GST_WARNING_OBJECT (filter, "Ignoring value for param2, not odd" " nor zero (%d)", prop); } } break; case PROP_PARAM3: filter->param3 = g_value_get_double (value); break; case PROP_PARAM4: filter->param4 = g_value_get_double (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_cv_smooth_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstCvSmooth *filter = GST_CV_SMOOTH (object); switch (prop_id) { case PROP_SMOOTH_TYPE: g_value_set_enum (value, filter->type); break; case PROP_PARAM1: g_value_set_int (value, filter->param1); break; case PROP_PARAM2: g_value_set_int (value, filter->param2); break; case PROP_PARAM3: g_value_set_double (value, filter->param3); break; case PROP_PARAM4: g_value_set_double (value, filter->param4); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static GstFlowReturn gst_cv_smooth_transform (GstOpencvBaseTransform * base, GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg) { GstCvSmooth *filter = GST_CV_SMOOTH (base); cvSmooth (img, outimg, filter->type, filter->param1, filter->param2, filter->param3, filter->param4); return GST_FLOW_OK; } static GstFlowReturn gst_cv_smooth_transform_ip (GstOpencvBaseTransform * base, GstBuffer * buf, IplImage * img) { GstCvSmooth *filter = GST_CV_SMOOTH (base); cvSmooth (img, img, filter->type, filter->param1, filter->param2, filter->param3, filter->param4); return GST_FLOW_OK; } gboolean gst_cv_smooth_plugin_init (GstPlugin * plugin) { GST_DEBUG_CATEGORY_INIT (gst_cv_smooth_debug, "cvsmooth", 0, "cvsmooth"); return gst_element_register (plugin, "cvsmooth", GST_RANK_NONE, GST_TYPE_CV_SMOOTH); }