repo
string
commit
string
message
string
diff
string
cfaerber/Graphics-ColorNames-WWW
bbee250d90dac9cc2b20c1b58baa2f37234c3da3
Graphics-ColorNames-WWW-1.00
diff --git a/IE.pm b/IE.pm index 1be2e48..16085d4 100644 --- a/IE.pm +++ b/IE.pm @@ -1,198 +1,198 @@ package Graphics::ColorNames::IE; =head1 NAME Graphics::ColorNames::IE - MS Internet Explorer color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::IE; $NameTable = Graphics::ColorNames::IE->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values recognized by Microsoft Internet Explorer. =head2 Note Although Microsoft calls them "X11 color names", some of them are not identical to the definitions in the X Specification. =head1 SEE ALSO C<Graphics::ColorNames>, MSDN <http://msdn.microsoft.com/library/en-us/dnwebgen/html/X11_names.asp> =head1 AUTHOR -Claus Färber <cfaerber@cpan.org> +Claus Färber <CFAERBER@cpan.org> =head1 LICENSE -Copyright © 2005 Claus Färber +Copyright © 2005-2008 Claus Färber Based on C<Graphics::ColorNames::HTML> Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut require 5.006; use strict; use warnings; our $VERSION = '1.00'; sub NamesRgbTable() { use integer; return { (lc 'AliceBlue') => 0xF0F8FF, # 240,248,255 (lc 'AntiqueWhite') => 0xFAEBD7, # 250,235,215 (lc 'Aqua') => 0x00FFFF, # 0,255,255 (lc 'Aquamarine') => 0x7FFFD4, # 127,255,212 (lc 'Azure') => 0xF0FFFF, # 240,255,255 (lc 'Beige') => 0xF5F5DC, # 245,245,220 (lc 'Bisque') => 0xFFE4C4, # 255,228,196 (lc 'Black') => 0x000000, # 0,0,0 (lc 'BlanchedAlmond') => 0xFFEBCD, # 255,235,205 (lc 'Blue') => 0x0000FF, # 0,0,255 (lc 'BlueViolet') => 0x8A2BE2, # 138,43,226 (lc 'Brown') => 0xA52A2A, # 165,42,42 (lc 'BurlyWood') => 0xDEB887, # 222,184,135 (lc 'CadetBlue') => 0x5F9EA0, # 95,158,160 (lc 'Chartreuse') => 0x7FFF00, # 127,255,0 (lc 'Chocolate') => 0xD2691E, # 210,105,30 (lc 'Coral') => 0xFF7F50, # 255,127,80 (lc 'CornflowerBlue') => 0x6495ED, # 100,149,237 (lc 'Cornsilk') => 0xFFF8DC, # 255,248,220 (lc 'Crimson') => 0xDC143C, # 220,20,60 (lc 'Cyan') => 0x00FFFF, # 0,255,255 (lc 'DarkBlue') => 0x00008B, # 0,0,139 (lc 'DarkCyan') => 0x008B8B, # 0,139,139 (lc 'DarkGoldenrod') => 0xB8860B, # 184,134,11 (lc 'DarkGray') => 0xA9A9A9, # 169,169,169 (lc 'DarkGreen') => 0x006400, # 0,100,0 (lc 'DarkKhaki') => 0xBDB76B, # 189,183,107 (lc 'DarkMagenta') => 0x8B008B, # 139,0,139 (lc 'DarkOliveGreen') => 0x556B2F, # 85,107,47 (lc 'DarkOrange') => 0xFF8C00, # 255,140,0 (lc 'DarkOrchid') => 0x9932CC, # 153,50,204 (lc 'DarkRed') => 0x8B0000, # 139,0,0 (lc 'DarkSalmon') => 0xE9967A, # 233,150,122 (lc 'DarkSeaGreen') => 0x8FBC8F, # 143,188,143 (lc 'DarkSlateBlue') => 0x483D8B, # 72,61,139 (lc 'DarkSlateGray') => 0x2F4F4F, # 47,79,79 (lc 'DarkTurquoise') => 0x00CED1, # 0,206,209 (lc 'DarkViolet') => 0x9400D3, # 148,0,211 (lc 'DeepPink') => 0xFF1493, # 255,20,147 (lc 'DeepSkyBlue') => 0x00BFFF, # 0,191,255 (lc 'DimGray') => 0x696969, # 105,105,105 (lc 'DodgerBlue') => 0x1E90FF, # 30,144,255 (lc 'FireBrick') => 0xB22222, # 178,34,34 (lc 'FloralWhite') => 0xFFFAF0, # 255,250,240 (lc 'ForestGreen') => 0x228B22, # 34,139,34 (lc 'Fuchsia') => 0xFF00FF, # 255,0,255 (lc 'Gainsboro') => 0xDCDCDC, # 220,220,220 (lc 'GhostWhite') => 0xF8F8FF, # 248,248,255 (lc 'Gold') => 0xFFD700, # 255,215,0 (lc 'Goldenrod') => 0xDAA520, # 218,165,32 (lc 'Gray') => 0x808080, # 128,128,128 (lc 'Green') => 0x008000, # 0,128,0 (lc 'GreenYellow') => 0xADFF2F, # 173,255,47 (lc 'Honeydew') => 0xF0FFF0, # 240,255,240 (lc 'HotPink') => 0xFF69B4, # 255,105,180 (lc 'IndianRed') => 0xCD5C5C, # 205,92,92 (lc 'Indigo') => 0x4B0082, # 75,0,130 (lc 'Ivory') => 0xFFFFF0, # 255,255,240 (lc 'Khaki') => 0xF0E68C, # 240,230,140 (lc 'Lavender') => 0xE6E6FA, # 230,230,250 (lc 'LavenderBlush') => 0xFFF0F5, # 255,240,245 (lc 'LawnGreen') => 0x7CFC00, # 124,252,0 (lc 'LemonChiffon') => 0xFFFACD, # 255,250,205 (lc 'LightBlue') => 0xADD8E6, # 173,216,230 (lc 'LightCoral') => 0xF08080, # 240,128,128 (lc 'LightCyan') => 0xE0FFFF, # 224,255,255 (lc 'LightGoldenrodYellow') => 0xFAFAD2, # 250,250,210 (lc 'LightGreen') => 0x90EE90, # 144,238,144 (lc 'LightGrey') => 0xD3D3D3, # 211,211,211 (lc 'LightPink') => 0xFFB6C1, # 255,182,193 (lc 'LightSalmon') => 0xFFA07A, # 255,160,122 (lc 'LightSeaGreen') => 0x20B2AA, # 32,178,170 (lc 'LightSkyBlue') => 0x87CEFA, # 135,206,250 (lc 'LightSlateGray') => 0x778899, # 119,136,153 (lc 'LightSteelBlue') => 0xB0C4DE, # 176,196,222 (lc 'LightYellow') => 0xFFFFE0, # 255,255,224 (lc 'Lime') => 0x00FF00, # 0,255,0 (lc 'LimeGreen') => 0x32CD32, # 50,205,50 (lc 'Linen') => 0xFAF0E6, # 250,240,230 (lc 'Magenta') => 0xFF00FF, # 255,0,255 (lc 'Maroon') => 0x800000, # 128,0,0 (lc 'MediumAquamarine') => 0x66CDAA, # 102,205,170 (lc 'MediumBlue') => 0x0000CD, # 0,0,205 (lc 'MediumOrchid') => 0xBA55D3, # 186,85,211 (lc 'MediumPurple') => 0x9370DB, # 147,112,219 (lc 'MediumSeaGreen') => 0x3CB371, # 60,179,113 (lc 'MediumSlateBlue') => 0x7B68EE, # 123,104,238 (lc 'MediumSpringGreen') => 0x00FA9A, # 0,250,154 (lc 'MediumTurquoise') => 0x48D1CC, # 72,209,204 (lc 'MediumVioletRed') => 0xC71585, # 199,21,133 (lc 'MidnightBlue') => 0x191970, # 25,25,112 (lc 'MintCream') => 0xF5FFFA, # 245,255,250 (lc 'MistyRose') => 0xFFE4E1, # 255,228,225 (lc 'Moccasin') => 0xFFE4B5, # 255,228,181 (lc 'NavajoWhite') => 0xFFDEAD, # 255,222,173 (lc 'Navy') => 0x000080, # 0,0,128 (lc 'OldLace') => 0xFDF5E6, # 253,245,230 (lc 'Olive') => 0x808000, # 128,128,0 (lc 'OliveDrab') => 0x6B8E23, # 107,142,35 (lc 'Orange') => 0xFFA500, # 255,165,0 (lc 'OrangeRed') => 0xFF4500, # 255,69,0 (lc 'Orchid') => 0xDA70D6, # 218,112,214 (lc 'PaleGoldenrod') => 0xEEE8AA, # 238,232,170 (lc 'PaleGreen') => 0x98FB98, # 152,251,152 (lc 'PaleTurquoise') => 0xAFEEEE, # 175,238,238 (lc 'PaleVioletRed') => 0xDB7093, # 219,112,147 (lc 'PapayaWhip') => 0xFFEFD5, # 255,239,213 (lc 'PeachPuff') => 0xFFDAB9, # 255,218,185 (lc 'Peru') => 0xCD853F, # 205,133,63 (lc 'Pink') => 0xFFC0CB, # 255,192,203 (lc 'Plum') => 0xDDA0DD, # 221,160,221 (lc 'PowderBlue') => 0xB0E0E6, # 176,224,230 (lc 'Purple') => 0x800080, # 128,0,128 (lc 'Red') => 0xFF0000, # 255,0,0 (lc 'RosyBrown') => 0xBC8F8F, # 188,143,143 (lc 'RoyalBlue') => 0x4169E1, # 65,105,225 (lc 'SaddleBrown') => 0x8B4513, # 139,69,19 (lc 'Salmon') => 0xFA8072, # 250,128,114 (lc 'SandyBrown') => 0xF4A460, # 244,164,96 (lc 'SeaGreen') => 0x2E8B57, # 46,139,87 (lc 'Seashell') => 0xFFF5EE, # 255,245,238 (lc 'Sienna') => 0xA0522D, # 160,82,45 (lc 'Silver') => 0xC0C0C0, # 192,192,192 (lc 'SkyBlue') => 0x87CEEB, # 135,206,235 (lc 'SlateBlue') => 0x6A5ACD, # 106,90,205 (lc 'SlateGray') => 0x708090, # 112,128,144 (lc 'Snow') => 0xFFFAFA, # 255,250,250 (lc 'SpringGreen') => 0x00FF7F, # 0,255,127 (lc 'SteelBlue') => 0x4682B4, # 70,130,180 (lc 'Tan') => 0xD2B48C, # 210,180,140 (lc 'Teal') => 0x008080, # 0,128,128 (lc 'Thistle') => 0xD8BFD8, # 216,191,216 (lc 'Tomato') => 0xFF6347, # 255,99,71 (lc 'Turquoise') => 0x40E0D0, # 64,224,208 (lc 'Violet') => 0xEE82EE, # 238,130,238 (lc 'Wheat') => 0xF5DEB3, # 245,222,179 (lc 'White') => 0xFFFFFF, # 255,255,255 (lc 'WhiteSmoke') => 0xF5F5F5, # 245,245,245 (lc 'Yellow') => 0xFFFF00, # 255,255,0 (lc 'YellowGreen') => 0x9ACD32, # 154,205,50 }; } 1; __END__ diff --git a/META.yml b/META.yml index cae8c03..f53091c 100644 --- a/META.yml +++ b/META.yml @@ -1,11 +1,14 @@ -# http://module-build.sourceforge.net/META-spec.html -#XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX# -name: Graphics-ColorNames-WWW -version: 0.01 -version_from: WWW.pm -installdirs: site -requires: +--- #YAML:1.0 +name: Graphics-ColorNames-WWW +version: 1.00 +abstract: WWW color names and equivalent RGB values +license: ~ +author: + - Claus Färber <CFAERBER@cpan.org> +generated_by: ExtUtils::MakeMaker version 6.42 +distribution_type: module +requires: Graphics::ColorNames: 0.32 - -distribution_type: module -generated_by: ExtUtils::MakeMaker version 6.17 +meta-spec: + url: http://module-build.sourceforge.net/META-spec-v1.3.html + version: 1.3 diff --git a/Makefile.PL b/Makefile.PL index e5175b7..b01d070 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,13 +1,13 @@ use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'Graphics::ColorNames::WWW', 'VERSION_FROM' => 'WWW.pm', # finds $VERSION 'PREREQ_PM' => { 'Graphics::ColorNames' => 0.32, }, ($] >= 5.005 ? ## Add these new keywords supported since 5.005 (ABSTRACT_FROM => 'WWW.pm', # retrieve abstract from module - AUTHOR => 'Claus Färber <perl@faerber.muc.de>') : ()), + AUTHOR => 'Claus Färber <CFAERBER@cpan.org>') : ()), ); diff --git a/SVG.pm b/SVG.pm index a9fb29e..5eb4f9f 100644 --- a/SVG.pm +++ b/SVG.pm @@ -1,208 +1,208 @@ package Graphics::ColorNames::SVG; =head1 NAME Graphics::ColorNames::SVG - SVG color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::SVG; $NameTable = Graphics::ColorNames::SVG->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from the SVG 1.2 Specification. =head2 Note Reportedly "fuchsia" was misspelled "fuscia" in an unidentified SVG specification. It also appears to be a common misspelling, so both names are recognized. =head1 SEE ALSO C<Graphics::ColorNames>, SVG 1.2 Specificiation <http://www.w3.org/SVG/> =head1 AUTHOR -Claus Färber <cfaerber@cpan.org> +Claus Färber <CFAERBER@cpan.org> =head1 LICENSE -Copyright © 2005 Claus Färber +Copyright © 2005-2008 Claus Färber Based on C<Graphics::ColorNames::HTML> Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut require 5.006; use strict; use warnings; our $VERSION = '1.00'; sub NamesRgbTable() { sub rgb { ($_[0] << 16) + ($_[1] << 8) + ($_[2]) } use integer; return { 'aliceblue' => rgb(240, 248, 255), 'antiquewhite' => rgb(250, 235, 215), 'aqua' => rgb( 0, 255, 255), 'aquamarine' => rgb(127, 255, 212), 'azure' => rgb(240, 255, 255), 'beige' => rgb(245, 245, 220), 'bisque' => rgb(255, 228, 196), 'black' => rgb( 0, 0, 0), 'blanchedalmond' => rgb(255, 235, 205), 'blue' => rgb( 0, 0, 255), 'blueviolet' => rgb(138, 43, 226), 'brown' => rgb(165, 42, 42), 'burlywood' => rgb(222, 184, 135), 'cadetblue' => rgb( 95, 158, 160), 'chartreuse' => rgb(127, 255, 0), 'chocolate' => rgb(210, 105, 30), 'coral' => rgb(255, 127, 80), 'cornflowerblue' => rgb(100, 149, 237), 'cornsilk' => rgb(255, 248, 220), 'crimson' => rgb(220, 20, 60), 'cyan' => rgb( 0, 255, 255), 'darkblue' => rgb( 0, 0, 139), 'darkcyan' => rgb( 0, 139, 139), 'darkgoldenrod' => rgb(184, 134, 11), 'darkgray' => rgb(169, 169, 169), 'darkgreen' => rgb( 0, 100, 0), 'darkgrey' => rgb(169, 169, 169), 'darkkhaki' => rgb(189, 183, 107), 'darkmagenta' => rgb(139, 0, 139), 'darkolivegreen' => rgb( 85, 107, 47), 'darkorange' => rgb(255, 140, 0), 'darkorchid' => rgb(153, 50, 204), 'darkred' => rgb(139, 0, 0), 'darksalmon' => rgb(233, 150, 122), 'darkseagreen' => rgb(143, 188, 143), 'darkslateblue' => rgb( 72, 61, 139), 'darkslategray' => rgb( 47, 79, 79), 'darkslategrey' => rgb( 47, 79, 79), 'darkturquoise' => rgb( 0, 206, 209), 'darkviolet' => rgb(148, 0, 211), 'deeppink' => rgb(255, 20, 147), 'deepskyblue' => rgb( 0, 191, 255), 'dimgray' => rgb(105, 105, 105), 'dimgrey' => rgb(105, 105, 105), 'dodgerblue' => rgb( 30, 144, 255), 'firebrick' => rgb(178, 34, 34), 'floralwhite' => rgb(255, 250, 240), 'forestgreen' => rgb( 34, 139, 34), 'fuchsia' => 0xff00ff, # "fuscia" is incorrect but common 'fuscia' => 0xff00ff, # mis-spelling... 'gainsboro' => rgb(220, 220, 220), 'ghostwhite' => rgb(248, 248, 255), 'gold' => rgb(255, 215, 0), 'goldenrod' => rgb(218, 165, 32), 'gray' => rgb(128, 128, 128), 'grey' => rgb(128, 128, 128), 'green' => rgb( 0, 128, 0), 'greenyellow' => rgb(173, 255, 47), 'honeydew' => rgb(240, 255, 240), 'hotpink' => rgb(255, 105, 180), 'indianred' => rgb(205, 92, 92), 'indigo' => rgb( 75, 0, 130), 'ivory' => rgb(255, 255, 240), 'khaki' => rgb(240, 230, 140), 'lavender' => rgb(230, 230, 250), 'lavenderblush' => rgb(255, 240, 245), 'lawngreen' => rgb(124, 252, 0), 'lemonchiffon' => rgb(255, 250, 205), 'lightblue' => rgb(173, 216, 230), 'lightcoral' => rgb(240, 128, 128), 'lightcyan' => rgb(224, 255, 255), 'lightgoldenrodyellow' => rgb(250, 250, 210), 'lightgray' => rgb(211, 211, 211), 'lightgreen' => rgb(144, 238, 144), 'lightgrey' => rgb(211, 211, 211), 'lightpink' => rgb(255, 182, 193), 'lightsalmon' => rgb(255, 160, 122), 'lightseagreen' => rgb( 32, 178, 170), 'lightskyblue' => rgb(135, 206, 250), 'lightslategray' => rgb(119, 136, 153), 'lightslategrey' => rgb(119, 136, 153), 'lightsteelblue' => rgb(176, 196, 222), 'lightyellow' => rgb(255, 255, 224), 'lime' => rgb( 0, 255, 0), 'limegreen' => rgb( 50, 205, 50), 'linen' => rgb(250, 240, 230), 'magenta' => rgb(255, 0, 255), 'maroon' => rgb(128, 0, 0), 'mediumaquamarine' => rgb(102, 205, 170), 'mediumblue' => rgb( 0, 0, 205), 'mediumorchid' => rgb(186, 85, 211), 'mediumpurple' => rgb(147, 112, 219), 'mediumseagreen' => rgb( 60, 179, 113), 'mediumslateblue' => rgb(123, 104, 238), 'mediumspringgreen' => rgb( 0, 250, 154), 'mediumturquoise' => rgb( 72, 209, 204), 'mediumvioletred' => rgb(199, 21, 133), 'midnightblue' => rgb( 25, 25, 112), 'mintcream' => rgb(245, 255, 250), 'mistyrose' => rgb(255, 228, 225), 'moccasin' => rgb(255, 228, 181), 'navajowhite' => rgb(255, 222, 173), 'navy' => rgb( 0, 0, 128), 'oldlace' => rgb(253, 245, 230), 'olive' => rgb(128, 128, 0), 'olivedrab' => rgb(107, 142, 35), 'orange' => rgb(255, 165, 0), 'orangered' => rgb(255, 69, 0), 'orchid' => rgb(218, 112, 214), 'palegoldenrod' => rgb(238, 232, 170), 'palegreen' => rgb(152, 251, 152), 'paleturquoise' => rgb(175, 238, 238), 'palevioletred' => rgb(219, 112, 147), 'papayawhip' => rgb(255, 239, 213), 'peachpuff' => rgb(255, 218, 185), 'peru' => rgb(205, 133, 63), 'pink' => rgb(255, 192, 203), 'plum' => rgb(221, 160, 221), 'powderblue' => rgb(176, 224, 230), 'purple' => rgb(128, 0, 128), 'red' => rgb(255, 0, 0), 'rosybrown' => rgb(188, 143, 143), 'royalblue' => rgb( 65, 105, 225), 'saddlebrown' => rgb(139, 69, 19), 'salmon' => rgb(250, 128, 114), 'sandybrown' => rgb(244, 164, 96), 'seagreen' => rgb( 46, 139, 87), 'seashell' => rgb(255, 245, 238), 'sienna' => rgb(160, 82, 45), 'silver' => rgb(192, 192, 192), 'skyblue' => rgb(135, 206, 235), 'slateblue' => rgb(106, 90, 205), 'slategray' => rgb(112, 128, 144), 'slategrey' => rgb(112, 128, 144), 'snow' => rgb(255, 250, 250), 'springgreen' => rgb( 0, 255, 127), 'steelblue' => rgb( 70, 130, 180), 'tan' => rgb(210, 180, 140), 'teal' => rgb( 0, 128, 128), 'thistle' => rgb(216, 191, 216), 'tomato' => rgb(255, 99, 71), 'turquoise' => rgb( 64, 224, 208), 'violet' => rgb(238, 130, 238), 'wheat' => rgb(245, 222, 179), 'white' => rgb(255, 255, 255), 'whitesmoke' => rgb(245, 245, 245), 'yellow' => rgb(255, 255, 0), 'yellowgreen' => rgb(154, 205, 50), }; } 1; __END__ diff --git a/WWW.pm b/WWW.pm index 80701a9..62a5b5c 100644 --- a/WWW.pm +++ b/WWW.pm @@ -1,68 +1,68 @@ package Graphics::ColorNames::WWW; =head1 NAME Graphics::ColorNames::WWW - WWW color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::WWW; $NameTable = Graphics::ColorNames::WWW->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This modules defines color names and their associated RGB values from various WWW specifications and implementations. =cut # Note: Mozilla is a subset of SVG # Note: HTML is a subset of HTML my @modules = ( 'SVG', # 'HTML', -- subset of SVG # 'Mozilla', -- subset of SVG # 'IE', -- subset of SVG ); =head1 SEE ALSO C<Graphics::ColorNames> =head1 AUTHOR -Claus Färber <cfaerber@cpan.org> +Claus Färber <CFAERBER@cpan.org> =head1 LICENSE -Copyright © 2005 Claus Färber +Copyright © 2005-2008 Claus Färber Based on C<Graphics::ColorNames::HTML> Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut require 5.006; use strict; use warnings; -our $VERSION = '0.01'; +our $VERSION = '1.00'; sub NamesRgbTable() { my %map = (); foreach (@modules) { eval "use Graphics::ColorNames::$_;"; die $@ if $@; %map = ((%map),%{eval "Graphics::ColorNames::$_->NamesRgbTable"}); } return \%map; } 1; __END__
cfaerber/Graphics-ColorNames-WWW
8e253cdfa6ef54341db4a52d4d6706357ee6b654
Graphics-ColorNames-WWW-0.01
diff --git a/IE.pm b/IE.pm new file mode 100644 index 0000000..1be2e48 --- /dev/null +++ b/IE.pm @@ -0,0 +1,198 @@ +package Graphics::ColorNames::IE; + +=head1 NAME + +Graphics::ColorNames::IE - MS Internet Explorer color names and equivalent RGB values + +=head1 SYNOPSIS + + require Graphics::ColorNames::IE; + + $NameTable = Graphics::ColorNames::IE->NamesRgbTable(); + $RgbBlack = $NameTable->{black}; + +=head1 DESCRIPTION + +This module defines color names and their associated RGB values recognized by +Microsoft Internet Explorer. + +=head2 Note + +Although Microsoft calls them "X11 color names", some of them are not identical +to the definitions in the X Specification. + +=head1 SEE ALSO + +C<Graphics::ColorNames>, MSDN <http://msdn.microsoft.com/library/en-us/dnwebgen/html/X11_names.asp> + +=head1 AUTHOR + +Claus Färber <cfaerber@cpan.org> + +=head1 LICENSE + +Copyright © 2005 Claus Färber + +Based on C<Graphics::ColorNames::HTML> Copyright © 2001-2004 Robert Rothenberg. + +All rights reserved. This program is free software; you can redistribute it +and/or modify it under the same terms as Perl itself. + +=cut + +require 5.006; + +use strict; +use warnings; + +our $VERSION = '1.00'; + +sub NamesRgbTable() { + use integer; + return { + (lc 'AliceBlue') => 0xF0F8FF, # 240,248,255 + (lc 'AntiqueWhite') => 0xFAEBD7, # 250,235,215 + (lc 'Aqua') => 0x00FFFF, # 0,255,255 + (lc 'Aquamarine') => 0x7FFFD4, # 127,255,212 + (lc 'Azure') => 0xF0FFFF, # 240,255,255 + (lc 'Beige') => 0xF5F5DC, # 245,245,220 + (lc 'Bisque') => 0xFFE4C4, # 255,228,196 + (lc 'Black') => 0x000000, # 0,0,0 + (lc 'BlanchedAlmond') => 0xFFEBCD, # 255,235,205 + (lc 'Blue') => 0x0000FF, # 0,0,255 + (lc 'BlueViolet') => 0x8A2BE2, # 138,43,226 + (lc 'Brown') => 0xA52A2A, # 165,42,42 + (lc 'BurlyWood') => 0xDEB887, # 222,184,135 + (lc 'CadetBlue') => 0x5F9EA0, # 95,158,160 + (lc 'Chartreuse') => 0x7FFF00, # 127,255,0 + (lc 'Chocolate') => 0xD2691E, # 210,105,30 + (lc 'Coral') => 0xFF7F50, # 255,127,80 + (lc 'CornflowerBlue') => 0x6495ED, # 100,149,237 + (lc 'Cornsilk') => 0xFFF8DC, # 255,248,220 + (lc 'Crimson') => 0xDC143C, # 220,20,60 + (lc 'Cyan') => 0x00FFFF, # 0,255,255 + (lc 'DarkBlue') => 0x00008B, # 0,0,139 + (lc 'DarkCyan') => 0x008B8B, # 0,139,139 + (lc 'DarkGoldenrod') => 0xB8860B, # 184,134,11 + (lc 'DarkGray') => 0xA9A9A9, # 169,169,169 + (lc 'DarkGreen') => 0x006400, # 0,100,0 + (lc 'DarkKhaki') => 0xBDB76B, # 189,183,107 + (lc 'DarkMagenta') => 0x8B008B, # 139,0,139 + (lc 'DarkOliveGreen') => 0x556B2F, # 85,107,47 + (lc 'DarkOrange') => 0xFF8C00, # 255,140,0 + (lc 'DarkOrchid') => 0x9932CC, # 153,50,204 + (lc 'DarkRed') => 0x8B0000, # 139,0,0 + (lc 'DarkSalmon') => 0xE9967A, # 233,150,122 + (lc 'DarkSeaGreen') => 0x8FBC8F, # 143,188,143 + (lc 'DarkSlateBlue') => 0x483D8B, # 72,61,139 + (lc 'DarkSlateGray') => 0x2F4F4F, # 47,79,79 + (lc 'DarkTurquoise') => 0x00CED1, # 0,206,209 + (lc 'DarkViolet') => 0x9400D3, # 148,0,211 + (lc 'DeepPink') => 0xFF1493, # 255,20,147 + (lc 'DeepSkyBlue') => 0x00BFFF, # 0,191,255 + (lc 'DimGray') => 0x696969, # 105,105,105 + (lc 'DodgerBlue') => 0x1E90FF, # 30,144,255 + (lc 'FireBrick') => 0xB22222, # 178,34,34 + (lc 'FloralWhite') => 0xFFFAF0, # 255,250,240 + (lc 'ForestGreen') => 0x228B22, # 34,139,34 + (lc 'Fuchsia') => 0xFF00FF, # 255,0,255 + (lc 'Gainsboro') => 0xDCDCDC, # 220,220,220 + (lc 'GhostWhite') => 0xF8F8FF, # 248,248,255 + (lc 'Gold') => 0xFFD700, # 255,215,0 + (lc 'Goldenrod') => 0xDAA520, # 218,165,32 + (lc 'Gray') => 0x808080, # 128,128,128 + (lc 'Green') => 0x008000, # 0,128,0 + (lc 'GreenYellow') => 0xADFF2F, # 173,255,47 + (lc 'Honeydew') => 0xF0FFF0, # 240,255,240 + (lc 'HotPink') => 0xFF69B4, # 255,105,180 + (lc 'IndianRed') => 0xCD5C5C, # 205,92,92 + (lc 'Indigo') => 0x4B0082, # 75,0,130 + (lc 'Ivory') => 0xFFFFF0, # 255,255,240 + (lc 'Khaki') => 0xF0E68C, # 240,230,140 + (lc 'Lavender') => 0xE6E6FA, # 230,230,250 + (lc 'LavenderBlush') => 0xFFF0F5, # 255,240,245 + (lc 'LawnGreen') => 0x7CFC00, # 124,252,0 + (lc 'LemonChiffon') => 0xFFFACD, # 255,250,205 + (lc 'LightBlue') => 0xADD8E6, # 173,216,230 + (lc 'LightCoral') => 0xF08080, # 240,128,128 + (lc 'LightCyan') => 0xE0FFFF, # 224,255,255 + (lc 'LightGoldenrodYellow') => 0xFAFAD2, # 250,250,210 + (lc 'LightGreen') => 0x90EE90, # 144,238,144 + (lc 'LightGrey') => 0xD3D3D3, # 211,211,211 + (lc 'LightPink') => 0xFFB6C1, # 255,182,193 + (lc 'LightSalmon') => 0xFFA07A, # 255,160,122 + (lc 'LightSeaGreen') => 0x20B2AA, # 32,178,170 + (lc 'LightSkyBlue') => 0x87CEFA, # 135,206,250 + (lc 'LightSlateGray') => 0x778899, # 119,136,153 + (lc 'LightSteelBlue') => 0xB0C4DE, # 176,196,222 + (lc 'LightYellow') => 0xFFFFE0, # 255,255,224 + (lc 'Lime') => 0x00FF00, # 0,255,0 + (lc 'LimeGreen') => 0x32CD32, # 50,205,50 + (lc 'Linen') => 0xFAF0E6, # 250,240,230 + (lc 'Magenta') => 0xFF00FF, # 255,0,255 + (lc 'Maroon') => 0x800000, # 128,0,0 + (lc 'MediumAquamarine') => 0x66CDAA, # 102,205,170 + (lc 'MediumBlue') => 0x0000CD, # 0,0,205 + (lc 'MediumOrchid') => 0xBA55D3, # 186,85,211 + (lc 'MediumPurple') => 0x9370DB, # 147,112,219 + (lc 'MediumSeaGreen') => 0x3CB371, # 60,179,113 + (lc 'MediumSlateBlue') => 0x7B68EE, # 123,104,238 + (lc 'MediumSpringGreen') => 0x00FA9A, # 0,250,154 + (lc 'MediumTurquoise') => 0x48D1CC, # 72,209,204 + (lc 'MediumVioletRed') => 0xC71585, # 199,21,133 + (lc 'MidnightBlue') => 0x191970, # 25,25,112 + (lc 'MintCream') => 0xF5FFFA, # 245,255,250 + (lc 'MistyRose') => 0xFFE4E1, # 255,228,225 + (lc 'Moccasin') => 0xFFE4B5, # 255,228,181 + (lc 'NavajoWhite') => 0xFFDEAD, # 255,222,173 + (lc 'Navy') => 0x000080, # 0,0,128 + (lc 'OldLace') => 0xFDF5E6, # 253,245,230 + (lc 'Olive') => 0x808000, # 128,128,0 + (lc 'OliveDrab') => 0x6B8E23, # 107,142,35 + (lc 'Orange') => 0xFFA500, # 255,165,0 + (lc 'OrangeRed') => 0xFF4500, # 255,69,0 + (lc 'Orchid') => 0xDA70D6, # 218,112,214 + (lc 'PaleGoldenrod') => 0xEEE8AA, # 238,232,170 + (lc 'PaleGreen') => 0x98FB98, # 152,251,152 + (lc 'PaleTurquoise') => 0xAFEEEE, # 175,238,238 + (lc 'PaleVioletRed') => 0xDB7093, # 219,112,147 + (lc 'PapayaWhip') => 0xFFEFD5, # 255,239,213 + (lc 'PeachPuff') => 0xFFDAB9, # 255,218,185 + (lc 'Peru') => 0xCD853F, # 205,133,63 + (lc 'Pink') => 0xFFC0CB, # 255,192,203 + (lc 'Plum') => 0xDDA0DD, # 221,160,221 + (lc 'PowderBlue') => 0xB0E0E6, # 176,224,230 + (lc 'Purple') => 0x800080, # 128,0,128 + (lc 'Red') => 0xFF0000, # 255,0,0 + (lc 'RosyBrown') => 0xBC8F8F, # 188,143,143 + (lc 'RoyalBlue') => 0x4169E1, # 65,105,225 + (lc 'SaddleBrown') => 0x8B4513, # 139,69,19 + (lc 'Salmon') => 0xFA8072, # 250,128,114 + (lc 'SandyBrown') => 0xF4A460, # 244,164,96 + (lc 'SeaGreen') => 0x2E8B57, # 46,139,87 + (lc 'Seashell') => 0xFFF5EE, # 255,245,238 + (lc 'Sienna') => 0xA0522D, # 160,82,45 + (lc 'Silver') => 0xC0C0C0, # 192,192,192 + (lc 'SkyBlue') => 0x87CEEB, # 135,206,235 + (lc 'SlateBlue') => 0x6A5ACD, # 106,90,205 + (lc 'SlateGray') => 0x708090, # 112,128,144 + (lc 'Snow') => 0xFFFAFA, # 255,250,250 + (lc 'SpringGreen') => 0x00FF7F, # 0,255,127 + (lc 'SteelBlue') => 0x4682B4, # 70,130,180 + (lc 'Tan') => 0xD2B48C, # 210,180,140 + (lc 'Teal') => 0x008080, # 0,128,128 + (lc 'Thistle') => 0xD8BFD8, # 216,191,216 + (lc 'Tomato') => 0xFF6347, # 255,99,71 + (lc 'Turquoise') => 0x40E0D0, # 64,224,208 + (lc 'Violet') => 0xEE82EE, # 238,130,238 + (lc 'Wheat') => 0xF5DEB3, # 245,222,179 + (lc 'White') => 0xFFFFFF, # 255,255,255 + (lc 'WhiteSmoke') => 0xF5F5F5, # 245,245,245 + (lc 'Yellow') => 0xFFFF00, # 255,255,0 + (lc 'YellowGreen') => 0x9ACD32, # 154,205,50 + }; +} + +1; + +__END__ diff --git a/MANIFEST b/MANIFEST new file mode 100644 index 0000000..9701f23 --- /dev/null +++ b/MANIFEST @@ -0,0 +1,13 @@ +Makefile.PL +MANIFEST +META.yml +WWW.pm +IE.pm +SVG.pm +t/00_WWW.t +t/10_SVG.t +t/11_IE.t +t/20_WWW_HTML.t +t/20_WWW_IE.t +t/20_WWW_Mozilla.t +t/20_WWW_SVG.t diff --git a/META.yml b/META.yml new file mode 100644 index 0000000..cae8c03 --- /dev/null +++ b/META.yml @@ -0,0 +1,11 @@ +# http://module-build.sourceforge.net/META-spec.html +#XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX# +name: Graphics-ColorNames-WWW +version: 0.01 +version_from: WWW.pm +installdirs: site +requires: + Graphics::ColorNames: 0.32 + +distribution_type: module +generated_by: ExtUtils::MakeMaker version 6.17 diff --git a/Makefile.PL b/Makefile.PL new file mode 100644 index 0000000..e5175b7 --- /dev/null +++ b/Makefile.PL @@ -0,0 +1,13 @@ +use ExtUtils::MakeMaker; +# See lib/ExtUtils/MakeMaker.pm for details of how to influence +# the contents of the Makefile that is written. +WriteMakefile( + 'NAME' => 'Graphics::ColorNames::WWW', + 'VERSION_FROM' => 'WWW.pm', # finds $VERSION + 'PREREQ_PM' => { + 'Graphics::ColorNames' => 0.32, + }, + ($] >= 5.005 ? ## Add these new keywords supported since 5.005 + (ABSTRACT_FROM => 'WWW.pm', # retrieve abstract from module + AUTHOR => 'Claus Färber <perl@faerber.muc.de>') : ()), +); diff --git a/SVG.pm b/SVG.pm new file mode 100644 index 0000000..a9fb29e --- /dev/null +++ b/SVG.pm @@ -0,0 +1,208 @@ +package Graphics::ColorNames::SVG; + +=head1 NAME + +Graphics::ColorNames::SVG - SVG color names and equivalent RGB values + +=head1 SYNOPSIS + + require Graphics::ColorNames::SVG; + + $NameTable = Graphics::ColorNames::SVG->NamesRgbTable(); + $RgbBlack = $NameTable->{black}; + +=head1 DESCRIPTION + +This module defines color names and their associated RGB values from the +SVG 1.2 Specification. + +=head2 Note + +Reportedly "fuchsia" was misspelled "fuscia" in an unidentified SVG +specification. It also appears to be a common misspelling, so both names are +recognized. + +=head1 SEE ALSO + +C<Graphics::ColorNames>, SVG 1.2 Specificiation <http://www.w3.org/SVG/> + +=head1 AUTHOR + +Claus Färber <cfaerber@cpan.org> + +=head1 LICENSE + +Copyright © 2005 Claus Färber + +Based on C<Graphics::ColorNames::HTML> Copyright © 2001-2004 Robert Rothenberg. + +All rights reserved. This program is free software; you can redistribute it +and/or modify it under the same terms as Perl itself. + +=cut + +require 5.006; + +use strict; +use warnings; + +our $VERSION = '1.00'; + +sub NamesRgbTable() { + sub rgb { ($_[0] << 16) + ($_[1] << 8) + ($_[2]) } + use integer; + return { + 'aliceblue' => rgb(240, 248, 255), + 'antiquewhite' => rgb(250, 235, 215), + 'aqua' => rgb( 0, 255, 255), + 'aquamarine' => rgb(127, 255, 212), + 'azure' => rgb(240, 255, 255), + 'beige' => rgb(245, 245, 220), + 'bisque' => rgb(255, 228, 196), + 'black' => rgb( 0, 0, 0), + 'blanchedalmond' => rgb(255, 235, 205), + 'blue' => rgb( 0, 0, 255), + 'blueviolet' => rgb(138, 43, 226), + 'brown' => rgb(165, 42, 42), + 'burlywood' => rgb(222, 184, 135), + 'cadetblue' => rgb( 95, 158, 160), + 'chartreuse' => rgb(127, 255, 0), + 'chocolate' => rgb(210, 105, 30), + 'coral' => rgb(255, 127, 80), + 'cornflowerblue' => rgb(100, 149, 237), + 'cornsilk' => rgb(255, 248, 220), + 'crimson' => rgb(220, 20, 60), + 'cyan' => rgb( 0, 255, 255), + 'darkblue' => rgb( 0, 0, 139), + 'darkcyan' => rgb( 0, 139, 139), + 'darkgoldenrod' => rgb(184, 134, 11), + 'darkgray' => rgb(169, 169, 169), + 'darkgreen' => rgb( 0, 100, 0), + 'darkgrey' => rgb(169, 169, 169), + 'darkkhaki' => rgb(189, 183, 107), + 'darkmagenta' => rgb(139, 0, 139), + 'darkolivegreen' => rgb( 85, 107, 47), + 'darkorange' => rgb(255, 140, 0), + 'darkorchid' => rgb(153, 50, 204), + 'darkred' => rgb(139, 0, 0), + 'darksalmon' => rgb(233, 150, 122), + 'darkseagreen' => rgb(143, 188, 143), + 'darkslateblue' => rgb( 72, 61, 139), + 'darkslategray' => rgb( 47, 79, 79), + 'darkslategrey' => rgb( 47, 79, 79), + 'darkturquoise' => rgb( 0, 206, 209), + 'darkviolet' => rgb(148, 0, 211), + 'deeppink' => rgb(255, 20, 147), + 'deepskyblue' => rgb( 0, 191, 255), + 'dimgray' => rgb(105, 105, 105), + 'dimgrey' => rgb(105, 105, 105), + 'dodgerblue' => rgb( 30, 144, 255), + 'firebrick' => rgb(178, 34, 34), + 'floralwhite' => rgb(255, 250, 240), + 'forestgreen' => rgb( 34, 139, 34), + 'fuchsia' => 0xff00ff, # "fuscia" is incorrect but common + 'fuscia' => 0xff00ff, # mis-spelling... + 'gainsboro' => rgb(220, 220, 220), + 'ghostwhite' => rgb(248, 248, 255), + 'gold' => rgb(255, 215, 0), + 'goldenrod' => rgb(218, 165, 32), + 'gray' => rgb(128, 128, 128), + 'grey' => rgb(128, 128, 128), + 'green' => rgb( 0, 128, 0), + 'greenyellow' => rgb(173, 255, 47), + 'honeydew' => rgb(240, 255, 240), + 'hotpink' => rgb(255, 105, 180), + 'indianred' => rgb(205, 92, 92), + 'indigo' => rgb( 75, 0, 130), + 'ivory' => rgb(255, 255, 240), + 'khaki' => rgb(240, 230, 140), + 'lavender' => rgb(230, 230, 250), + 'lavenderblush' => rgb(255, 240, 245), + 'lawngreen' => rgb(124, 252, 0), + 'lemonchiffon' => rgb(255, 250, 205), + 'lightblue' => rgb(173, 216, 230), + 'lightcoral' => rgb(240, 128, 128), + 'lightcyan' => rgb(224, 255, 255), + 'lightgoldenrodyellow' => rgb(250, 250, 210), + 'lightgray' => rgb(211, 211, 211), + 'lightgreen' => rgb(144, 238, 144), + 'lightgrey' => rgb(211, 211, 211), + 'lightpink' => rgb(255, 182, 193), + 'lightsalmon' => rgb(255, 160, 122), + 'lightseagreen' => rgb( 32, 178, 170), + 'lightskyblue' => rgb(135, 206, 250), + 'lightslategray' => rgb(119, 136, 153), + 'lightslategrey' => rgb(119, 136, 153), + 'lightsteelblue' => rgb(176, 196, 222), + 'lightyellow' => rgb(255, 255, 224), + 'lime' => rgb( 0, 255, 0), + 'limegreen' => rgb( 50, 205, 50), + 'linen' => rgb(250, 240, 230), + 'magenta' => rgb(255, 0, 255), + 'maroon' => rgb(128, 0, 0), + 'mediumaquamarine' => rgb(102, 205, 170), + 'mediumblue' => rgb( 0, 0, 205), + 'mediumorchid' => rgb(186, 85, 211), + 'mediumpurple' => rgb(147, 112, 219), + 'mediumseagreen' => rgb( 60, 179, 113), + 'mediumslateblue' => rgb(123, 104, 238), + 'mediumspringgreen' => rgb( 0, 250, 154), + 'mediumturquoise' => rgb( 72, 209, 204), + 'mediumvioletred' => rgb(199, 21, 133), + 'midnightblue' => rgb( 25, 25, 112), + 'mintcream' => rgb(245, 255, 250), + 'mistyrose' => rgb(255, 228, 225), + 'moccasin' => rgb(255, 228, 181), + 'navajowhite' => rgb(255, 222, 173), + 'navy' => rgb( 0, 0, 128), + 'oldlace' => rgb(253, 245, 230), + 'olive' => rgb(128, 128, 0), + 'olivedrab' => rgb(107, 142, 35), + 'orange' => rgb(255, 165, 0), + 'orangered' => rgb(255, 69, 0), + 'orchid' => rgb(218, 112, 214), + 'palegoldenrod' => rgb(238, 232, 170), + 'palegreen' => rgb(152, 251, 152), + 'paleturquoise' => rgb(175, 238, 238), + 'palevioletred' => rgb(219, 112, 147), + 'papayawhip' => rgb(255, 239, 213), + 'peachpuff' => rgb(255, 218, 185), + 'peru' => rgb(205, 133, 63), + 'pink' => rgb(255, 192, 203), + 'plum' => rgb(221, 160, 221), + 'powderblue' => rgb(176, 224, 230), + 'purple' => rgb(128, 0, 128), + 'red' => rgb(255, 0, 0), + 'rosybrown' => rgb(188, 143, 143), + 'royalblue' => rgb( 65, 105, 225), + 'saddlebrown' => rgb(139, 69, 19), + 'salmon' => rgb(250, 128, 114), + 'sandybrown' => rgb(244, 164, 96), + 'seagreen' => rgb( 46, 139, 87), + 'seashell' => rgb(255, 245, 238), + 'sienna' => rgb(160, 82, 45), + 'silver' => rgb(192, 192, 192), + 'skyblue' => rgb(135, 206, 235), + 'slateblue' => rgb(106, 90, 205), + 'slategray' => rgb(112, 128, 144), + 'slategrey' => rgb(112, 128, 144), + 'snow' => rgb(255, 250, 250), + 'springgreen' => rgb( 0, 255, 127), + 'steelblue' => rgb( 70, 130, 180), + 'tan' => rgb(210, 180, 140), + 'teal' => rgb( 0, 128, 128), + 'thistle' => rgb(216, 191, 216), + 'tomato' => rgb(255, 99, 71), + 'turquoise' => rgb( 64, 224, 208), + 'violet' => rgb(238, 130, 238), + 'wheat' => rgb(245, 222, 179), + 'white' => rgb(255, 255, 255), + 'whitesmoke' => rgb(245, 245, 245), + 'yellow' => rgb(255, 255, 0), + 'yellowgreen' => rgb(154, 205, 50), + }; +} + +1; + +__END__ diff --git a/WWW.pm b/WWW.pm new file mode 100644 index 0000000..80701a9 --- /dev/null +++ b/WWW.pm @@ -0,0 +1,68 @@ +package Graphics::ColorNames::WWW; + +=head1 NAME + +Graphics::ColorNames::WWW - WWW color names and equivalent RGB values + +=head1 SYNOPSIS + + require Graphics::ColorNames::WWW; + + $NameTable = Graphics::ColorNames::WWW->NamesRgbTable(); + $RgbBlack = $NameTable->{black}; + +=head1 DESCRIPTION + +This modules defines color names and their associated RGB values from various +WWW specifications and implementations. + +=cut + +# Note: Mozilla is a subset of SVG +# Note: HTML is a subset of HTML + +my @modules = ( + 'SVG', +# 'HTML', -- subset of SVG +# 'Mozilla', -- subset of SVG +# 'IE', -- subset of SVG +); + +=head1 SEE ALSO + +C<Graphics::ColorNames> + +=head1 AUTHOR + +Claus Färber <cfaerber@cpan.org> + +=head1 LICENSE + +Copyright © 2005 Claus Färber + +Based on C<Graphics::ColorNames::HTML> Copyright © 2001-2004 Robert Rothenberg. + +All rights reserved. This program is free software; you can redistribute it +and/or modify it under the same terms as Perl itself. + +=cut + +require 5.006; + +use strict; +use warnings; + +our $VERSION = '0.01'; + +sub NamesRgbTable() { + my %map = (); + foreach (@modules) { + eval "use Graphics::ColorNames::$_;"; die $@ if $@; + %map = ((%map),%{eval "Graphics::ColorNames::$_->NamesRgbTable"}); + } + return \%map; +} + +1; + +__END__ diff --git a/t/00_WWW.t b/t/00_WWW.t new file mode 100644 index 0000000..2fe8a22 --- /dev/null +++ b/t/00_WWW.t @@ -0,0 +1,18 @@ +use Test; + +BEGIN { + plan tests => 5, todo => [ ] +} + +use strict; +use Carp; + +use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); +ok(1); + +tie my %colors, 'Graphics::ColorNames', 'WWW'; +ok(1); + +ok(exists($colors{"fuchsia"})); +ok(exists($colors{"fuscia"})); +ok($colors{"fuscia"} eq $colors{"fuchsia"}); diff --git a/t/10_SVG.t b/t/10_SVG.t new file mode 100644 index 0000000..4bc8d2d --- /dev/null +++ b/t/10_SVG.t @@ -0,0 +1,33 @@ +use Test; + + +BEGIN { + my $colors = 148; + plan tests => 9 + $colors, todo => [ ] +} + +use strict; +use Carp; + +use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); +ok(1); + +tie my %colors, 'Graphics::ColorNames', 'SVG'; +ok(1); + +ok(keys %colors, 148); + +my $count = 0; +foreach my $name (keys %colors) + { + my @RGB = hex2tuple( $colors{$name} ); + ok(tuple2hex(@RGB), $colors{$name} ); + } + +ok(exists($colors{"fuchsia"})); +ok(exists($colors{"fuscia"})); +ok($colors{"fuscia"} eq $colors{"fuchsia"}); + +ok(uc $colors{'white'}, 'FFFFFF'); +ok(uc $colors{'blue'}, '0000FF'); +ok(uc $colors{'cyan'}, '00FFFF'); diff --git a/t/11_IE.t b/t/11_IE.t new file mode 100644 index 0000000..e4e893a --- /dev/null +++ b/t/11_IE.t @@ -0,0 +1,29 @@ +use Test; + + +BEGIN { + my $colors = 140; + plan tests => 6 + $colors, todo => [ ] +} + +use strict; +use Carp; + +use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); +ok(1); + +tie my %colors, 'Graphics::ColorNames', 'IE'; +ok(1); + +ok(keys %colors, 140); + +my $count = 0; +foreach my $name (keys %colors) + { + my @RGB = hex2tuple( $colors{$name} ); + ok(tuple2hex(@RGB), $colors{$name} ); + } + +ok(uc $colors{'white'}, 'FFFFFF'); +ok(uc $colors{'blue'}, '0000FF'); +ok(uc $colors{'cyan'}, '00FFFF'); diff --git a/t/20_WWW_HTML.t b/t/20_WWW_HTML.t new file mode 100644 index 0000000..f00eb5b --- /dev/null +++ b/t/20_WWW_HTML.t @@ -0,0 +1,21 @@ +use Test; + + +BEGIN { + my $colors = 17; + plan tests => $colors, todo => [ ] +} + +use strict; +use Carp; + +use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); +tie my %colors, 'Graphics::ColorNames', 'HTML'; +tie my %col_www, 'Graphics::ColorNames', 'WWW'; + +my $count = 0; +foreach my $name (keys %colors) + { + my @RGB = hex2tuple( $colors{$name} ); + ok($name.'-'.tuple2hex(@RGB), $name.'-'.$col_www{$name} ); + } diff --git a/t/20_WWW_IE.t b/t/20_WWW_IE.t new file mode 100644 index 0000000..05643c4 --- /dev/null +++ b/t/20_WWW_IE.t @@ -0,0 +1,21 @@ +use Test; + + +BEGIN { + my $colors = 193-53; + plan tests => $colors, todo => [ ] +} + +use strict; +use Carp; + +use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); +tie my %col_www, 'Graphics::ColorNames', 'WWW'; +tie my %colors, 'Graphics::ColorNames', 'IE'; + +my $count = 0; +foreach my $name (keys %colors) + { + my @RGB = hex2tuple( $colors{$name} ); + ok(tuple2hex(@RGB), $col_www{$name} ); + } diff --git a/t/20_WWW_Mozilla.t b/t/20_WWW_Mozilla.t new file mode 100644 index 0000000..6aea990 --- /dev/null +++ b/t/20_WWW_Mozilla.t @@ -0,0 +1,19 @@ +use Test::More tests => 146; + +use strict; +use Carp; + +SKIP: { + eval { require Graphics::ColorNames::Mozilla; }; + skip ("Graphics::ColorNames::Mozilla not installed", 146) if $@; + + use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); + tie my %col_www, 'Graphics::ColorNames', 'WWW'; + tie my %colors, 'Graphics::ColorNames', 'Mozilla'; + + foreach my $name (keys %colors) + { + my @RGB = hex2tuple( $colors{$name} ); + is(tuple2hex(@RGB), $col_www{$name} ); + } +} diff --git a/t/20_WWW_SVG.t b/t/20_WWW_SVG.t new file mode 100644 index 0000000..b74a509 --- /dev/null +++ b/t/20_WWW_SVG.t @@ -0,0 +1,21 @@ +use Test; + + +BEGIN { + my $colors = 148; + plan tests => $colors, todo => [ ] +} + +use strict; +use Carp; + +use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); +tie my %col_www, 'Graphics::ColorNames', 'WWW'; +tie my %colors, 'Graphics::ColorNames', 'SVG'; + +my $count = 0; +foreach my $name (keys %colors) + { + my @RGB = hex2tuple( $colors{$name} ); + ok(tuple2hex(@RGB), $col_www{$name} ); + }
cfaerber/Graphics-ColorNames-WWW
f76f32b5051541572674acaea5e31f2d117f1624
Color-Calc-1.00
diff --git a/Calc.pm b/Calc.pm index 5134a2e..79c2593 100644 --- a/Calc.pm +++ b/Calc.pm @@ -1,615 +1,620 @@ -# $Id: Calc.pm,v 1.10 2005/04/09 20:49:58 cfaerber Exp $ +# $Id: Calc.pm,v 1.13 2005/09/24 17:36:15 cfaerber Exp $ # package Color::Calc; use strict; -use Carp; -use POSIX; +use Carp; +use Exporter; use Params::Validate qw(:all); +use POSIX; use Graphics::ColorNames qw( hex2tuple tuple2hex ); use Graphics::ColorNames::HTML; -our $VERSION = '0.29_0003'; +our $VERSION = '1.00'; $VERSION = eval $VERSION; our $MODE = (); my %__HTMLColors = (); our @__subs = qw( blend blend_bw bw contrast contrast_bw dark get grey gray invert light mix ); my %__formats = ( 'tuple' => sub { return __normtuple_out(@_); }, 'hex' => sub { return tuple2hex((@_)); }, 'html' => sub { my $col = lc(tuple2hex((@_))); return $__HTMLColors{$col} || '#'.$col; }, 'object' => sub { eval { require Graphics::ColorObject; }; return Graphics::ColorObject->new_RGB255( [(@_)] ); }, -# 'pdf' => sub { eval { require PDF::API2::Color; }; return PDF::API2::Color->newRGB( map { $_ / 255 } ((@_))); }, + 'obj' => sub { eval { require Color::Object; }; return Color::Object->newRGB(map { 255*$_; } @_); }, + 'pdf' => sub { return sprint('#%%04x%%04x%%04x',(map { 257*$_ } @_)) }, ); + my @__formats = keys %__formats; my $__formats_re = join('|', @__formats,'__MODEvar'); { my $table = Graphics::ColorNames::HTML::NamesRgbTable(); %__HTMLColors = map { ( sprintf('%06x', $$table{$_}) => $_ ) } grep { $_ ne 'fuscia' } keys %$table; }; our @EXPORT = ('color', map({"color_$_"} @__formats, map({my $s=$_; (map{$s.'_'.$_} @__formats)} @__subs), @__subs)); our @ISA = ('Exporter'); my %new_param = ( 'ColorScheme' => { type => SCALAR, optional => 1 }, 'OutputFormat' => { type => SCALAR, untaint => 1, regexp => qr($__formats_re), optional => 1 }, ); sub new { my $pkg = shift; validate(@_, \%new_param); my $self = {@_}; bless($self, $pkg); if(!ref($self->{'ColorScheme'})) { my %ColorNames; tie %ColorNames, 'Graphics::ColorNames', ($self->{'ColorScheme'} || 'X'); $self->{'ColorScheme'} = \%ColorNames; } $self->set_output_format($self->{'OutputFormat'} || 'tuple'); return $self; } my $__default_object = undef; sub __get_default { $__default_object = __PACKAGE__->new('OutputFormat' => '__MODEvar') unless $__default_object; return $__default_object; } my $__tuple_object = undef; sub __get_tuple { $__tuple_object = __PACKAGE__->new('OutputFormat' => 'tuple') unless $__tuple_object; return $__tuple_object; } my %import_param = ( %new_param, 'Prefix' => { type => SCALAR, optional => 1, regexp => qr/^[[:alpha:]\d]\w*$/ }, '__Prefix' => { type => SCALAR, optional => 1, regexp => qr/^[[:alpha:]\d]\w*$/ }, '__Suffix' => { type => SCALAR, optional => 1, regexp => qr/^\w+$/ }, ); my %import_param_names = map { ($_=>1) } keys %import_param; sub import { my $pkg = shift; if(!@_ || !exists $import_param_names{$_[0]}) { local $Exporter::ExportLevel; $Exporter::ExportLevel++; return Exporter::import($pkg, @_); } return __import(scalar caller(0),@_) ? 1 : 0; } sub __import { my $pkg = shift; validate(@_, \%import_param); my %param = @_; my $std_prefix = (exists $param{'Prefix'}) ? $param{'Prefix'} : 'color'; delete $param{'Prefix'}; my $prefix = (exists $param{'__Prefix'}) ? $param{'__Prefix'} : $std_prefix ? $std_prefix.'_' : ''; delete $param{'__Prefix'}; my $suffix = (exists $param{'__Suffix'}) ? $param{'__Suffix'} : ''; delete $param{'__Suffix'}; my $obj = new(__PACKAGE__, %param); { no strict 'refs'; { $prefix = $pkg.'::'.$prefix; foreach my $sub (@__subs) { my $name = $prefix.$sub.$suffix; *$name = sub { $obj->$sub(@_); }; }; }; if($std_prefix) { my $name = $pkg.'::'.$std_prefix.$suffix; *$name = sub { $obj->get(@_); }; } } return 1; } sub __normtuple_in { return map { ($_ < 0) ? 0 : (($_ > 255) ? 255 : int($_+.5)) } @_; } sub __normtuple_out { return map { (length $_) == 3 ? '0'.$_ : $_ } __normtuple_in(@_) } sub __normtuple { return __normtuple_out(__normtuple_in(@_)); } sub __is_col_val { return undef unless defined $_[0]; return undef if $_[0] eq ''; my ($n,$u) = POSIX::strtod($_[0]); return undef if $u != 0; return ($n <= 255) && ($n>= 0); } # Note: Color::Object was supported in versions before 0.2. This # is kept for compatibility, but no longer documented. # # Note: versions before 0.2 allowed calling some functions (those # with one parameter) with a list instead of an arrayref. This is # kept for compatibility, but no longer documented. sub __get { my ($self,$p,$q) = @_; if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 0 ) { $$p[0] = $$p[0]->[0]; } if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 2 ) { return __normtuple_in(@{shift @$p}); } - elsif( UNIVERSAL::isa($$p[0],'Color::Object') || - UNIVERSAL::isa($$p[0],'PDF::API2::Color')) { - return (map { 255 * $_; } (shift(@{$p})->asRGB)); + elsif( my $f255 = UNIVERSAL::can($$p[0],'asRGB255') + || UNIVERSAL::can($$p[0],'as_RGB255') ) { + return ($f255->(shift(@{$p}))); } - elsif( UNIVERSAL::isa($$p[0],'Graphics::ColorObject')) { - return (shift(@{$p})->as_RGB255()); + elsif( my $f1 = UNIVERSAL::can($$p[0],'asRGB') + || UNIVERSAL::can($$p[0],'as_RGB') ) { + return (map { 255 * $_; } $f1->(shift(@{$p}))); } elsif( $#$p >= (2 + ($q||0)) && __is_col_val($$p[0]) && __is_col_val($$p[1]) && __is_col_val($$p[2])) { return (splice @$p, 0, 3); } - elsif( $$p[0] =~ m/^#?([0-9A-F])([0-9A-F])([0-9A-F])$/i ) { + elsif( $$p[0] =~ m/^#?(([0-9A-F][0-9A-F][0-9A-F])+)$/i ) { shift @$p; - return (map { hex($_) * 17 } ($1,$2,$3)); - } - elsif( $$p[0] =~ m/^#?([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])$/i ) { - shift @$p; - return (map { hex($_) } ($1,$2,$3)); + my $hh = $1; my $hl = (length $hh)/3; + return map { hex($_) * 255.0 / hex('F' x $hl) } + (substr($hh,0,$hl), substr($hh,$hl,$hl), substr($hh,2*$hl)); } else { my $col = $self->{'ColorScheme'}->{$$p[0]}; if($col) { shift @$p; return hex2tuple($col); } else { carp("Invalid color name '$$p[0]'"); return undef; } } } sub set_output_format { validate_pos(@_, { isa => __PACKAGE__ }, { type => SCALAR, regexp => qr($__formats_re) }); my $self = shift; my $old = $self->{'OutputFormat'}; $self->{'OutputFormat'} = shift; $self->{'__put'} = $self->{'OutputFormat'} eq '__MODEvar' ? sub{ return $__formats{$MODE || 'tuple'}->(@_); } : $__formats{$self->{'OutputFormat'}}; return $old; } sub __put { my $self = shift; return $self->{'__put'}->(__normtuple_in(@_)); } sub __get_self { if(UNIVERSAL::isa($_[0]->[0], __PACKAGE__)) { return shift @{$_[0]}; } else { return __get_default; } } sub get { my $self = __get_self(\@_); return $self->__put($self->__get(\@_)); } sub invert { my $self = __get_self(\@_); return $self->__put(map { 255 - $_ } $self->__get(\@_)); } sub bw { my $self = __get_self(\@_); my @c = $self->__get(\@_); my $g = $c[0]*.3 + $c[1]*.59 + $c[2]*.11; return $self->__put(__normtuple($g,$g,$g)); } *grey = \&bw; *gray = \&bw; sub mix { my $self = __get_self(\@_); my @c1 = ($self->__get(\@_,1)); my @c2 = ($self->__get(\@_)); my $alpha = shift(@_); $alpha = 0.5 unless defined $alpha; return $self->__put(__normtuple( ($c1[0] + ($c2[0]-$c1[0])*$alpha), ($c1[1] + ($c2[1]-$c1[1])*$alpha), ($c1[2] + ($c2[2]-$c1[2])*$alpha) )); } sub light { my $self = __get_self(\@_); return $self->__put(__get_tuple->mix([$self->__get(\@_)],[255,255,255],shift)); } sub dark { my $self = __get_self(\@_); return $self->__put(__get_tuple->mix([$self->__get(\@_)],[0,0,0],shift)); } sub contrast { my $self = __get_self(\@_); my @rgb = $self->__get(\@_); my $cut = (shift || .5) * 255; return $self->__put(map { $_ >= $cut ? 0 : '0255' } @rgb); } sub contrast_bw { my $self = __get_self(\@_); my @rgb = $self->__get(\@_); return $self->__put(__get_tuple->contrast([__get_tuple->bw(@rgb)], shift)); } sub blend { my $self = __get_self(\@_); my @c1 = $self->__get(\@_); return $self->mix(\@c1,[__get_tuple->contrast(\@c1)],shift); } sub blend_bw { my $self = __get_self(\@_); my @c = $self->__get(\@_); return $self->mix(\@c,[__get_tuple->contrast_bw(\@c)],shift); } foreach my $format (@__formats) { __import(__PACKAGE__, 'Prefix' => 'color', '__Suffix' => "_$format", 'OutputFormat' => $format); __import(__PACKAGE__, 'Prefix' => '', '__Suffix' => "_$format", 'OutputFormat' => $format); } __import(__PACKAGE__, 'Prefix' => 'color', 'OutputFormat' => '__MODEvar'); =head1 NAME Color::Calc - Simple calculations with RGB colors. =head1 SYNOPSIS use Color::Calc (); my $background = 'green'; print 'background: ',Color::Calc::color_html($background),';'; print 'border-top: solid 1px ',Color::Calc::light_html($background),';'; print 'border-bottom: solid 1px ',Color::Calc::dark_html($background),';'; print 'color: ',contrast_bw_html($background),';'; =head1 DESCRIPTION The C<Color::Calc> module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. =head2 Color Formats =head3 Input All of the methods accept colors as parameters in the following formats: =over =item * An arrayref pointing to an array with three elements in the range C<0>..C<255> corresponding to the red, green, and blue component. + =item * -A string containing a hexadecimal RGB value in the form -C<#I<RRGGBB>>/C<#I<RGB>> or C<I<RGB>>/C<I<RRGGBB>>. +A string containing a hexadecimal RGB value like +C<#I<RGB>>/C<#I<RRGGBB>>/C<#I<RRRGGGBBB>>/... or +C<I<RGB>>/C<I<RRGGBB>>/C<I<RRRGGGBBB>>/... =item * A color name accepted by C<Graphics::ColorNames>. -=item * - -A C<PDF::API2::Color> reference. +A C<Graphics::ColorObject> reference. =item * -A C<Graphics::ColorObject> reference. +A list of three values in the range C<0>..C<255> corresponding to the red, +green, and blue component where the first value does not have 3 or a multiple +of 3 digits (e.g. C<('0128',128,128)>). =item * -A return value of any (public) C<Color::Calc> method even if the -C<tuple> output format is selected. +A return value of any (public) C<Color::Calc> method even if the C<tuple> +output format is selected. =back =head3 Output C<Color::Calc> can return colors in the following modes: =over =item tuple Returns a list of three values in the range 0..255. =item hex Returns a hexadecimal RGB value in the format RRGGBB. =item html Returns a value compatible with W3C's HTML and CSS specifications, i.e. I<#RRGGBB> or one of the sixteen color names. -=item pdf - -Returns a C<PDF::API2::Color> reference. The module -C<PDF::API2::Color> must be installed. - =item object Returns a C<Graphics::ColorObject> reference. The module C<Graphics::ColorObject> must be installed. +=item pdf + +Returns a value which can be passed to C<PDF::API2::Content>'s fillcolor and +strokecolor methods. + =item __MODEvar (DEPRECATED) Uses the value of C<$Color::Calc::MODE> to select the output format. You should use C<local> when setting this variable. =back =head2 Object-Orientated interface use Color::Calc(); my $cc = new Color::Calc( 'ColorScheme' => 'X', OutputFormat => 'HTML' ); print $cc->invert( 'white' ); =over =item new $cc = new Color::Calc( 'ColorScheme' => $name, 'OutputFormat' => $format ); Creates a new C<Color::Calc> object which can be used to access the color calculation methods. =over =item ColorScheme One of the color schemes accepted by C<Graphics::ColorNames>. Used to translate color names on input. See the documentation of C<Graphics::ColorNames> for possible values. Default: C<X> (please note that this is incompatible with HTML color names). =item OutputFormat Sets the output format of the object's methods. See above for possible values. Default: C<__MODEvar> =back =item $cc->get($color) Returns the color as-is (but in the selected output format). This function can be used for color format conversion/normalisation. =item $cc->invert($color) Returns the inverse of $color. =item $cc->bw($color) =item $cc->grey($color) Converts $color to greyscale. =item $cc->mix($color1, $color2 [, $alpha]) Returns a color that is the mixture of $color1 and $color2. The optional $alpha parameter can be a value between 0.0 (use $color1 only) and 1.0 (use $color2 only), the default is 0.5. =item $cc->color_light($color [, $alpha]) Returns a lighter version of $color, i.e. returns $cc->mix($color,[255,255,255],$alpha); The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use 'white' only), the default is 0.5. =item $cc->dark($color [, $alpha]) Returns a darker version of $color, i.e. returns $cc->mix($color,[0,0,0],$alpha); The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use 'black' only), the default is 0.5. =item $cc->contrast($color [, $cut]) Returns a color that has the highest possible contrast to the input color. This is done by setting the red, green, and blue values to 0 if the corresponding value in the input is above C<($cut * 255)> and to 255 otherwise. The default for C<$cut> is .5, representing a cutoff between 127 and 128. =item $cc->contrast_bw($color [, $cut]) Returns black or white, whichever has the higher contrast to $color. This is done by setting returning black if the grey value of $color is above C<($cut * 255)> and white otherwise. The default for C<$cut> is .5, representing a cutoff between 127 and 128. =item $cc->blend($color [, $alpha]) Returns a color that blends into the background, i.e. it returns $cc->mix($color,$cc->contrast($color),$alpha). The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use C<contrast($color)> only), the default is 0.5. The idea is that C<$color> is the foreground color, so C<contrast($color)> is similar to the background color. Mixing them returns a color somewhere between them. You might want to use mix($color, $background, $alpha) instead if you know the real background color. =item $cc->blend_bw($color [, $alpha]) Returns a mix of $color and black or white, whichever has the higher contrast to $color. The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use black/white only), the default is 0.5. =back =head2 Procedural Interface With Importing You can also choose to import customised funtions into your namespace: use Color::Calc( 'ColorScheme' => 'X', 'OutputFormat' => 'HTML', 'Prefix' => 'cc' ); print cc_invert( 'white' ); # prints 'black' On import, you can specify the following parameters: =over =item ColorScheme See above. =item OutputFormat See above. =item Prefix Adds the prefix and an underscore to the front of the method names. You can call the methods as I<prefix>_I<method_name>. You can also call I<prefix> instead of I<prefix>C<_get>. Default: C<color> =back Please note that specifying an empty list of parameters means "don't import anything". Omit the list to import the default functions. You can also C<use> the following modules to import the function with pre-defined parameters. =over =item C<use Color::Calc::WWW> Same as C<use Color::Calc( ColorScheme =&gt; 'WWW', OutputFormat => 'html' )> =item C<use Color::Calc::html> (DEPRECATED) Same as C<use Color::Calc( OutputFormat =&gt; 'html')> Please note that this only selects HTML as the C<OutputFormat> but not as the C<ColorScheme> (which defaults to 'X'), which is probably not what you expect. Use C<Color::Calc::WWW> instead. =item C<use Color::Calc::hex> Same as C<use Color::Calc( OutputFormat =&gt; 'hex')> =item C<use Color::Calc::object> Same as C<use Color::Calc( OutputFormat =&gt; 'object')> =item C<use Color::Calc::pdf> Same as C<use Color::Calc( OutputFormat =&gt; 'pdf')> =item C<use Color::Calc::tuple> Same as C<use Color::Calc( OutputFormat =&gt; 'tuple')> =back =head2 Procedural Interface Without Importing (DEPRECATED) You can also access the methods as class methods of the various packages with and without the C<color> prefix: use Color::Calc::WWW(); print Color::Calc::WWW::color('FFF'); # prints 'white' print Color::Calc::WWW::color_invert('FFF'); # prints 'black' print Color::Calc::html::invert('FFF'); # prints 'black' For the main module C<Color::Calc>, you can also add a suffix C<_I<output_format>> to select the output format: use Color::Calc(); print Color::Calc::color_html('FFF'); # prints 'white' print Color::Calc::color_invert_html('FFF'); # prints 'black' print Color::Calc::invert_hex('FFF'); # prints '000000' =head1 SEE ALSO L<Graphics::ColorNames> (required); + L<Graphics::ColorObject> (optional) =head1 AUTHOR Claus A. Färber <perl@faerber.muc.de> =head1 COPYRIGHT Copyright © 2004, 2005 Claus A. Färber All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; diff --git a/Changes b/Changes index 8f950c7..bf2b54a 100644 --- a/Changes +++ b/Changes @@ -1,36 +1,46 @@ Revision history for Perl extension Color::Calc. +0.30 Sat Sep 24 20:00:00 2005 + - new 'pdf' output format, which is accepted by PDF::API2 v.40 + - allow any number of hex digits per color in #RGB/#RRGGBB/ + #RRRGGGBBB/... + - better tests + - FIX: #13731 import w/ use does not work under mod_perl + +0.29_0003 Sat Apr 09 20:00:00 2005 + - fixed MANIFEST (broken distribution) + 0.29_0002 Sat Mar 26 16:20:00 2005 - Color::Calc::WWW now uses Graphics::ColorNames::WWW - Color::Calc::WWW was missing from distribution - removed 'pdf' output format as PDF::API2::Color is no longer - complete test suite 0.29_0001 Fri Mar 25 12:00:00 2005 - added object-orientated interface - added procedural interface with customisation on import - added Color::Calc::WWW - color scheme is now selectable 0.20 Mon Mar 28 00:00:00 2004 - added Color::Calc::<xxx> modules to select return type - added $Color::Calc::MODE to select return type - return value of xxx_tuple can be used as parameter - <xxx>_html returns color names instead of #RRGGBB if possible - support for Graphics::ColorObject (input/output) - support for PDF::API2::Color (input/output) - fixed import list 0.12 Thu Mar 18 00:00:00 2004 - added xxx_html - should work with perl 5.005 now 0.10 Sun May 04 00:00:00 2003 - added tests - added more functions - some documentation corrections 0.02 Sat Apr 26 00:00:00 2003 - first public release -$Id: Changes,v 1.8 2005/04/09 20:49:58 cfaerber Exp $ +$Id: Changes,v 1.10 2005/09/24 17:36:53 cfaerber Exp $ diff --git a/META.yml b/META.yml index 4b561ac..e7db5b4 100644 --- a/META.yml +++ b/META.yml @@ -1,13 +1,13 @@ # http://module-build.sourceforge.net/META-spec.html #XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX# name: Color-Calc -version: 0.29_0003 +version: 1.00 version_from: Calc.pm installdirs: site requires: Graphics::ColorNames: 0.32 Graphics::ColorNames::SVG: 0 Params::Validate: 0.75 distribution_type: module generated_by: ExtUtils::MakeMaker version 6.17 diff --git a/t/10_suffixes.t b/t/10_suffixes.t deleted file mode 100644 index 54f5f07..0000000 --- a/t/10_suffixes.t +++ /dev/null @@ -1,6 +0,0 @@ -use Test::More tests => 3; -use Color::Calc; - -is((join '-', color_tuple('red')), '0255-0-0'); -is(color_hex([255,0,0]), 'ff0000'); -is(color_html([255,0,0]), 'red'); diff --git a/t/11_import_MODEval.t b/t/11_import_MODEval.t index c947500..a5dcd20 100644 --- a/t/11_import_MODEval.t +++ b/t/11_import_MODEval.t @@ -1,73 +1,74 @@ -# $Id: 11_import_MODEval.t,v 1.2 2005/04/09 20:49:58 cfaerber Exp $ +# $Id: 11_import_MODEval.t,v 1.3 2005/09/24 17:36:28 cfaerber Exp $ # use Test::More tests => 52; use Color::Calc; local $Color::Calc::MODE = 'hex'; + is(color_get ('red'), 'ff0000'); is(color ('red'), 'ff0000'); is(color_mix ('red','blue'), '800080'); is(color_blend_bw ('red'), 'ff8080'); is(color_blend ('red'), '808080'); is(color_bw ('red'), '4d4d4d'); is(color_contrast_bw ('red'), 'ffffff'); is(color_contrast ('red'), '00ffff'); is(color_dark ('red'), '800000'); is(color_gray ('red'), '4d4d4d'); is(color_grey ('red'), '4d4d4d'); is(color_invert ('red'), '00ffff'); is(color_light ('red'), 'ff8080'); local $Color::Calc::MODE = 'html'; is(color_get ('F00'), 'red'); is(color ('F00'), 'red'); is(color_mix ('red','blue'), 'purple'); is(color_blend_bw ('red'), '#ff8080'); is(color_blend ('red'), 'gray'); is(color_bw ('red'), '#4d4d4d'); is(color_contrast_bw ('red'), 'white'); is(color_contrast ('red'), 'aqua'); is(color_dark ('red'), 'maroon'); is(color_gray ('red'), '#4d4d4d'); is(color_grey ('red'), '#4d4d4d'); is(color_invert ('red'), 'aqua'); is(color_light ('red'), '#ff8080'); local $Color::Calc::MODE = 'object'; SKIP: { -eval { require Graphics::ColorObject; }; -skip "Graphics::ColorObject not installed", 12 if $@; + eval { require Graphics::ColorObject; }; + skip "Graphics::ColorObject not installed", 13 if $@; is(lc color_get ('red')->as_RGBhex, 'ff0000'); is(lc color ('red')->as_RGBhex, 'ff0000'); is(lc color_mix ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc color_blend ('red')->as_RGBhex, '808080'); is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast ('red')->as_RGBhex, '00ffff'); is(lc color_dark ('red')->as_RGBhex, '800000'); is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert ('red')->as_RGBhex, '00ffff'); is(lc color_light ('red')->as_RGBhex, 'ff8080'); } local $Color::Calc::MODE = 'tuple'; is(join(',',color_get ('red')), '0255,0,0'); is(join(',',color ('red')), '0255,0,0'); is(join(',',color_mix ('red','blue')), '0128,0,0128'); is(join(',',color_blend_bw ('red')), '0255,0128,0128'); is(join(',',color_blend ('red')), '0128,0128,0128'); is(join(',',color_bw ('red')), '77,77,77'); is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); is(join(',',color_contrast ('red')), '0,0255,0255'); is(join(',',color_dark ('red')), '0128,0,0'); is(join(',',color_gray ('red')), '77,77,77'); is(join(',',color_grey ('red')), '77,77,77'); is(join(',',color_invert ('red')), '0,0255,0255'); is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/11_import_object.t b/t/11_import_object.t index 75ac540..a8bc492 100644 --- a/t/11_import_object.t +++ b/t/11_import_object.t @@ -1,24 +1,24 @@ -# $Id: 11_import_object.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# $Id: 11_import_object.t,v 1.3 2005/09/24 17:36:28 cfaerber Exp $ # use Test::More tests => 13; use Color::Calc( 'OutputFormat' => 'object' ); SKIP: { eval { require Graphics::ColorObject; }; -skip "Graphics::ColorObject not installed", 12 if $@; +skip "Graphics::ColorObject not installed", 13 if $@; is(lc color_get ('red')->as_RGBhex, 'ff0000'); is(lc color ('red')->as_RGBhex, 'ff0000'); is(lc color_mix ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc color_blend ('red')->as_RGBhex, '808080'); is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast ('red')->as_RGBhex, '00ffff'); is(lc color_dark ('red')->as_RGBhex, '800000'); is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert ('red')->as_RGBhex, '00ffff'); is(lc color_light ('red')->as_RGBhex, 'ff8080'); } diff --git a/t/12_param_1.t b/t/12_param_1.t deleted file mode 100644 index 1e69bf6..0000000 --- a/t/12_param_1.t +++ /dev/null @@ -1,12 +0,0 @@ -use Test::More tests => 7; -use Color::Calc; - -$Color::Calc::MODE = 'hex'; - -is(color('red'), 'ff0000'); -is(color([255,0,0]), 'ff0000'); -is(color('F00'), 'ff0000'); -is(color('255','0','0'),'ff0000'); -is(color('FF0000'), 'ff0000'); -is(color('#F00'), 'ff0000'); -is(color('#FF0000'), 'ff0000'); diff --git a/t/13_param_2.t b/t/13_param_2.t deleted file mode 100644 index 693b049..0000000 --- a/t/13_param_2.t +++ /dev/null @@ -1,12 +0,0 @@ -use Test::More tests => 4; -use Color::Calc; - -$Color::Calc::MODE = 'hex'; - -# R G B ALPHA -is(color_dark('255','000','000', ),'800000'); -is(color_dark('255','000','000', .4 ),'990000'); - -# RGB ALPHA -is(color_dark('FF0', ),'808000'); -is(color_dark('FF0', .4 ),'999900'); diff --git a/t/14_param_3.t b/t/14_param_3.t deleted file mode 100644 index 6fa8359..0000000 --- a/t/14_param_3.t +++ /dev/null @@ -1,14 +0,0 @@ -use Test::More tests => 5; -use Color::Calc; - -$Color::Calc::MODE = 'hex'; - -# R G B RGB ALPHA -is(color_mix('255','000','000','000' ),'800000'); -is(color_mix('255','000','000','000', .4 ),'990000'); -# RGB R G B ALPHA -is(color_mix('FF0','000','000','000', ),'808000'); -is(color_mix('FF0','000','000','000', .4 ),'999900'); -# RGB RGB ALPHA -is(color_mix('255','000','000' ),'225555'); - diff --git a/t/18_DEPRECATED_import_MODEval.t b/t/18_DEPRECATED_import_MODEval.t index db2e626..1159493 100644 --- a/t/18_DEPRECATED_import_MODEval.t +++ b/t/18_DEPRECATED_import_MODEval.t @@ -1,73 +1,73 @@ -# $Id: 18_DEPRECATED_import_MODEval.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# $Id: 18_DEPRECATED_import_MODEval.t,v 1.3 2005/09/24 17:36:28 cfaerber Exp $ # use Test::More tests => 52; use Color::Calc; local $Color::Calc::MODE = 'hex'; is(color_get ('red'), 'ff0000'); is(color ('red'), 'ff0000'); is(color_mix ('red','blue'), '800080'); is(color_blend_bw ('red'), 'ff8080'); is(color_blend ('red'), '808080'); is(color_bw ('red'), '4d4d4d'); is(color_contrast_bw ('red'), 'ffffff'); is(color_contrast ('red'), '00ffff'); is(color_dark ('red'), '800000'); is(color_gray ('red'), '4d4d4d'); is(color_grey ('red'), '4d4d4d'); is(color_invert ('red'), '00ffff'); is(color_light ('red'), 'ff8080'); local $Color::Calc::MODE = 'html'; is(color_get ('F00'), 'red'); is(color ('F00'), 'red'); is(color_mix ('red','blue'), 'purple'); is(color_blend_bw ('red'), '#ff8080'); is(color_blend ('red'), 'gray'); is(color_bw ('red'), '#4d4d4d'); is(color_contrast_bw ('red'), 'white'); is(color_contrast ('red'), 'aqua'); is(color_dark ('red'), 'maroon'); is(color_gray ('red'), '#4d4d4d'); is(color_grey ('red'), '#4d4d4d'); is(color_invert ('red'), 'aqua'); is(color_light ('red'), '#ff8080'); local $Color::Calc::MODE = 'object'; SKIP: { eval { require Graphics::ColorObject; }; -skip "Graphics::ColorObject not installed", 12 if $@; +skip "Graphics::ColorObject not installed", 13 if $@; is(lc color_get ('red')->as_RGBhex, 'ff0000'); is(lc color ('red')->as_RGBhex, 'ff0000'); is(lc color_mix ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc color_blend ('red')->as_RGBhex, '808080'); is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast ('red')->as_RGBhex, '00ffff'); is(lc color_dark ('red')->as_RGBhex, '800000'); is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert ('red')->as_RGBhex, '00ffff'); is(lc color_light ('red')->as_RGBhex, 'ff8080'); } local $Color::Calc::MODE = 'tuple'; is(join(',',color_get ('red')), '0255,0,0'); is(join(',',color ('red')), '0255,0,0'); is(join(',',color_mix ('red','blue')), '0128,0,0128'); is(join(',',color_blend_bw ('red')), '0255,0128,0128'); is(join(',',color_blend ('red')), '0128,0128,0128'); is(join(',',color_bw ('red')), '77,77,77'); is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); is(join(',',color_contrast ('red')), '0,0255,0255'); is(join(',',color_dark ('red')), '0128,0,0'); is(join(',',color_gray ('red')), '77,77,77'); is(join(',',color_grey ('red')), '77,77,77'); is(join(',',color_invert ('red')), '0,0255,0255'); is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/18_DEPRECATED_import_suffix.t b/t/18_DEPRECATED_import_suffix.t index 4e5ff10..ce6a0f2 100644 --- a/t/18_DEPRECATED_import_suffix.t +++ b/t/18_DEPRECATED_import_suffix.t @@ -1,69 +1,69 @@ -# $Id: 18_DEPRECATED_import_suffix.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# $Id: 18_DEPRECATED_import_suffix.t,v 1.3 2005/09/24 17:36:28 cfaerber Exp $ # use Test::More tests => 52; use Color::Calc; is(color_get_hex ('red'), 'ff0000'); is(color_hex ('red'), 'ff0000'); is(color_mix_hex ('red','blue'), '800080'); is(color_blend_bw_hex ('red'), 'ff8080'); is(color_blend_hex ('red'), '808080'); is(color_bw_hex ('red'), '4d4d4d'); is(color_contrast_bw_hex ('red'), 'ffffff'); is(color_contrast_hex ('red'), '00ffff'); is(color_dark_hex ('red'), '800000'); is(color_gray_hex ('red'), '4d4d4d'); is(color_grey_hex ('red'), '4d4d4d'); is(color_invert_hex ('red'), '00ffff'); is(color_light_hex ('red'), 'ff8080'); is(color_get_html ('F00'), 'red'); is(color_html ('F00'), 'red'); is(color_mix_html ('red','blue'), 'purple'); is(color_blend_bw_html ('red'), '#ff8080'); is(color_blend_html ('red'), 'gray'); is(color_bw_html ('red'), '#4d4d4d'); is(color_contrast_bw_html ('red'), 'white'); is(color_contrast_html ('red'), 'aqua'); is(color_dark_html ('red'), 'maroon'); is(color_gray_html ('red'), '#4d4d4d'); is(color_grey_html ('red'), '#4d4d4d'); is(color_invert_html ('red'), 'aqua'); is(color_light_html ('red'), '#ff8080'); SKIP: { eval { require Graphics::ColorObject; }; -skip "Graphics::ColorObject not installed", 12 if $@; +skip "Graphics::ColorObject not installed", 13 if $@; is(lc color_get_object ('red')->as_RGBhex, 'ff0000'); is(lc color_object ('red')->as_RGBhex, 'ff0000'); is(lc color_mix_object ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw_object ('red')->as_RGBhex, 'ff8080'); is(lc color_blend_object ('red')->as_RGBhex, '808080'); is(lc color_bw_object ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw_object ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast_object ('red')->as_RGBhex, '00ffff'); is(lc color_dark_object ('red')->as_RGBhex, '800000'); is(lc color_gray_object ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey_object ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert_object ('red')->as_RGBhex, '00ffff'); is(lc color_light_object ('red')->as_RGBhex, 'ff8080'); } is(join(',',color_get_tuple ('red')), '0255,0,0'); is(join(',',color_tuple ('red')), '0255,0,0'); is(join(',',color_mix_tuple ('red','blue')), '0128,0,0128'); is(join(',',color_blend_bw_tuple ('red')), '0255,0128,0128'); is(join(',',color_blend_tuple ('red')), '0128,0128,0128'); is(join(',',color_bw_tuple ('red')), '77,77,77'); is(join(',',color_contrast_bw_tuple ('red')), '0255,0255,0255'); is(join(',',color_contrast_tuple ('red')), '0,0255,0255'); is(join(',',color_dark_tuple ('red')), '0128,0,0'); is(join(',',color_gray_tuple ('red')), '77,77,77'); is(join(',',color_grey_tuple ('red')), '77,77,77'); is(join(',',color_invert_tuple ('red')), '0,0255,0255'); is(join(',',color_light_tuple ('red')), '0255,0128,0128'); diff --git a/t/19_DEPRECATED_module_class-method.t b/t/19_DEPRECATED_module_class-method.t index 6d77503..75e6030 100644 --- a/t/19_DEPRECATED_module_class-method.t +++ b/t/19_DEPRECATED_module_class-method.t @@ -1,68 +1,67 @@ -# $Id: 19_DEPRECATED_module_class-method.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# $Id: 19_DEPRECATED_module_class-method.t,v 1.3 2005/09/24 17:36:28 cfaerber Exp $ # use Test::More tests => 48; use Color::Calc::hex(); use Color::Calc::html(); -use Color::Calc::object(); use Color::Calc::tuple(); is(Color::Calc::hex::get ('red'), 'ff0000'); is(Color::Calc::hex::mix ('red','blue'), '800080'); is(Color::Calc::hex::blend_bw ('red'), 'ff8080'); is(Color::Calc::hex::blend ('red'), '808080'); is(Color::Calc::hex::bw ('red'), '4d4d4d'); is(Color::Calc::hex::contrast_bw ('red'), 'ffffff'); is(Color::Calc::hex::contrast ('red'), '00ffff'); is(Color::Calc::hex::dark ('red'), '800000'); is(Color::Calc::hex::gray ('red'), '4d4d4d'); is(Color::Calc::hex::grey ('red'), '4d4d4d'); is(Color::Calc::hex::invert ('red'), '00ffff'); is(Color::Calc::hex::light ('red'), 'ff8080'); is(Color::Calc::html::get ('F00'), 'red'); is(Color::Calc::html::mix ('red','blue'), 'purple'); is(Color::Calc::html::blend_bw ('red'), '#ff8080'); is(Color::Calc::html::blend ('red'), 'gray'); is(Color::Calc::html::bw ('red'), '#4d4d4d'); is(Color::Calc::html::contrast_bw ('red'), 'white'); is(Color::Calc::html::contrast ('red'), 'aqua'); is(Color::Calc::html::dark ('red'), 'maroon'); is(Color::Calc::html::gray ('red'), '#4d4d4d'); is(Color::Calc::html::grey ('red'), '#4d4d4d'); is(Color::Calc::html::invert ('red'), 'aqua'); is(Color::Calc::html::light ('red'), '#ff8080'); SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc Color::Calc::object::get ('red')->as_RGBhex, 'ff0000'); is(lc Color::Calc::object::mix ('red','blue')->as_RGBhex, '800080'); is(lc Color::Calc::object::blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc Color::Calc::object::blend ('red')->as_RGBhex, '808080'); is(lc Color::Calc::object::bw ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::object::contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc Color::Calc::object::contrast ('red')->as_RGBhex, '00ffff'); is(lc Color::Calc::object::dark ('red')->as_RGBhex, '800000'); is(lc Color::Calc::object::gray ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::object::grey ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::object::invert ('red')->as_RGBhex, '00ffff'); is(lc Color::Calc::object::light ('red')->as_RGBhex, 'ff8080'); } is(join(',',Color::Calc::tuple::get ('red')), '0255,0,0'); is(join(',',Color::Calc::tuple::mix ('red','blue')), '0128,0,0128'); is(join(',',Color::Calc::tuple::blend_bw ('red')), '0255,0128,0128'); is(join(',',Color::Calc::tuple::blend ('red')), '0128,0128,0128'); is(join(',',Color::Calc::tuple::bw ('red')), '77,77,77'); is(join(',',Color::Calc::tuple::contrast_bw ('red')), '0255,0255,0255'); is(join(',',Color::Calc::tuple::contrast ('red')), '0,0255,0255'); is(join(',',Color::Calc::tuple::dark ('red')), '0128,0,0'); is(join(',',Color::Calc::tuple::gray ('red')), '77,77,77'); is(join(',',Color::Calc::tuple::grey ('red')), '77,77,77'); is(join(',',Color::Calc::tuple::invert ('red')), '0,0255,0255'); is(join(',',Color::Calc::tuple::light ('red')), '0255,0128,0128'); diff --git a/t/19_DEPRECATED_module_import_object.t b/t/19_DEPRECATED_module_import_object.t index 32c6074..703b8f9 100644 --- a/t/19_DEPRECATED_module_import_object.t +++ b/t/19_DEPRECATED_module_import_object.t @@ -1,24 +1,23 @@ -# $Id: 19_DEPRECATED_module_import_object.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# $Id: 19_DEPRECATED_module_import_object.t,v 1.3 2005/09/24 17:36:28 cfaerber Exp $ # use Test::More tests => 13; -use Color::Calc::object; SKIP: { eval { require Graphics::ColorObject; }; -skip "Graphics::ColorObject not installed", 12 if $@; +skip "Graphics::ColorObject not installed", 13 if $@; is(lc color_get ('red')->as_RGBhex, 'ff0000'); is(lc color ('red')->as_RGBhex, 'ff0000'); is(lc color_mix ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc color_blend ('red')->as_RGBhex, '808080'); is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast ('red')->as_RGBhex, '00ffff'); is(lc color_dark ('red')->as_RGBhex, '800000'); is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert ('red')->as_RGBhex, '00ffff'); is(lc color_light ('red')->as_RGBhex, 'ff8080'); } diff --git a/t/1use.t b/t/1use.t deleted file mode 100644 index 4e392d0..0000000 --- a/t/1use.t +++ /dev/null @@ -1,4 +0,0 @@ -use Test::More tests => 3; -BEGIN { use_ok('Color::Calc') }; -is(uc(color_contrast_hex('#000000')),'FFFFFF'); -is(uc(color_contrast_html('#000000')),'#FFFFFF'); diff --git a/t/20_hex.t b/t/20_hex.t deleted file mode 100644 index 8ec5ef1..0000000 --- a/t/20_hex.t +++ /dev/null @@ -1,9 +0,0 @@ -use Test::More tests => 6; -use Color::Calc::hex; - -is(color('red'), 'ff0000'); -is(color([255,0,0]), 'ff0000'); -is(color('F00'), 'ff0000'); -is(color('FF0000'), 'ff0000'); -is(color('#F00'), 'ff0000'); -is(color('#FF0000'), 'ff0000'); diff --git a/t/21_html.t b/t/21_html.t deleted file mode 100644 index 78177da..0000000 --- a/t/21_html.t +++ /dev/null @@ -1,9 +0,0 @@ -use Test::More tests => 6; -use Color::Calc::html; - -is(color('red'), 'red'); -is(color([255,0,0]), 'red'); -is(color('F00'), 'red'); -is(color('FF0000'), 'red'); -is(color('#F00'), 'red'); -is(color('#FF0000'), 'red'); diff --git a/t/30_mix.t b/t/30_mix.t deleted file mode 100644 index 6d08ecf..0000000 --- a/t/30_mix.t +++ /dev/null @@ -1,16 +0,0 @@ -use Test::More tests => 10; -use Color::Calc::hex; - -is(color_mix('black','white'), '808080'); -is(color_mix('black','white',0.25), '404040'); - -is(color_light('white'), 'ffffff'); -is(color_light('black'), '808080'); -is(color_light('black',0.25), '404040'); - -is(color_dark('black'), '000000'); -is(color_dark('white'), '808080'); -is(color_dark('white',0.25), 'bfbfbf'); - -is(color_dark('CCCCCC'), '666666'); -is(color_light('CCCCCC'), 'e6e6e6'); diff --git a/t/90_Graphics-ColorObject.t b/t/90_Graphics-ColorObject.t deleted file mode 100644 index 71dd11a..0000000 --- a/t/90_Graphics-ColorObject.t +++ /dev/null @@ -1,10 +0,0 @@ -use Test::More tests => 2; -use Color::Calc; - -SKIP: { - eval { require Graphics::ColorObject; }; - skip "Graphics::ColorObject not installed", 2 if $@; - - is(color_object('red')->as_RGBhex, 'FF0000'); - is(color_mix_object('red','blue')->as_RGBhex, '808000'); -}; diff --git a/t/91_PDF-API2-Color.t b/t/91_PDF-API2-Color.t deleted file mode 100644 index 90036c1..0000000 --- a/t/91_PDF-API2-Color.t +++ /dev/null @@ -1,12 +0,0 @@ -use Test::More tests => 2; -use Color::Calc; - -SKIP: { - -no warnings 'redefine'; - eval { require PDF::API2::Color; }; - skip "PDF::API2::Color not installed", 2 if $@; - - is(color_pdf('red')->asHex, '#FF0000'); - is(color_mix_pdf('red','blue')->asHex, '#800080'); -};
cfaerber/Graphics-ColorNames-WWW
02463ac62085c85d14b2b95c3219af5588b6f6ea
Color-Calc-0.29_0003
diff --git a/Calc.pm b/Calc.pm index ad04b96..5134a2e 100644 --- a/Calc.pm +++ b/Calc.pm @@ -1,613 +1,615 @@ +# $Id: Calc.pm,v 1.10 2005/04/09 20:49:58 cfaerber Exp $ +# package Color::Calc; use strict; use Carp; use POSIX; use Params::Validate qw(:all); use Graphics::ColorNames qw( hex2tuple tuple2hex ); use Graphics::ColorNames::HTML; our $VERSION = '0.29_0003'; $VERSION = eval $VERSION; our $MODE = (); my %__HTMLColors = (); our @__subs = qw( blend blend_bw bw contrast contrast_bw dark get grey gray invert light mix ); my %__formats = ( 'tuple' => sub { return __normtuple_out(@_); }, 'hex' => sub { return tuple2hex((@_)); }, 'html' => sub { my $col = lc(tuple2hex((@_))); return $__HTMLColors{$col} || '#'.$col; }, 'object' => sub { eval { require Graphics::ColorObject; }; return Graphics::ColorObject->new_RGB255( [(@_)] ); }, # 'pdf' => sub { eval { require PDF::API2::Color; }; return PDF::API2::Color->newRGB( map { $_ / 255 } ((@_))); }, ); my @__formats = keys %__formats; my $__formats_re = join('|', @__formats,'__MODEvar'); { my $table = Graphics::ColorNames::HTML::NamesRgbTable(); %__HTMLColors = map { ( sprintf('%06x', $$table{$_}) => $_ ) } grep { $_ ne 'fuscia' } keys %$table; }; our @EXPORT = ('color', map({"color_$_"} @__formats, map({my $s=$_; (map{$s.'_'.$_} @__formats)} @__subs), @__subs)); our @ISA = ('Exporter'); my %new_param = ( 'ColorScheme' => { type => SCALAR, optional => 1 }, 'OutputFormat' => { type => SCALAR, untaint => 1, regexp => qr($__formats_re), optional => 1 }, ); sub new { my $pkg = shift; validate(@_, \%new_param); my $self = {@_}; bless($self, $pkg); if(!ref($self->{'ColorScheme'})) { my %ColorNames; tie %ColorNames, 'Graphics::ColorNames', ($self->{'ColorScheme'} || 'X'); $self->{'ColorScheme'} = \%ColorNames; } $self->set_output_format($self->{'OutputFormat'} || 'tuple'); return $self; } my $__default_object = undef; sub __get_default { $__default_object = __PACKAGE__->new('OutputFormat' => '__MODEvar') unless $__default_object; return $__default_object; } my $__tuple_object = undef; sub __get_tuple { $__tuple_object = __PACKAGE__->new('OutputFormat' => 'tuple') unless $__tuple_object; return $__tuple_object; } my %import_param = ( %new_param, 'Prefix' => { type => SCALAR, optional => 1, regexp => qr/^[[:alpha:]\d]\w*$/ }, '__Prefix' => { type => SCALAR, optional => 1, regexp => qr/^[[:alpha:]\d]\w*$/ }, '__Suffix' => { type => SCALAR, optional => 1, regexp => qr/^\w+$/ }, ); my %import_param_names = map { ($_=>1) } keys %import_param; sub import { my $pkg = shift; if(!@_ || !exists $import_param_names{$_[0]}) { local $Exporter::ExportLevel; $Exporter::ExportLevel++; return Exporter::import($pkg, @_); } return __import(scalar caller(0),@_) ? 1 : 0; } sub __import { my $pkg = shift; validate(@_, \%import_param); my %param = @_; my $std_prefix = (exists $param{'Prefix'}) ? $param{'Prefix'} : 'color'; delete $param{'Prefix'}; my $prefix = (exists $param{'__Prefix'}) ? $param{'__Prefix'} : $std_prefix ? $std_prefix.'_' : ''; delete $param{'__Prefix'}; my $suffix = (exists $param{'__Suffix'}) ? $param{'__Suffix'} : ''; delete $param{'__Suffix'}; my $obj = new(__PACKAGE__, %param); { no strict 'refs'; { $prefix = $pkg.'::'.$prefix; foreach my $sub (@__subs) { my $name = $prefix.$sub.$suffix; *$name = sub { $obj->$sub(@_); }; }; }; if($std_prefix) { my $name = $pkg.'::'.$std_prefix.$suffix; *$name = sub { $obj->get(@_); }; } } return 1; } sub __normtuple_in { return map { ($_ < 0) ? 0 : (($_ > 255) ? 255 : int($_+.5)) } @_; } sub __normtuple_out { return map { (length $_) == 3 ? '0'.$_ : $_ } __normtuple_in(@_) } sub __normtuple { return __normtuple_out(__normtuple_in(@_)); } sub __is_col_val { return undef unless defined $_[0]; return undef if $_[0] eq ''; my ($n,$u) = POSIX::strtod($_[0]); return undef if $u != 0; return ($n <= 255) && ($n>= 0); } # Note: Color::Object was supported in versions before 0.2. This # is kept for compatibility, but no longer documented. # # Note: versions before 0.2 allowed calling some functions (those # with one parameter) with a list instead of an arrayref. This is # kept for compatibility, but no longer documented. sub __get { my ($self,$p,$q) = @_; if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 0 ) { $$p[0] = $$p[0]->[0]; } if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 2 ) { return __normtuple_in(@{shift @$p}); } elsif( UNIVERSAL::isa($$p[0],'Color::Object') || UNIVERSAL::isa($$p[0],'PDF::API2::Color')) { return (map { 255 * $_; } (shift(@{$p})->asRGB)); } elsif( UNIVERSAL::isa($$p[0],'Graphics::ColorObject')) { return (shift(@{$p})->as_RGB255()); } elsif( $#$p >= (2 + ($q||0)) && __is_col_val($$p[0]) && __is_col_val($$p[1]) && __is_col_val($$p[2])) { return (splice @$p, 0, 3); } elsif( $$p[0] =~ m/^#?([0-9A-F])([0-9A-F])([0-9A-F])$/i ) { shift @$p; return (map { hex($_) * 17 } ($1,$2,$3)); } elsif( $$p[0] =~ m/^#?([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])$/i ) { shift @$p; return (map { hex($_) } ($1,$2,$3)); } else { my $col = $self->{'ColorScheme'}->{$$p[0]}; if($col) { shift @$p; return hex2tuple($col); } else { carp("Invalid color name '$$p[0]'"); return undef; } } } sub set_output_format { validate_pos(@_, { isa => __PACKAGE__ }, { type => SCALAR, regexp => qr($__formats_re) }); my $self = shift; my $old = $self->{'OutputFormat'}; $self->{'OutputFormat'} = shift; $self->{'__put'} = $self->{'OutputFormat'} eq '__MODEvar' ? sub{ return $__formats{$MODE || 'tuple'}->(@_); } : $__formats{$self->{'OutputFormat'}}; return $old; } sub __put { my $self = shift; return $self->{'__put'}->(__normtuple_in(@_)); } sub __get_self { if(UNIVERSAL::isa($_[0]->[0], __PACKAGE__)) { return shift @{$_[0]}; } else { return __get_default; } } sub get { my $self = __get_self(\@_); return $self->__put($self->__get(\@_)); } sub invert { my $self = __get_self(\@_); return $self->__put(map { 255 - $_ } $self->__get(\@_)); } sub bw { my $self = __get_self(\@_); my @c = $self->__get(\@_); my $g = $c[0]*.3 + $c[1]*.59 + $c[2]*.11; return $self->__put(__normtuple($g,$g,$g)); } *grey = \&bw; *gray = \&bw; sub mix { my $self = __get_self(\@_); my @c1 = ($self->__get(\@_,1)); my @c2 = ($self->__get(\@_)); my $alpha = shift(@_); $alpha = 0.5 unless defined $alpha; return $self->__put(__normtuple( ($c1[0] + ($c2[0]-$c1[0])*$alpha), ($c1[1] + ($c2[1]-$c1[1])*$alpha), ($c1[2] + ($c2[2]-$c1[2])*$alpha) )); } sub light { my $self = __get_self(\@_); return $self->__put(__get_tuple->mix([$self->__get(\@_)],[255,255,255],shift)); } sub dark { my $self = __get_self(\@_); return $self->__put(__get_tuple->mix([$self->__get(\@_)],[0,0,0],shift)); } sub contrast { my $self = __get_self(\@_); my @rgb = $self->__get(\@_); my $cut = (shift || .5) * 255; return $self->__put(map { $_ >= $cut ? 0 : '0255' } @rgb); } sub contrast_bw { my $self = __get_self(\@_); my @rgb = $self->__get(\@_); return $self->__put(__get_tuple->contrast([__get_tuple->bw(@rgb)], shift)); } sub blend { my $self = __get_self(\@_); my @c1 = $self->__get(\@_); return $self->mix(\@c1,[__get_tuple->contrast(\@c1)],shift); } sub blend_bw { my $self = __get_self(\@_); my @c = $self->__get(\@_); return $self->mix(\@c,[__get_tuple->contrast_bw(\@c)],shift); } foreach my $format (@__formats) { __import(__PACKAGE__, 'Prefix' => 'color', '__Suffix' => "_$format", 'OutputFormat' => $format); __import(__PACKAGE__, 'Prefix' => '', '__Suffix' => "_$format", 'OutputFormat' => $format); } __import(__PACKAGE__, 'Prefix' => 'color', 'OutputFormat' => '__MODEvar'); =head1 NAME Color::Calc - Simple calculations with RGB colors. =head1 SYNOPSIS use Color::Calc (); my $background = 'green'; print 'background: ',Color::Calc::color_html($background),';'; print 'border-top: solid 1px ',Color::Calc::light_html($background),';'; print 'border-bottom: solid 1px ',Color::Calc::dark_html($background),';'; print 'color: ',contrast_bw_html($background),';'; =head1 DESCRIPTION The C<Color::Calc> module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. =head2 Color Formats =head3 Input All of the methods accept colors as parameters in the following formats: =over =item * An arrayref pointing to an array with three elements in the range C<0>..C<255> corresponding to the red, green, and blue component. =item * A string containing a hexadecimal RGB value in the form C<#I<RRGGBB>>/C<#I<RGB>> or C<I<RGB>>/C<I<RRGGBB>>. =item * A color name accepted by C<Graphics::ColorNames>. =item * A C<PDF::API2::Color> reference. =item * A C<Graphics::ColorObject> reference. =item * A return value of any (public) C<Color::Calc> method even if the C<tuple> output format is selected. =back =head3 Output C<Color::Calc> can return colors in the following modes: =over =item tuple Returns a list of three values in the range 0..255. =item hex Returns a hexadecimal RGB value in the format RRGGBB. =item html Returns a value compatible with W3C's HTML and CSS specifications, i.e. I<#RRGGBB> or one of the sixteen color names. =item pdf Returns a C<PDF::API2::Color> reference. The module C<PDF::API2::Color> must be installed. =item object Returns a C<Graphics::ColorObject> reference. The module C<Graphics::ColorObject> must be installed. =item __MODEvar (DEPRECATED) Uses the value of C<$Color::Calc::MODE> to select the output format. You should use C<local> when setting this variable. =back =head2 Object-Orientated interface use Color::Calc(); my $cc = new Color::Calc( 'ColorScheme' => 'X', OutputFormat => 'HTML' ); print $cc->invert( 'white' ); =over =item new $cc = new Color::Calc( 'ColorScheme' => $name, 'OutputFormat' => $format ); Creates a new C<Color::Calc> object which can be used to access the color calculation methods. =over =item ColorScheme One of the color schemes accepted by C<Graphics::ColorNames>. Used to translate color names on input. See the documentation of C<Graphics::ColorNames> for possible values. Default: C<X> (please note that this is incompatible with HTML color names). =item OutputFormat Sets the output format of the object's methods. See above for possible values. Default: C<__MODEvar> =back =item $cc->get($color) Returns the color as-is (but in the selected output format). This function can be used for color format conversion/normalisation. =item $cc->invert($color) Returns the inverse of $color. =item $cc->bw($color) =item $cc->grey($color) Converts $color to greyscale. =item $cc->mix($color1, $color2 [, $alpha]) Returns a color that is the mixture of $color1 and $color2. The optional $alpha parameter can be a value between 0.0 (use $color1 only) and 1.0 (use $color2 only), the default is 0.5. =item $cc->color_light($color [, $alpha]) Returns a lighter version of $color, i.e. returns $cc->mix($color,[255,255,255],$alpha); The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use 'white' only), the default is 0.5. =item $cc->dark($color [, $alpha]) Returns a darker version of $color, i.e. returns $cc->mix($color,[0,0,0],$alpha); The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use 'black' only), the default is 0.5. =item $cc->contrast($color [, $cut]) Returns a color that has the highest possible contrast to the input color. This is done by setting the red, green, and blue values to 0 if the corresponding value in the input is above C<($cut * 255)> and to 255 otherwise. The default for C<$cut> is .5, representing a cutoff between 127 and 128. =item $cc->contrast_bw($color [, $cut]) Returns black or white, whichever has the higher contrast to $color. This is done by setting returning black if the grey value of $color is above C<($cut * 255)> and white otherwise. The default for C<$cut> is .5, representing a cutoff between 127 and 128. =item $cc->blend($color [, $alpha]) Returns a color that blends into the background, i.e. it returns $cc->mix($color,$cc->contrast($color),$alpha). The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use C<contrast($color)> only), the default is 0.5. The idea is that C<$color> is the foreground color, so C<contrast($color)> is similar to the background color. Mixing them returns a color somewhere between them. You might want to use mix($color, $background, $alpha) instead if you know the real background color. =item $cc->blend_bw($color [, $alpha]) Returns a mix of $color and black or white, whichever has the higher contrast to $color. The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use black/white only), the default is 0.5. =back =head2 Procedural Interface With Importing You can also choose to import customised funtions into your namespace: use Color::Calc( 'ColorScheme' => 'X', 'OutputFormat' => 'HTML', 'Prefix' => 'cc' ); print cc_invert( 'white' ); # prints 'black' On import, you can specify the following parameters: =over =item ColorScheme See above. =item OutputFormat See above. =item Prefix Adds the prefix and an underscore to the front of the method names. You can call the methods as I<prefix>_I<method_name>. You can also call I<prefix> instead of I<prefix>C<_get>. Default: C<color> =back Please note that specifying an empty list of parameters means "don't import anything". Omit the list to import the default functions. You can also C<use> the following modules to import the function with pre-defined parameters. =over =item C<use Color::Calc::WWW> Same as C<use Color::Calc( ColorScheme =&gt; 'WWW', OutputFormat => 'html' )> =item C<use Color::Calc::html> (DEPRECATED) Same as C<use Color::Calc( OutputFormat =&gt; 'html')> Please note that this only selects HTML as the C<OutputFormat> but not as the C<ColorScheme> (which defaults to 'X'), which is probably not what you expect. Use C<Color::Calc::WWW> instead. =item C<use Color::Calc::hex> Same as C<use Color::Calc( OutputFormat =&gt; 'hex')> =item C<use Color::Calc::object> Same as C<use Color::Calc( OutputFormat =&gt; 'object')> =item C<use Color::Calc::pdf> Same as C<use Color::Calc( OutputFormat =&gt; 'pdf')> =item C<use Color::Calc::tuple> Same as C<use Color::Calc( OutputFormat =&gt; 'tuple')> =back =head2 Procedural Interface Without Importing (DEPRECATED) You can also access the methods as class methods of the various packages with and without the C<color> prefix: use Color::Calc::WWW(); print Color::Calc::WWW::color('FFF'); # prints 'white' print Color::Calc::WWW::color_invert('FFF'); # prints 'black' print Color::Calc::html::invert('FFF'); # prints 'black' For the main module C<Color::Calc>, you can also add a suffix C<_I<output_format>> to select the output format: use Color::Calc(); print Color::Calc::color_html('FFF'); # prints 'white' print Color::Calc::color_invert_html('FFF'); # prints 'black' print Color::Calc::invert_hex('FFF'); # prints '000000' =head1 SEE ALSO L<Graphics::ColorNames> (required); -L<Color::Object> (optional) +L<Graphics::ColorObject> (optional) =head1 AUTHOR Claus A. Färber <perl@faerber.muc.de> =head1 COPYRIGHT Copyright © 2004, 2005 Claus A. Färber All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; diff --git a/Calc/WWW.pm b/Calc/WWW.pm index 94a79ee..37ed118 100644 --- a/Calc/WWW.pm +++ b/Calc/WWW.pm @@ -1,12 +1,14 @@ +# $Id: WWW.pm,v 1.4 2005/04/09 20:49:58 cfaerber Exp $ +# package Color::Calc::WWW; use strict; use Carp; use Exporter; use Color::Calc('OutputFormat' => 'html', 'ColorScheme' => 'WWW'); our @ISA = qw(Exporter); our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); 1; diff --git a/Calc/hex.pm b/Calc/hex.pm index a3c59ee..2d44758 100644 --- a/Calc/hex.pm +++ b/Calc/hex.pm @@ -1,23 +1,25 @@ +# $Id: hex.pm,v 1.2 2005/04/09 20:49:58 cfaerber Exp $ +# package Color::Calc::hex; use strict; use Carp; use Exporter; use Color::Calc(); our @ISA = qw(Exporter); our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); *color = \&Color::Calc::color_hex; foreach my $sub (@Color::Calc::__subs) { my $su1 = 'color_'.$sub; my $dst = 'Color::Calc::'.$sub.'_hex'; no strict 'refs'; *$sub = \&$dst; *$su1 = \&$dst; }; 1; diff --git a/Calc/html.pm b/Calc/html.pm index f0daa19..53b0d14 100644 --- a/Calc/html.pm +++ b/Calc/html.pm @@ -1,23 +1,25 @@ +# $Id: html.pm,v 1.2 2005/04/09 20:49:58 cfaerber Exp $ +# package Color::Calc::html; use strict; use Carp; use Exporter; use Color::Calc(); our @ISA = qw(Exporter); our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); *color = \&Color::Calc::color_html; foreach my $sub (@Color::Calc::__subs) { my $su1 = 'color_'.$sub; my $dst = 'Color::Calc::'.$sub.'_html'; no strict 'refs'; *$sub = \&$dst; *$su1 = \&$dst; }; 1; diff --git a/Calc/object.pm b/Calc/object.pm index 779aced..403a49c 100644 --- a/Calc/object.pm +++ b/Calc/object.pm @@ -1,24 +1,26 @@ +# $Id: object.pm,v 1.2 2005/04/09 20:49:58 cfaerber Exp $ +# package Color::Calc::object; use Graphics::ColorObject; use strict; use Carp; use Exporter; use Color::Calc(); our @ISA = qw(Exporter); our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); *color = \&Color::Calc::color_object; foreach my $sub (@Color::Calc::__subs) { my $su1 = 'color_'.$sub; my $dst = 'Color::Calc::'.$sub.'_object'; no strict 'refs'; *$sub = \&$dst; *$su1 = \&$dst; }; 1; diff --git a/Calc/tuple.pm b/Calc/tuple.pm index c04f54b..ae479f2 100644 --- a/Calc/tuple.pm +++ b/Calc/tuple.pm @@ -1,23 +1,25 @@ +# $Id: tuple.pm,v 1.2 2005/04/09 20:49:58 cfaerber Exp $ +# package Color::Calc::tuple; use strict; use Carp; use Exporter; use Color::Calc(); our @ISA = qw(Exporter); our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); *color = \&Color::Calc::color_tuple; foreach my $sub (@Color::Calc::__subs) { my $su1 = 'color_'.$sub; my $dst = 'Color::Calc::'.$sub.'_tuple'; no strict 'refs'; *$sub = \&$dst; *$su1 = \&$dst; }; 1; diff --git a/Changes b/Changes index 9952e0f..8f950c7 100644 --- a/Changes +++ b/Changes @@ -1,34 +1,36 @@ Revision history for Perl extension Color::Calc. 0.29_0002 Sat Mar 26 16:20:00 2005 - Color::Calc::WWW now uses Graphics::ColorNames::WWW - Color::Calc::WWW was missing from distribution - removed 'pdf' output format as PDF::API2::Color is no longer - complete test suite 0.29_0001 Fri Mar 25 12:00:00 2005 - added object-orientated interface - added procedural interface with customisation on import - added Color::Calc::WWW - color scheme is now selectable 0.20 Mon Mar 28 00:00:00 2004 - added Color::Calc::<xxx> modules to select return type - added $Color::Calc::MODE to select return type - return value of xxx_tuple can be used as parameter - <xxx>_html returns color names instead of #RRGGBB if possible - support for Graphics::ColorObject (input/output) - support for PDF::API2::Color (input/output) - fixed import list 0.12 Thu Mar 18 00:00:00 2004 - added xxx_html - should work with perl 5.005 now 0.10 Sun May 04 00:00:00 2003 - added tests - added more functions - some documentation corrections 0.02 Sat Apr 26 00:00:00 2003 - first public release + +$Id: Changes,v 1.8 2005/04/09 20:49:58 cfaerber Exp $ diff --git a/MANIFEST b/MANIFEST index 2cf8630..22cfbe7 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,33 +1,33 @@ Calc.pm Calc/WWW.pm Calc/hex.pm Calc/html.pm Calc/object.pm Calc/tuple.pm Changes -Makefile +Makefile.PL MANIFEST META.yml README t/00_basic.t t/10_object-orientated.t t/11_import_hex.t t/11_import_html.t t/11_import_MODEval.t t/11_import_object.t t/11_import_tuple.t t/12_import_module_WWW.t t/18_DEPRECATED_class-method_MODEval.t t/18_DEPRECATED_class-method_suffix.t t/18_DEPRECATED_import_MODEval.t t/18_DEPRECATED_import_suffix.t t/19_DEPRECATED_module_class-method.t t/19_DEPRECATED_module_import_hex.t t/19_DEPRECATED_module_import_html.t t/19_DEPRECATED_module_import_object.t t/19_DEPRECATED_module_import_tuple.t t/20_input_formats_oo.t t/21_input_formats_import.t t/30_color_schemes_oo.t t/31_color_schemes_import_HTML.t t/31_color_schemes_import_X.t diff --git a/META.yml b/META.yml index 9e6fef7..4b561ac 100644 --- a/META.yml +++ b/META.yml @@ -1,13 +1,13 @@ # http://module-build.sourceforge.net/META-spec.html #XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX# name: Color-Calc -version: 0.29_0002 +version: 0.29_0003 version_from: Calc.pm installdirs: site requires: Graphics::ColorNames: 0.32 Graphics::ColorNames::SVG: 0 Params::Validate: 0.75 distribution_type: module generated_by: ExtUtils::MakeMaker version 6.17 diff --git a/Makefile.PL b/Makefile.PL index 1127e31..53f39f0 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,14 +1,17 @@ +# $Id: Makefile.PL,v 1.4 2005/04/09 20:49:58 cfaerber Exp $ +# use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'Color::Calc', 'VERSION_FROM' => 'Calc.pm', # finds $VERSION 'PREREQ_PM' => { 'Graphics::ColorNames' => 0.32, + 'Graphics::ColorNames::SVG' => 0.00, 'Params::Validate' => 0.75, }, ($] >= 5.005 ? ## Add these new keywords supported since 5.005 (ABSTRACT_FROM => 'Calc.pm', # retrieve abstract from module AUTHOR => 'Claus Färber <perl@faerber.muc.de>') : ()), ); diff --git a/README b/README index 60892c8..cb4a743 100644 --- a/README +++ b/README @@ -1,37 +1,36 @@ -Color::Calc 0.2 -=============== +Color::Calc +=========== The "Color::Calc" module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. The module is useful for CGI (or embedded perl) programmes that create HTML or CSS output. INSTALLATION To install this module type the following: perl Makefile.PL make make test make install DEPENDENCIES This module requires these other modules and libraries: Graphics::ColorNames The following modules are optional: Color::Object - PDF::API2::Color Graphics::ColorObject COPYRIGHT AND LICENCE -Copyright © 2004 Claus A. Färber +Copyright © 2004, 2005 Claus A. Färber This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/t/00_basic.t b/t/00_basic.t index 7681466..39caa7e 100644 --- a/t/00_basic.t +++ b/t/00_basic.t @@ -1,6 +1,8 @@ +# $Id: 00_basic.t,v 1.5 2005/04/09 20:49:58 cfaerber Exp $ +# use Test::More tests => 2; use_ok('Color::Calc'); my $cc = new Color::Calc; isa_ok($cc, 'Color::Calc'); diff --git a/t/10_object-orientated.t b/t/10_object-orientated.t index c817d65..abd7654 100644 --- a/t/10_object-orientated.t +++ b/t/10_object-orientated.t @@ -1,67 +1,69 @@ +# $Id: 10_object-orientated.t,v 1.2 2005/04/09 20:49:58 cfaerber Exp $ +# use Test::More tests => 48; use Color::Calc(); my $cc = Color::Calc->new( 'OutputFormat' => 'hex' ); is($cc->get ('red'), 'ff0000'); is($cc->mix ('red','blue'), '800080'); is($cc->blend_bw ('red'), 'ff8080'); is($cc->blend ('red'), '808080'); is($cc->bw ('red'), '4d4d4d'); is($cc->contrast_bw ('red'), 'ffffff'); is($cc->contrast ('red'), '00ffff'); is($cc->dark ('red'), '800000'); is($cc->gray ('red'), '4d4d4d'); is($cc->grey ('red'), '4d4d4d'); is($cc->invert ('red'), '00ffff'); is($cc->light ('red'), 'ff8080'); $cc = Color::Calc->new( 'OutputFormat' => 'html' ); is($cc->get ('F00'), 'red'); is($cc->mix ('red','blue'), 'purple'); is($cc->blend_bw ('red'), '#ff8080'); is($cc->blend ('red'), 'gray'); is($cc->bw ('red'), '#4d4d4d'); is($cc->contrast_bw ('red'), 'white'); is($cc->contrast ('red'), 'aqua'); is($cc->dark ('red'), 'maroon'); is($cc->gray ('red'), '#4d4d4d'); is($cc->grey ('red'), '#4d4d4d'); is($cc->invert ('red'), 'aqua'); is($cc->light ('red'), '#ff8080'); $cc = Color::Calc->new( 'OutputFormat' => 'object' ); SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc $cc->get ('red')->as_RGBhex, 'ff0000'); is(lc $cc->mix ('red','blue')->as_RGBhex, '800080'); is(lc $cc->blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc $cc->blend ('red')->as_RGBhex, '808080'); is(lc $cc->bw ('red')->as_RGBhex, '4d4d4d'); is(lc $cc->contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc $cc->contrast ('red')->as_RGBhex, '00ffff'); is(lc $cc->dark ('red')->as_RGBhex, '800000'); is(lc $cc->gray ('red')->as_RGBhex, '4d4d4d'); is(lc $cc->grey ('red')->as_RGBhex, '4d4d4d'); is(lc $cc->invert ('red')->as_RGBhex, '00ffff'); is(lc $cc->light ('red')->as_RGBhex, 'ff8080'); } $cc = Color::Calc->new( 'OutputFormat' => 'tuple' ); is(join(',',$cc->get ('red')), '0255,0,0'); is(join(',',$cc->mix ('red','blue')), '0128,0,0128'); is(join(',',$cc->blend_bw ('red')), '0255,0128,0128'); is(join(',',$cc->blend ('red')), '0128,0128,0128'); is(join(',',$cc->bw ('red')), '77,77,77'); is(join(',',$cc->contrast_bw ('red')), '0255,0255,0255'); is(join(',',$cc->contrast ('red')), '0,0255,0255'); is(join(',',$cc->dark ('red')), '0128,0,0'); is(join(',',$cc->gray ('red')), '77,77,77'); is(join(',',$cc->grey ('red')), '77,77,77'); is(join(',',$cc->invert ('red')), '0,0255,0255'); is(join(',',$cc->light ('red')), '0255,0128,0128'); diff --git a/t/11_import_MODEval.t b/t/11_import_MODEval.t index 9ae8bb7..c947500 100644 --- a/t/11_import_MODEval.t +++ b/t/11_import_MODEval.t @@ -1,71 +1,73 @@ +# $Id: 11_import_MODEval.t,v 1.2 2005/04/09 20:49:58 cfaerber Exp $ +# use Test::More tests => 52; use Color::Calc; local $Color::Calc::MODE = 'hex'; is(color_get ('red'), 'ff0000'); is(color ('red'), 'ff0000'); is(color_mix ('red','blue'), '800080'); is(color_blend_bw ('red'), 'ff8080'); is(color_blend ('red'), '808080'); is(color_bw ('red'), '4d4d4d'); is(color_contrast_bw ('red'), 'ffffff'); is(color_contrast ('red'), '00ffff'); is(color_dark ('red'), '800000'); is(color_gray ('red'), '4d4d4d'); is(color_grey ('red'), '4d4d4d'); is(color_invert ('red'), '00ffff'); is(color_light ('red'), 'ff8080'); local $Color::Calc::MODE = 'html'; is(color_get ('F00'), 'red'); is(color ('F00'), 'red'); is(color_mix ('red','blue'), 'purple'); is(color_blend_bw ('red'), '#ff8080'); is(color_blend ('red'), 'gray'); is(color_bw ('red'), '#4d4d4d'); is(color_contrast_bw ('red'), 'white'); is(color_contrast ('red'), 'aqua'); is(color_dark ('red'), 'maroon'); is(color_gray ('red'), '#4d4d4d'); is(color_grey ('red'), '#4d4d4d'); is(color_invert ('red'), 'aqua'); is(color_light ('red'), '#ff8080'); local $Color::Calc::MODE = 'object'; SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc color_get ('red')->as_RGBhex, 'ff0000'); is(lc color ('red')->as_RGBhex, 'ff0000'); is(lc color_mix ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc color_blend ('red')->as_RGBhex, '808080'); is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast ('red')->as_RGBhex, '00ffff'); is(lc color_dark ('red')->as_RGBhex, '800000'); is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert ('red')->as_RGBhex, '00ffff'); is(lc color_light ('red')->as_RGBhex, 'ff8080'); } local $Color::Calc::MODE = 'tuple'; is(join(',',color_get ('red')), '0255,0,0'); is(join(',',color ('red')), '0255,0,0'); is(join(',',color_mix ('red','blue')), '0128,0,0128'); is(join(',',color_blend_bw ('red')), '0255,0128,0128'); is(join(',',color_blend ('red')), '0128,0128,0128'); is(join(',',color_bw ('red')), '77,77,77'); is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); is(join(',',color_contrast ('red')), '0,0255,0255'); is(join(',',color_dark ('red')), '0128,0,0'); is(join(',',color_gray ('red')), '77,77,77'); is(join(',',color_grey ('red')), '77,77,77'); is(join(',',color_invert ('red')), '0,0255,0255'); is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/11_import_hex.t b/t/11_import_hex.t index 9f208c1..06a9447 100644 --- a/t/11_import_hex.t +++ b/t/11_import_hex.t @@ -1,17 +1,19 @@ +# $Id: 11_import_hex.t,v 1.2 2005/04/09 20:49:58 cfaerber Exp $ +# use Test::More tests => 13; use Color::Calc( 'OutputFormat' => 'hex' ); is(color_get ('red'), 'ff0000'); is(color ('red'), 'ff0000'); is(color_mix ('red','blue'), '800080'); is(color_blend_bw ('red'), 'ff8080'); is(color_blend ('red'), '808080'); is(color_bw ('red'), '4d4d4d'); is(color_contrast_bw ('red'), 'ffffff'); is(color_contrast ('red'), '00ffff'); is(color_dark ('red'), '800000'); is(color_gray ('red'), '4d4d4d'); is(color_grey ('red'), '4d4d4d'); is(color_invert ('red'), '00ffff'); is(color_light ('red'), 'ff8080'); diff --git a/t/11_import_html.t b/t/11_import_html.t index 791d2bd..942e4d8 100644 --- a/t/11_import_html.t +++ b/t/11_import_html.t @@ -1,17 +1,19 @@ +# $Id: 11_import_html.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 13; use Color::Calc( 'OutputFormat' => 'html' ); is(color_get ('F00'), 'red'); is(color ('F00'), 'red'); is(color_mix ('red','blue'), 'purple'); is(color_blend_bw ('red'), '#ff8080'); is(color_blend ('red'), 'gray'); is(color_bw ('red'), '#4d4d4d'); is(color_contrast_bw ('red'), 'white'); is(color_contrast ('red'), 'aqua'); is(color_dark ('red'), 'maroon'); is(color_gray ('red'), '#4d4d4d'); is(color_grey ('red'), '#4d4d4d'); is(color_invert ('red'), 'aqua'); is(color_light ('red'), '#ff8080'); diff --git a/t/11_import_object.t b/t/11_import_object.t index 6453a23..75ac540 100644 --- a/t/11_import_object.t +++ b/t/11_import_object.t @@ -1,22 +1,24 @@ +# $Id: 11_import_object.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 13; use Color::Calc( 'OutputFormat' => 'object' ); SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc color_get ('red')->as_RGBhex, 'ff0000'); is(lc color ('red')->as_RGBhex, 'ff0000'); is(lc color_mix ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc color_blend ('red')->as_RGBhex, '808080'); is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast ('red')->as_RGBhex, '00ffff'); is(lc color_dark ('red')->as_RGBhex, '800000'); is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert ('red')->as_RGBhex, '00ffff'); is(lc color_light ('red')->as_RGBhex, 'ff8080'); } diff --git a/t/11_import_tuple.t b/t/11_import_tuple.t index c23ba39..097c584 100644 --- a/t/11_import_tuple.t +++ b/t/11_import_tuple.t @@ -1,17 +1,19 @@ +# $Id: 11_import_tuple.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 13; use Color::Calc( 'OutputFormat' => 'tuple' ); is(join(',',color_get ('red')), '0255,0,0'); is(join(',',color ('red')), '0255,0,0'); is(join(',',color_mix ('red','blue')), '0128,0,0128'); is(join(',',color_blend_bw ('red')), '0255,0128,0128'); is(join(',',color_blend ('red')), '0128,0128,0128'); is(join(',',color_bw ('red')), '77,77,77'); is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); is(join(',',color_contrast ('red')), '0,0255,0255'); is(join(',',color_dark ('red')), '0128,0,0'); is(join(',',color_gray ('red')), '77,77,77'); is(join(',',color_grey ('red')), '77,77,77'); is(join(',',color_invert ('red')), '0,0255,0255'); is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/12_import_module_WWW.t b/t/12_import_module_WWW.t index 5c2c616..26776b7 100644 --- a/t/12_import_module_WWW.t +++ b/t/12_import_module_WWW.t @@ -1,19 +1,21 @@ +# $Id: 12_import_module_WWW.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 14; use Color::Calc::WWW; is(color_get ('F00'), 'red'); is(color_get ('green'), 'green'); is(color ('F00'), 'red'); is(color_mix ('red','blue'), 'purple'); is(color_blend_bw ('red'), '#ff8080'); is(color_blend ('red'), 'gray'); is(color_bw ('red'), '#4d4d4d'); is(color_contrast_bw ('red'), 'white'); is(color_contrast ('red'), 'aqua'); is(color_dark ('red'), 'maroon'); is(color_gray ('red'), '#4d4d4d'); is(color_grey ('red'), '#4d4d4d'); is(color_invert ('red'), 'aqua'); is(color_light ('red'), '#ff8080'); diff --git a/t/18_DEPRECATED_class-method_MODEval.t b/t/18_DEPRECATED_class-method_MODEval.t index 7956512..be7240c 100644 --- a/t/18_DEPRECATED_class-method_MODEval.t +++ b/t/18_DEPRECATED_class-method_MODEval.t @@ -1,67 +1,69 @@ +# $Id: 18_DEPRECATED_class-method_MODEval.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 48; use Color::Calc(); local $Color::Calc::MODE = 'hex'; is(Color::Calc::get ('red'), 'ff0000'); is(Color::Calc::mix ('red','blue'), '800080'); is(Color::Calc::blend_bw ('red'), 'ff8080'); is(Color::Calc::blend ('red'), '808080'); is(Color::Calc::bw ('red'), '4d4d4d'); is(Color::Calc::contrast_bw ('red'), 'ffffff'); is(Color::Calc::contrast ('red'), '00ffff'); is(Color::Calc::dark ('red'), '800000'); is(Color::Calc::gray ('red'), '4d4d4d'); is(Color::Calc::grey ('red'), '4d4d4d'); is(Color::Calc::invert ('red'), '00ffff'); is(Color::Calc::light ('red'), 'ff8080'); local $Color::Calc::MODE = 'html'; is(Color::Calc::get ('F00'), 'red'); is(Color::Calc::mix ('red','blue'), 'purple'); is(Color::Calc::blend_bw ('red'), '#ff8080'); is(Color::Calc::blend ('red'), 'gray'); is(Color::Calc::bw ('red'), '#4d4d4d'); is(Color::Calc::contrast_bw ('red'), 'white'); is(Color::Calc::contrast ('red'), 'aqua'); is(Color::Calc::dark ('red'), 'maroon'); is(Color::Calc::gray ('red'), '#4d4d4d'); is(Color::Calc::grey ('red'), '#4d4d4d'); is(Color::Calc::invert ('red'), 'aqua'); is(Color::Calc::light ('red'), '#ff8080'); local $Color::Calc::MODE = 'object'; SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc Color::Calc::get ('red')->as_RGBhex, 'ff0000'); is(lc Color::Calc::mix ('red','blue')->as_RGBhex, '800080'); is(lc Color::Calc::blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc Color::Calc::blend ('red')->as_RGBhex, '808080'); is(lc Color::Calc::bw ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc Color::Calc::contrast ('red')->as_RGBhex, '00ffff'); is(lc Color::Calc::dark ('red')->as_RGBhex, '800000'); is(lc Color::Calc::gray ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::grey ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::invert ('red')->as_RGBhex, '00ffff'); is(lc Color::Calc::light ('red')->as_RGBhex, 'ff8080'); } local $Color::Calc::MODE = 'tuple'; is(join(',',Color::Calc::get ('red')), '0255,0,0'); is(join(',',Color::Calc::mix ('red','blue')), '0128,0,0128'); is(join(',',Color::Calc::blend_bw ('red')), '0255,0128,0128'); is(join(',',Color::Calc::blend ('red')), '0128,0128,0128'); is(join(',',Color::Calc::bw ('red')), '77,77,77'); is(join(',',Color::Calc::contrast_bw ('red')), '0255,0255,0255'); is(join(',',Color::Calc::contrast ('red')), '0,0255,0255'); is(join(',',Color::Calc::dark ('red')), '0128,0,0'); is(join(',',Color::Calc::gray ('red')), '77,77,77'); is(join(',',Color::Calc::grey ('red')), '77,77,77'); is(join(',',Color::Calc::invert ('red')), '0,0255,0255'); is(join(',',Color::Calc::light ('red')), '0255,0128,0128'); diff --git a/t/18_DEPRECATED_class-method_suffix.t b/t/18_DEPRECATED_class-method_suffix.t index d4668d7..f8286b0 100644 --- a/t/18_DEPRECATED_class-method_suffix.t +++ b/t/18_DEPRECATED_class-method_suffix.t @@ -1,63 +1,65 @@ +# $Id: 18_DEPRECATED_class-method_suffix.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => (12*4); use Color::Calc(); is(Color::Calc::get_hex ('red'), 'ff0000'); is(Color::Calc::mix_hex ('red','blue'), '800080'); is(Color::Calc::blend_bw_hex ('red'), 'ff8080'); is(Color::Calc::blend_hex ('red'), '808080'); is(Color::Calc::bw_hex ('red'), '4d4d4d'); is(Color::Calc::contrast_bw_hex ('red'), 'ffffff'); is(Color::Calc::contrast_hex ('red'), '00ffff'); is(Color::Calc::dark_hex ('red'), '800000'); is(Color::Calc::gray_hex ('red'), '4d4d4d'); is(Color::Calc::grey_hex ('red'), '4d4d4d'); is(Color::Calc::invert_hex ('red'), '00ffff'); is(Color::Calc::light_hex ('red'), 'ff8080'); is(Color::Calc::get_html ('F00'), 'red'); is(Color::Calc::mix_html ('red','blue'), 'purple'); is(Color::Calc::blend_bw_html ('red'), '#ff8080'); is(Color::Calc::blend_html ('red'), 'gray'); is(Color::Calc::bw_html ('red'), '#4d4d4d'); is(Color::Calc::contrast_bw_html ('red'), 'white'); is(Color::Calc::contrast_html ('red'), 'aqua'); is(Color::Calc::dark_html ('red'), 'maroon'); is(Color::Calc::gray_html ('red'), '#4d4d4d'); is(Color::Calc::grey_html ('red'), '#4d4d4d'); is(Color::Calc::invert_html ('red'), 'aqua'); is(Color::Calc::light_html ('red'), '#ff8080'); SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc Color::Calc::get_object ('red')->as_RGBhex, 'ff0000'); is(lc Color::Calc::mix_object ('red','blue')->as_RGBhex, '800080'); is(lc Color::Calc::blend_bw_object ('red')->as_RGBhex, 'ff8080'); is(lc Color::Calc::blend_object ('red')->as_RGBhex, '808080'); is(lc Color::Calc::bw_object ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::contrast_bw_object ('red')->as_RGBhex, 'ffffff'); is(lc Color::Calc::contrast_object ('red')->as_RGBhex, '00ffff'); is(lc Color::Calc::dark_object ('red')->as_RGBhex, '800000'); is(lc Color::Calc::gray_object ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::grey_object ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::invert_object ('red')->as_RGBhex, '00ffff'); is(lc Color::Calc::light_object ('red')->as_RGBhex, 'ff8080'); } is(join(',',Color::Calc::get_tuple ('red')), '0255,0,0'); is(join(',',Color::Calc::mix_tuple ('red','blue')), '0128,0,0128'); is(join(',',Color::Calc::blend_bw_tuple ('red')), '0255,0128,0128'); is(join(',',Color::Calc::blend_tuple ('red')), '0128,0128,0128'); is(join(',',Color::Calc::bw_tuple ('red')), '77,77,77'); is(join(',',Color::Calc::contrast_bw_tuple ('red')), '0255,0255,0255'); is(join(',',Color::Calc::contrast_tuple ('red')), '0,0255,0255'); is(join(',',Color::Calc::dark_tuple ('red')), '0128,0,0'); is(join(',',Color::Calc::gray_tuple ('red')), '77,77,77'); is(join(',',Color::Calc::grey_tuple ('red')), '77,77,77'); is(join(',',Color::Calc::invert_tuple ('red')), '0,0255,0255'); is(join(',',Color::Calc::light_tuple ('red')), '0255,0128,0128'); diff --git a/t/18_DEPRECATED_import_MODEval.t b/t/18_DEPRECATED_import_MODEval.t index 9ae8bb7..db2e626 100644 --- a/t/18_DEPRECATED_import_MODEval.t +++ b/t/18_DEPRECATED_import_MODEval.t @@ -1,71 +1,73 @@ +# $Id: 18_DEPRECATED_import_MODEval.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 52; use Color::Calc; local $Color::Calc::MODE = 'hex'; is(color_get ('red'), 'ff0000'); is(color ('red'), 'ff0000'); is(color_mix ('red','blue'), '800080'); is(color_blend_bw ('red'), 'ff8080'); is(color_blend ('red'), '808080'); is(color_bw ('red'), '4d4d4d'); is(color_contrast_bw ('red'), 'ffffff'); is(color_contrast ('red'), '00ffff'); is(color_dark ('red'), '800000'); is(color_gray ('red'), '4d4d4d'); is(color_grey ('red'), '4d4d4d'); is(color_invert ('red'), '00ffff'); is(color_light ('red'), 'ff8080'); local $Color::Calc::MODE = 'html'; is(color_get ('F00'), 'red'); is(color ('F00'), 'red'); is(color_mix ('red','blue'), 'purple'); is(color_blend_bw ('red'), '#ff8080'); is(color_blend ('red'), 'gray'); is(color_bw ('red'), '#4d4d4d'); is(color_contrast_bw ('red'), 'white'); is(color_contrast ('red'), 'aqua'); is(color_dark ('red'), 'maroon'); is(color_gray ('red'), '#4d4d4d'); is(color_grey ('red'), '#4d4d4d'); is(color_invert ('red'), 'aqua'); is(color_light ('red'), '#ff8080'); local $Color::Calc::MODE = 'object'; SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc color_get ('red')->as_RGBhex, 'ff0000'); is(lc color ('red')->as_RGBhex, 'ff0000'); is(lc color_mix ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc color_blend ('red')->as_RGBhex, '808080'); is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast ('red')->as_RGBhex, '00ffff'); is(lc color_dark ('red')->as_RGBhex, '800000'); is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert ('red')->as_RGBhex, '00ffff'); is(lc color_light ('red')->as_RGBhex, 'ff8080'); } local $Color::Calc::MODE = 'tuple'; is(join(',',color_get ('red')), '0255,0,0'); is(join(',',color ('red')), '0255,0,0'); is(join(',',color_mix ('red','blue')), '0128,0,0128'); is(join(',',color_blend_bw ('red')), '0255,0128,0128'); is(join(',',color_blend ('red')), '0128,0128,0128'); is(join(',',color_bw ('red')), '77,77,77'); is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); is(join(',',color_contrast ('red')), '0,0255,0255'); is(join(',',color_dark ('red')), '0128,0,0'); is(join(',',color_gray ('red')), '77,77,77'); is(join(',',color_grey ('red')), '77,77,77'); is(join(',',color_invert ('red')), '0,0255,0255'); is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/18_DEPRECATED_import_suffix.t b/t/18_DEPRECATED_import_suffix.t index c71157e..4e5ff10 100644 --- a/t/18_DEPRECATED_import_suffix.t +++ b/t/18_DEPRECATED_import_suffix.t @@ -1,67 +1,69 @@ +# $Id: 18_DEPRECATED_import_suffix.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 52; use Color::Calc; is(color_get_hex ('red'), 'ff0000'); is(color_hex ('red'), 'ff0000'); is(color_mix_hex ('red','blue'), '800080'); is(color_blend_bw_hex ('red'), 'ff8080'); is(color_blend_hex ('red'), '808080'); is(color_bw_hex ('red'), '4d4d4d'); is(color_contrast_bw_hex ('red'), 'ffffff'); is(color_contrast_hex ('red'), '00ffff'); is(color_dark_hex ('red'), '800000'); is(color_gray_hex ('red'), '4d4d4d'); is(color_grey_hex ('red'), '4d4d4d'); is(color_invert_hex ('red'), '00ffff'); is(color_light_hex ('red'), 'ff8080'); is(color_get_html ('F00'), 'red'); is(color_html ('F00'), 'red'); is(color_mix_html ('red','blue'), 'purple'); is(color_blend_bw_html ('red'), '#ff8080'); is(color_blend_html ('red'), 'gray'); is(color_bw_html ('red'), '#4d4d4d'); is(color_contrast_bw_html ('red'), 'white'); is(color_contrast_html ('red'), 'aqua'); is(color_dark_html ('red'), 'maroon'); is(color_gray_html ('red'), '#4d4d4d'); is(color_grey_html ('red'), '#4d4d4d'); is(color_invert_html ('red'), 'aqua'); is(color_light_html ('red'), '#ff8080'); SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc color_get_object ('red')->as_RGBhex, 'ff0000'); is(lc color_object ('red')->as_RGBhex, 'ff0000'); is(lc color_mix_object ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw_object ('red')->as_RGBhex, 'ff8080'); is(lc color_blend_object ('red')->as_RGBhex, '808080'); is(lc color_bw_object ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw_object ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast_object ('red')->as_RGBhex, '00ffff'); is(lc color_dark_object ('red')->as_RGBhex, '800000'); is(lc color_gray_object ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey_object ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert_object ('red')->as_RGBhex, '00ffff'); is(lc color_light_object ('red')->as_RGBhex, 'ff8080'); } is(join(',',color_get_tuple ('red')), '0255,0,0'); is(join(',',color_tuple ('red')), '0255,0,0'); is(join(',',color_mix_tuple ('red','blue')), '0128,0,0128'); is(join(',',color_blend_bw_tuple ('red')), '0255,0128,0128'); is(join(',',color_blend_tuple ('red')), '0128,0128,0128'); is(join(',',color_bw_tuple ('red')), '77,77,77'); is(join(',',color_contrast_bw_tuple ('red')), '0255,0255,0255'); is(join(',',color_contrast_tuple ('red')), '0,0255,0255'); is(join(',',color_dark_tuple ('red')), '0128,0,0'); is(join(',',color_gray_tuple ('red')), '77,77,77'); is(join(',',color_grey_tuple ('red')), '77,77,77'); is(join(',',color_invert_tuple ('red')), '0,0255,0255'); is(join(',',color_light_tuple ('red')), '0255,0128,0128'); diff --git a/t/19_DEPRECATED_module_class-method.t b/t/19_DEPRECATED_module_class-method.t index caa1c77..6d77503 100644 --- a/t/19_DEPRECATED_module_class-method.t +++ b/t/19_DEPRECATED_module_class-method.t @@ -1,66 +1,68 @@ +# $Id: 19_DEPRECATED_module_class-method.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 48; use Color::Calc::hex(); use Color::Calc::html(); use Color::Calc::object(); use Color::Calc::tuple(); is(Color::Calc::hex::get ('red'), 'ff0000'); is(Color::Calc::hex::mix ('red','blue'), '800080'); is(Color::Calc::hex::blend_bw ('red'), 'ff8080'); is(Color::Calc::hex::blend ('red'), '808080'); is(Color::Calc::hex::bw ('red'), '4d4d4d'); is(Color::Calc::hex::contrast_bw ('red'), 'ffffff'); is(Color::Calc::hex::contrast ('red'), '00ffff'); is(Color::Calc::hex::dark ('red'), '800000'); is(Color::Calc::hex::gray ('red'), '4d4d4d'); is(Color::Calc::hex::grey ('red'), '4d4d4d'); is(Color::Calc::hex::invert ('red'), '00ffff'); is(Color::Calc::hex::light ('red'), 'ff8080'); is(Color::Calc::html::get ('F00'), 'red'); is(Color::Calc::html::mix ('red','blue'), 'purple'); is(Color::Calc::html::blend_bw ('red'), '#ff8080'); is(Color::Calc::html::blend ('red'), 'gray'); is(Color::Calc::html::bw ('red'), '#4d4d4d'); is(Color::Calc::html::contrast_bw ('red'), 'white'); is(Color::Calc::html::contrast ('red'), 'aqua'); is(Color::Calc::html::dark ('red'), 'maroon'); is(Color::Calc::html::gray ('red'), '#4d4d4d'); is(Color::Calc::html::grey ('red'), '#4d4d4d'); is(Color::Calc::html::invert ('red'), 'aqua'); is(Color::Calc::html::light ('red'), '#ff8080'); SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc Color::Calc::object::get ('red')->as_RGBhex, 'ff0000'); is(lc Color::Calc::object::mix ('red','blue')->as_RGBhex, '800080'); is(lc Color::Calc::object::blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc Color::Calc::object::blend ('red')->as_RGBhex, '808080'); is(lc Color::Calc::object::bw ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::object::contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc Color::Calc::object::contrast ('red')->as_RGBhex, '00ffff'); is(lc Color::Calc::object::dark ('red')->as_RGBhex, '800000'); is(lc Color::Calc::object::gray ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::object::grey ('red')->as_RGBhex, '4d4d4d'); is(lc Color::Calc::object::invert ('red')->as_RGBhex, '00ffff'); is(lc Color::Calc::object::light ('red')->as_RGBhex, 'ff8080'); } is(join(',',Color::Calc::tuple::get ('red')), '0255,0,0'); is(join(',',Color::Calc::tuple::mix ('red','blue')), '0128,0,0128'); is(join(',',Color::Calc::tuple::blend_bw ('red')), '0255,0128,0128'); is(join(',',Color::Calc::tuple::blend ('red')), '0128,0128,0128'); is(join(',',Color::Calc::tuple::bw ('red')), '77,77,77'); is(join(',',Color::Calc::tuple::contrast_bw ('red')), '0255,0255,0255'); is(join(',',Color::Calc::tuple::contrast ('red')), '0,0255,0255'); is(join(',',Color::Calc::tuple::dark ('red')), '0128,0,0'); is(join(',',Color::Calc::tuple::gray ('red')), '77,77,77'); is(join(',',Color::Calc::tuple::grey ('red')), '77,77,77'); is(join(',',Color::Calc::tuple::invert ('red')), '0,0255,0255'); is(join(',',Color::Calc::tuple::light ('red')), '0255,0128,0128'); diff --git a/t/19_DEPRECATED_module_import_hex.t b/t/19_DEPRECATED_module_import_hex.t index 115fb84..3102ee9 100644 --- a/t/19_DEPRECATED_module_import_hex.t +++ b/t/19_DEPRECATED_module_import_hex.t @@ -1,17 +1,19 @@ +# $Id: 19_DEPRECATED_module_import_hex.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 13; use Color::Calc::hex; is(color_get ('red'), 'ff0000'); is(color ('red'), 'ff0000'); is(color_mix ('red','blue'), '800080'); is(color_blend_bw ('red'), 'ff8080'); is(color_blend ('red'), '808080'); is(color_bw ('red'), '4d4d4d'); is(color_contrast_bw ('red'), 'ffffff'); is(color_contrast ('red'), '00ffff'); is(color_dark ('red'), '800000'); is(color_gray ('red'), '4d4d4d'); is(color_grey ('red'), '4d4d4d'); is(color_invert ('red'), '00ffff'); is(color_light ('red'), 'ff8080'); diff --git a/t/19_DEPRECATED_module_import_html.t b/t/19_DEPRECATED_module_import_html.t index ad085af..c4cbad6 100644 --- a/t/19_DEPRECATED_module_import_html.t +++ b/t/19_DEPRECATED_module_import_html.t @@ -1,19 +1,21 @@ +# $Id: 19_DEPRECATED_module_import_html.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 14; use Color::Calc::html; is(color_get ('F00'), 'red'); is(color_get ('green'), 'lime'); # !!! input uses X11 color names !!! is(color ('F00'), 'red'); is(color_mix ('red','blue'), 'purple'); is(color_blend_bw ('red'), '#ff8080'); is(color_blend ('red'), 'gray'); is(color_bw ('red'), '#4d4d4d'); is(color_contrast_bw ('red'), 'white'); is(color_contrast ('red'), 'aqua'); is(color_dark ('red'), 'maroon'); is(color_gray ('red'), '#4d4d4d'); is(color_grey ('red'), '#4d4d4d'); is(color_invert ('red'), 'aqua'); is(color_light ('red'), '#ff8080'); diff --git a/t/19_DEPRECATED_module_import_object.t b/t/19_DEPRECATED_module_import_object.t index d8a78c4..32c6074 100644 --- a/t/19_DEPRECATED_module_import_object.t +++ b/t/19_DEPRECATED_module_import_object.t @@ -1,22 +1,24 @@ +# $Id: 19_DEPRECATED_module_import_object.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 13; use Color::Calc::object; SKIP: { eval { require Graphics::ColorObject; }; skip "Graphics::ColorObject not installed", 12 if $@; is(lc color_get ('red')->as_RGBhex, 'ff0000'); is(lc color ('red')->as_RGBhex, 'ff0000'); is(lc color_mix ('red','blue')->as_RGBhex, '800080'); is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); is(lc color_blend ('red')->as_RGBhex, '808080'); is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); is(lc color_contrast ('red')->as_RGBhex, '00ffff'); is(lc color_dark ('red')->as_RGBhex, '800000'); is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); is(lc color_invert ('red')->as_RGBhex, '00ffff'); is(lc color_light ('red')->as_RGBhex, 'ff8080'); } diff --git a/t/19_DEPRECATED_module_import_tuple.t b/t/19_DEPRECATED_module_import_tuple.t index e373b0d..a39c173 100644 --- a/t/19_DEPRECATED_module_import_tuple.t +++ b/t/19_DEPRECATED_module_import_tuple.t @@ -1,17 +1,19 @@ +# $Id: 19_DEPRECATED_module_import_tuple.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 13; use Color::Calc::tuple; is(join(',',color_get ('red')), '0255,0,0'); is(join(',',color ('red')), '0255,0,0'); is(join(',',color_mix ('red','blue')), '0128,0,0128'); is(join(',',color_blend_bw ('red')), '0255,0128,0128'); is(join(',',color_blend ('red')), '0128,0128,0128'); is(join(',',color_bw ('red')), '77,77,77'); is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); is(join(',',color_contrast ('red')), '0,0255,0255'); is(join(',',color_dark ('red')), '0128,0,0'); is(join(',',color_gray ('red')), '77,77,77'); is(join(',',color_grey ('red')), '77,77,77'); is(join(',',color_invert ('red')), '0,0255,0255'); is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/20_input_formats_oo.t b/t/20_input_formats_oo.t index 12c61ed..1f82cce 100644 --- a/t/20_input_formats_oo.t +++ b/t/20_input_formats_oo.t @@ -1,12 +1,14 @@ +# $Id: 20_input_formats_oo.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 8; use Color::Calc(); my $cc = Color::Calc->new( 'OutputFormat' => 'hex' ); is($cc->mix ('F00','00F'), '800080'); is($cc->mix ('#F00','#00F'), '800080'); is($cc->mix ('FF0000','0000FF'), '800080'); is($cc->mix ('#FF0000','#0000FF'), '800080'); is($cc->mix ([255,0,0],[0,0,255]), '800080'); is($cc->mix ('0255',0,0,0,0,255), '800080'); is($cc->mix (['0255',0,0],0,0,255), '800080'); is($cc->mix ('0255',0,0,[0,0,255]), '800080'); diff --git a/t/21_input_formats_import.t b/t/21_input_formats_import.t index 7499f67..198f795 100644 --- a/t/21_input_formats_import.t +++ b/t/21_input_formats_import.t @@ -1,11 +1,13 @@ +# $Id: 21_input_formats_import.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 8; use Color::Calc( 'OutputFormat' => 'hex' ); is(color_mix ('F00','00F'), '800080'); is(color_mix ('#F00','#00F'), '800080'); is(color_mix ('FF0000','0000FF'), '800080'); is(color_mix ('#FF0000','#0000FF'), '800080'); is(color_mix ([255,0,0],[0,0,255]), '800080'); is(color_mix ('0255',0,0,0,0,255), '800080'); is(color_mix (['0255',0,0],0,0,255), '800080'); is(color_mix ('0255',0,0,[0,0,255]), '800080'); diff --git a/t/30_color_schemes_oo.t b/t/30_color_schemes_oo.t index 6a3d3a1..1eff60f 100644 --- a/t/30_color_schemes_oo.t +++ b/t/30_color_schemes_oo.t @@ -1,9 +1,11 @@ +# $Id: 30_color_schemes_oo.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 2; use Color::Calc(); my $cc = Color::Calc->new( 'OutputFormat' => 'html' ); is($cc->get ('green'), 'lime'); $cc = Color::Calc->new( 'ColorScheme' => 'HTML', 'OutputFormat' => 'html' ); is($cc->get ('green'), 'green'); diff --git a/t/31_color_schemes_import_HTML.t b/t/31_color_schemes_import_HTML.t index 1ed8946..8ea37fb 100644 --- a/t/31_color_schemes_import_HTML.t +++ b/t/31_color_schemes_import_HTML.t @@ -1,3 +1,5 @@ +# $Id: 31_color_schemes_import_HTML.t,v 1.2 2005/04/09 20:49:59 cfaerber Exp $ +# use Test::More tests => 1; use Color::Calc('ColorScheme' => 'HTML', 'OutputFormat' => 'html'); is(color_get ('green'), 'green'); diff --git a/t/31_color_schemes_import_X.t b/t/31_color_schemes_import_X.t index fa2b656..1ee0999 100644 --- a/t/31_color_schemes_import_X.t +++ b/t/31_color_schemes_import_X.t @@ -1,3 +1,5 @@ -use Test::More tests => 2; +# $Id: 31_color_schemes_import_X.t,v 1.3 2005/04/09 20:49:59 cfaerber Exp $ +# +use Test::More tests => 1; use Color::Calc('OutputFormat' => 'html' ); -is($cc->get ('green'), 'lime'); +is(color_get ('green'), 'lime');
cfaerber/Graphics-ColorNames-WWW
1730bfef4fc289e809126b4e6bd28e254549a584
Graphics-ColorNames-WWW-0.00_0001
diff --git a/Calc.pm b/Calc.pm index 11a0423..ad04b96 100644 --- a/Calc.pm +++ b/Calc.pm @@ -1,624 +1,613 @@ package Color::Calc; use strict; use Carp; use POSIX; use Params::Validate qw(:all); use Graphics::ColorNames qw( hex2tuple tuple2hex ); use Graphics::ColorNames::HTML; -our $VERSION = '0.29_0001'; +our $VERSION = '0.29_0003'; $VERSION = eval $VERSION; our $MODE = (); my %__HTMLColors = (); -our @__subs = qw( blend blend_bw bw contrast contrast_bw dark get grey invert light mix ); +our @__subs = qw( blend blend_bw bw contrast contrast_bw dark get grey gray invert light mix ); my %__formats = ( - 'tuple' => sub { return @_; }, + 'tuple' => sub { return __normtuple_out(@_); }, 'hex' => sub { return tuple2hex((@_)); }, 'html' => sub { my $col = lc(tuple2hex((@_))); return $__HTMLColors{$col} || '#'.$col; }, 'object' => sub { eval { require Graphics::ColorObject; }; return Graphics::ColorObject->new_RGB255( [(@_)] ); }, - 'pdf' => sub { eval { require PDF::API2::Color; }; return PDF::API2::Color->newRGB( map { $_ / 255 } ((@_))); }, +# 'pdf' => sub { eval { require PDF::API2::Color; }; return PDF::API2::Color->newRGB( map { $_ / 255 } ((@_))); }, ); my @__formats = keys %__formats; my $__formats_re = join('|', @__formats,'__MODEvar'); { my $table = Graphics::ColorNames::HTML::NamesRgbTable(); %__HTMLColors = map { ( sprintf('%06x', $$table{$_}) => $_ ) } grep { $_ ne 'fuscia' } keys %$table; }; our @EXPORT = ('color', map({"color_$_"} @__formats, map({my $s=$_; (map{$s.'_'.$_} @__formats)} @__subs), @__subs)); our @ISA = ('Exporter'); my %new_param = ( 'ColorScheme' => { type => SCALAR, optional => 1 }, 'OutputFormat' => { type => SCALAR, untaint => 1, regexp => qr($__formats_re), optional => 1 }, ); sub new { my $pkg = shift; validate(@_, \%new_param); my $self = {@_}; bless($self, $pkg); if(!ref($self->{'ColorScheme'})) { my %ColorNames; tie %ColorNames, 'Graphics::ColorNames', ($self->{'ColorScheme'} || 'X'); $self->{'ColorScheme'} = \%ColorNames; } $self->set_output_format($self->{'OutputFormat'} || 'tuple'); return $self; } -my $__default_object; +my $__default_object = undef; sub __get_default { $__default_object = __PACKAGE__->new('OutputFormat' => '__MODEvar') unless $__default_object; return $__default_object; } -my $__tuple_object; +my $__tuple_object = undef; sub __get_tuple { $__tuple_object = __PACKAGE__->new('OutputFormat' => 'tuple') unless $__tuple_object; return $__tuple_object; } my %import_param = ( %new_param, 'Prefix' => { type => SCALAR, optional => 1, regexp => qr/^[[:alpha:]\d]\w*$/ }, '__Prefix' => { type => SCALAR, optional => 1, regexp => qr/^[[:alpha:]\d]\w*$/ }, '__Suffix' => { type => SCALAR, optional => 1, regexp => qr/^\w+$/ }, ); my %import_param_names = map { ($_=>1) } keys %import_param; sub import { my $pkg = shift; if(!@_ || !exists $import_param_names{$_[0]}) { local $Exporter::ExportLevel; $Exporter::ExportLevel++; return Exporter::import($pkg, @_); } - __import(caller(0),@_); + return __import(scalar caller(0),@_) ? 1 : 0; } sub __import { my $pkg = shift; validate(@_, \%import_param); my %param = @_; my $std_prefix = (exists $param{'Prefix'}) ? $param{'Prefix'} : 'color'; delete $param{'Prefix'}; my $prefix = (exists $param{'__Prefix'}) ? $param{'__Prefix'} : $std_prefix ? $std_prefix.'_' : ''; delete $param{'__Prefix'}; my $suffix = (exists $param{'__Suffix'}) ? $param{'__Suffix'} : ''; delete $param{'__Suffix'}; my $obj = new(__PACKAGE__, %param); { no strict 'refs'; { $prefix = $pkg.'::'.$prefix; foreach my $sub (@__subs) { my $name = $prefix.$sub.$suffix; *$name = sub { $obj->$sub(@_); }; }; }; if($std_prefix) { my $name = $pkg.'::'.$std_prefix.$suffix; *$name = sub { $obj->get(@_); }; } } + return 1; } sub __normtuple_in { return map { ($_ < 0) ? 0 : (($_ > 255) ? 255 : int($_+.5)) } @_; } sub __normtuple_out { return map { (length $_) == 3 ? '0'.$_ : $_ } __normtuple_in(@_) } sub __normtuple { return __normtuple_out(__normtuple_in(@_)); } sub __is_col_val { return undef unless defined $_[0]; return undef if $_[0] eq ''; my ($n,$u) = POSIX::strtod($_[0]); return undef if $u != 0; return ($n <= 255) && ($n>= 0); } # Note: Color::Object was supported in versions before 0.2. This # is kept for compatibility, but no longer documented. # # Note: versions before 0.2 allowed calling some functions (those # with one parameter) with a list instead of an arrayref. This is # kept for compatibility, but no longer documented. sub __get { my ($self,$p,$q) = @_; if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 0 ) { $$p[0] = $$p[0]->[0]; } if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 2 ) { return __normtuple_in(@{shift @$p}); } elsif( UNIVERSAL::isa($$p[0],'Color::Object') || UNIVERSAL::isa($$p[0],'PDF::API2::Color')) { return (map { 255 * $_; } (shift(@{$p})->asRGB)); } elsif( UNIVERSAL::isa($$p[0],'Graphics::ColorObject')) { return (shift(@{$p})->as_RGB255()); } elsif( $#$p >= (2 + ($q||0)) && __is_col_val($$p[0]) && __is_col_val($$p[1]) && __is_col_val($$p[2])) { return (splice @$p, 0, 3); } elsif( $$p[0] =~ m/^#?([0-9A-F])([0-9A-F])([0-9A-F])$/i ) { shift @$p; return (map { hex($_) * 17 } ($1,$2,$3)); } elsif( $$p[0] =~ m/^#?([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])$/i ) { shift @$p; return (map { hex($_) } ($1,$2,$3)); } else { my $col = $self->{'ColorScheme'}->{$$p[0]}; if($col) { shift @$p; return hex2tuple($col); } else { carp("Invalid color name '$$p[0]'"); return undef; } } } sub set_output_format { validate_pos(@_, { isa => __PACKAGE__ }, { type => SCALAR, regexp => qr($__formats_re) }); my $self = shift; my $old = $self->{'OutputFormat'}; $self->{'OutputFormat'} = shift; $self->{'__put'} = $self->{'OutputFormat'} eq '__MODEvar' ? sub{ return $__formats{$MODE || 'tuple'}->(@_); } : $__formats{$self->{'OutputFormat'}}; return $old; } sub __put { my $self = shift; - return $self->{'__put'}->(@_); + return $self->{'__put'}->(__normtuple_in(@_)); } sub __get_self { - my $p = shift; - - if(UNIVERSAL::isa($p->[0], __PACKAGE__)) { - return shift @$p; + if(UNIVERSAL::isa($_[0]->[0], __PACKAGE__)) { + return shift @{$_[0]}; } else { return __get_default; } } sub get { my $self = __get_self(\@_); - return $self->__put(__normtuple_out($self->__get(\@_))); + return $self->__put($self->__get(\@_)); } - sub invert { my $self = __get_self(\@_); - return __normtuple_out(map { 255 - $_ } $self->__get(\@_)); + return $self->__put(map { 255 - $_ } $self->__get(\@_)); } sub bw { my $self = __get_self(\@_); my @c = $self->__get(\@_); my $g = $c[0]*.3 + $c[1]*.59 + $c[2]*.11; - return _put(__normtuple($g,$g,$g)); + return $self->__put(__normtuple($g,$g,$g)); } *grey = \&bw; *gray = \&bw; - sub mix { my $self = __get_self(\@_); my @c1 = ($self->__get(\@_,1)); my @c2 = ($self->__get(\@_)); my $alpha = shift(@_); $alpha = 0.5 unless defined $alpha; return $self->__put(__normtuple( ($c1[0] + ($c2[0]-$c1[0])*$alpha), ($c1[1] + ($c2[1]-$c1[1])*$alpha), ($c1[2] + ($c2[2]-$c1[2])*$alpha) )); } sub light { my $self = __get_self(\@_); return $self->__put(__get_tuple->mix([$self->__get(\@_)],[255,255,255],shift)); } - sub dark { my $self = __get_self(\@_); return $self->__put(__get_tuple->mix([$self->__get(\@_)],[0,0,0],shift)); } - sub contrast { my $self = __get_self(\@_); my @rgb = $self->__get(\@_); my $cut = (shift || .5) * 255; return $self->__put(map { $_ >= $cut ? 0 : '0255' } @rgb); } - sub contrast_bw { my $self = __get_self(\@_); - return $self->__put(__get_tuple->contrast([grey_tuple(@_)], shift)); + my @rgb = $self->__get(\@_); + return $self->__put(__get_tuple->contrast([__get_tuple->bw(@rgb)], shift)); } - sub blend { my $self = __get_self(\@_); my @c1 = $self->__get(\@_); - return __get_tuple->mix(\@c1,[contrast(\@c1)],shift); + return $self->mix(\@c1,[__get_tuple->contrast(\@c1)],shift); } - sub blend_bw { my $self = __get_self(\@_); my @c = $self->__get(\@_); - return __get_tuple->mix(\@c,[contrast_bw(\@c)],shift); + return $self->mix(\@c,[__get_tuple->contrast_bw(\@c)],shift); } - foreach my $format (@__formats) { __import(__PACKAGE__, 'Prefix' => 'color', '__Suffix' => "_$format", 'OutputFormat' => $format); __import(__PACKAGE__, 'Prefix' => '', '__Suffix' => "_$format", 'OutputFormat' => $format); } __import(__PACKAGE__, 'Prefix' => 'color', 'OutputFormat' => '__MODEvar'); -#- ----------------------------- -# - =head1 NAME Color::Calc - Simple calculations with RGB colors. =head1 SYNOPSIS use Color::Calc (); my $background = 'green'; print 'background: ',Color::Calc::color_html($background),';'; print 'border-top: solid 1px ',Color::Calc::light_html($background),';'; print 'border-bottom: solid 1px ',Color::Calc::dark_html($background),';'; print 'color: ',contrast_bw_html($background),';'; =head1 DESCRIPTION The C<Color::Calc> module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. =head2 Color Formats =head3 Input All of the methods accept colors as parameters in the following formats: =over =item * An arrayref pointing to an array with three elements in the range C<0>..C<255> corresponding to the red, green, and blue component. =item * A string containing a hexadecimal RGB value in the form C<#I<RRGGBB>>/C<#I<RGB>> or C<I<RGB>>/C<I<RRGGBB>>. =item * A color name accepted by C<Graphics::ColorNames>. =item * A C<PDF::API2::Color> reference. =item * A C<Graphics::ColorObject> reference. =item * A return value of any (public) C<Color::Calc> method even if the C<tuple> output format is selected. =back =head3 Output C<Color::Calc> can return colors in the following modes: =over =item tuple Returns a list of three values in the range 0..255. =item hex Returns a hexadecimal RGB value in the format RRGGBB. =item html Returns a value compatible with W3C's HTML and CSS specifications, i.e. I<#RRGGBB> or one of the sixteen color names. =item pdf Returns a C<PDF::API2::Color> reference. The module C<PDF::API2::Color> must be installed. =item object Returns a C<Graphics::ColorObject> reference. The module C<Graphics::ColorObject> must be installed. =item __MODEvar (DEPRECATED) Uses the value of C<$Color::Calc::MODE> to select the output format. You should use C<local> when setting this variable. =back =head2 Object-Orientated interface use Color::Calc(); my $cc = new Color::Calc( 'ColorScheme' => 'X', OutputFormat => 'HTML' ); print $cc->invert( 'white' ); =over =item new $cc = new Color::Calc( 'ColorScheme' => $name, 'OutputFormat' => $format ); Creates a new C<Color::Calc> object which can be used to access the color calculation methods. =over =item ColorScheme One of the color schemes accepted by C<Graphics::ColorNames>. Used to translate color names on input. See the documentation of C<Graphics::ColorNames> for possible values. Default: C<X> (please note that this is incompatible with HTML color names). =item OutputFormat Sets the output format of the object's methods. See above for possible values. Default: C<__MODEvar> =back =item $cc->get($color) Returns the color as-is (but in the selected output format). This function can be used for color format conversion/normalisation. =item $cc->invert($color) Returns the inverse of $color. =item $cc->bw($color) =item $cc->grey($color) Converts $color to greyscale. =item $cc->mix($color1, $color2 [, $alpha]) Returns a color that is the mixture of $color1 and $color2. The optional $alpha parameter can be a value between 0.0 (use $color1 only) and 1.0 (use $color2 only), the default is 0.5. =item $cc->color_light($color [, $alpha]) Returns a lighter version of $color, i.e. returns $cc->mix($color,[255,255,255],$alpha); The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use 'white' only), the default is 0.5. =item $cc->dark($color [, $alpha]) Returns a darker version of $color, i.e. returns $cc->mix($color,[0,0,0],$alpha); The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use 'black' only), the default is 0.5. =item $cc->contrast($color [, $cut]) Returns a color that has the highest possible contrast to the input color. This is done by setting the red, green, and blue values to 0 if the corresponding value in the input is above C<($cut * 255)> and to 255 otherwise. The default for C<$cut> is .5, representing a cutoff between 127 and 128. =item $cc->contrast_bw($color [, $cut]) Returns black or white, whichever has the higher contrast to $color. This is done by setting returning black if the grey value of $color is above C<($cut * 255)> and white otherwise. The default for C<$cut> is .5, representing a cutoff between 127 and 128. =item $cc->blend($color [, $alpha]) Returns a color that blends into the background, i.e. it returns $cc->mix($color,$cc->contrast($color),$alpha). The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use C<contrast($color)> only), the default is 0.5. The idea is that C<$color> is the foreground color, so C<contrast($color)> is similar to the background color. Mixing them returns a color somewhere between them. You might want to use mix($color, $background, $alpha) instead if you know the real background color. =item $cc->blend_bw($color [, $alpha]) Returns a mix of $color and black or white, whichever has the higher contrast to $color. The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use black/white only), the default is 0.5. =back =head2 Procedural Interface With Importing You can also choose to import customised funtions into your namespace: use Color::Calc( 'ColorScheme' => 'X', 'OutputFormat' => 'HTML', 'Prefix' => 'cc' ); print cc_invert( 'white' ); # prints 'black' On import, you can specify the following parameters: =over =item ColorScheme See above. =item OutputFormat See above. =item Prefix Adds the prefix and an underscore to the front of the method names. You can call the methods as I<prefix>_I<method_name>. You can also call I<prefix> instead of I<prefix>C<_get>. Default: C<color> =back Please note that specifying an empty list of parameters means "don't import anything". Omit the list to import the default functions. You can also C<use> the following modules to import the function with pre-defined parameters. =over =item C<use Color::Calc::WWW> -Same as C<use Color::Calc( ColorScheme =&gt; 'Netscape', OutputFormat => 'html' )> +Same as C<use Color::Calc( ColorScheme =&gt; 'WWW', OutputFormat => 'html' )> =item C<use Color::Calc::html> (DEPRECATED) Same as C<use Color::Calc( OutputFormat =&gt; 'html')> Please note that this only selects HTML as the C<OutputFormat> but not as the C<ColorScheme> (which defaults to 'X'), which is probably not what you expect. Use C<Color::Calc::WWW> instead. =item C<use Color::Calc::hex> Same as C<use Color::Calc( OutputFormat =&gt; 'hex')> =item C<use Color::Calc::object> Same as C<use Color::Calc( OutputFormat =&gt; 'object')> =item C<use Color::Calc::pdf> Same as C<use Color::Calc( OutputFormat =&gt; 'pdf')> =item C<use Color::Calc::tuple> Same as C<use Color::Calc( OutputFormat =&gt; 'tuple')> =back =head2 Procedural Interface Without Importing (DEPRECATED) You can also access the methods as class methods of the various packages with and without the C<color> prefix: use Color::Calc::WWW(); print Color::Calc::WWW::color('FFF'); # prints 'white' print Color::Calc::WWW::color_invert('FFF'); # prints 'black' print Color::Calc::html::invert('FFF'); # prints 'black' For the main module C<Color::Calc>, you can also add a suffix C<_I<output_format>> to select the output format: use Color::Calc(); print Color::Calc::color_html('FFF'); # prints 'white' print Color::Calc::color_invert_html('FFF'); # prints 'black' print Color::Calc::invert_hex('FFF'); # prints '000000' =head1 SEE ALSO L<Graphics::ColorNames> (required); L<Color::Object> (optional) =head1 AUTHOR Claus A. Färber <perl@faerber.muc.de> =head1 COPYRIGHT Copyright © 2004, 2005 Claus A. Färber All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; diff --git a/Changes b/Changes index 9ac82f5..9952e0f 100644 --- a/Changes +++ b/Changes @@ -1,28 +1,34 @@ Revision history for Perl extension Color::Calc. +0.29_0002 Sat Mar 26 16:20:00 2005 + - Color::Calc::WWW now uses Graphics::ColorNames::WWW + - Color::Calc::WWW was missing from distribution + - removed 'pdf' output format as PDF::API2::Color is no longer + - complete test suite + 0.29_0001 Fri Mar 25 12:00:00 2005 - added object-orientated interface - added procedural interface with customisation on import - added Color::Calc::WWW - color scheme is now selectable 0.20 Mon Mar 28 00:00:00 2004 - added Color::Calc::<xxx> modules to select return type - added $Color::Calc::MODE to select return type - return value of xxx_tuple can be used as parameter - <xxx>_html returns color names instead of #RRGGBB if possible - support for Graphics::ColorObject (input/output) - support for PDF::API2::Color (input/output) - fixed import list 0.12 Thu Mar 18 00:00:00 2004 - added xxx_html - should work with perl 5.005 now 0.10 Sun May 04 00:00:00 2003 - added tests - added more functions - some documentation corrections 0.02 Sat Apr 26 00:00:00 2003 - first public release diff --git a/MANIFEST b/MANIFEST index fc68d74..2cf8630 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,22 +1,33 @@ -README -Changes -MANIFEST -Makefile.PL Calc.pm +Calc/WWW.pm Calc/hex.pm Calc/html.pm -Calc/tuple.pm Calc/object.pm -Calc/pdf.pm -t/30_mix.t -t/20_hex.t -t/21_html.t -t/90_Graphics-ColorObject.t -t/13_param_2.t -t/14_param_3.t -t/10_suffixes.t +Calc/tuple.pm +Changes +Makefile +MANIFEST +META.yml +README t/00_basic.t -t/91_PDF-API2-Color.t -t/12_param_1.t -t/11_modes.t -META.yml Module meta-data (added by MakeMaker) +t/10_object-orientated.t +t/11_import_hex.t +t/11_import_html.t +t/11_import_MODEval.t +t/11_import_object.t +t/11_import_tuple.t +t/12_import_module_WWW.t +t/18_DEPRECATED_class-method_MODEval.t +t/18_DEPRECATED_class-method_suffix.t +t/18_DEPRECATED_import_MODEval.t +t/18_DEPRECATED_import_suffix.t +t/19_DEPRECATED_module_class-method.t +t/19_DEPRECATED_module_import_hex.t +t/19_DEPRECATED_module_import_html.t +t/19_DEPRECATED_module_import_object.t +t/19_DEPRECATED_module_import_tuple.t +t/20_input_formats_oo.t +t/21_input_formats_import.t +t/30_color_schemes_oo.t +t/31_color_schemes_import_HTML.t +t/31_color_schemes_import_X.t diff --git a/META.yml b/META.yml index a7ae86b..9e6fef7 100644 --- a/META.yml +++ b/META.yml @@ -1,12 +1,13 @@ # http://module-build.sourceforge.net/META-spec.html #XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX# name: Color-Calc -version: 0.29_0001 +version: 0.29_0002 version_from: Calc.pm installdirs: site requires: Graphics::ColorNames: 0.32 + Graphics::ColorNames::SVG: 0 Params::Validate: 0.75 distribution_type: module generated_by: ExtUtils::MakeMaker version 6.17
cfaerber/Graphics-ColorNames-WWW
f50c5d72832c51fec6a889326d57b00f19c5f761
Color-Calc-0.29_0001 (p2)
diff --git a/Calc/WWW.pm b/Calc/WWW.pm new file mode 100644 index 0000000..94a79ee --- /dev/null +++ b/Calc/WWW.pm @@ -0,0 +1,12 @@ +package Color::Calc::WWW; + +use strict; +use Carp; + +use Exporter; +use Color::Calc('OutputFormat' => 'html', 'ColorScheme' => 'WWW'); + +our @ISA = qw(Exporter); +our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); + +1; diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c54a577 --- /dev/null +++ b/Makefile @@ -0,0 +1,732 @@ +# This Makefile is for the Color::Calc extension to perl. +# +# It was generated automatically by MakeMaker version +# 6.17 (Revision: 1.133) from the contents of +# Makefile.PL. Don't edit this file, edit Makefile.PL instead. +# +# ANY CHANGES MADE HERE WILL BE LOST! +# +# MakeMaker ARGV: () +# +# MakeMaker Parameters: + +# ABSTRACT_FROM => q[Calc.pm] +# AUTHOR => q[Claus Färber <perl@faerber.muc.de>] +# NAME => q[Color::Calc] +# PREREQ_PM => { Params::Validate=>q[0.75], Graphics::ColorNames::SVG=>q[0], Graphics::ColorNames=>q[0.32] } +# VERSION_FROM => q[Calc.pm] + +# --- MakeMaker post_initialize section: + + +# --- MakeMaker const_config section: + +# These definitions are from config.sh (via /usr/lib/perl/5.8/Config.pm) + +# They may have been overridden via Makefile.PL or on the command line +AR = ar +CC = cc +CCCDLFLAGS = -fPIC +CCDLFLAGS = -Wl,-E +DLEXT = so +DLSRC = dl_dlopen.xs +LD = cc +LDDLFLAGS = -shared -L/usr/local/lib +LDFLAGS = -L/usr/local/lib +LIBC = /lib/libc-2.3.2.so +LIB_EXT = .a +OBJ_EXT = .o +OSNAME = linux +OSVERS = 2.4.27-ti1211 +RANLIB = : +SITELIBEXP = /usr/local/share/perl/5.8.4 +SITEARCHEXP = /usr/local/lib/perl/5.8.4 +SO = so +EXE_EXT = +FULL_AR = /usr/bin/ar +VENDORARCHEXP = /usr/lib/perl5 +VENDORLIBEXP = /usr/share/perl5 + + +# --- MakeMaker constants section: +AR_STATIC_ARGS = cr +DIRFILESEP = / +NAME = Color::Calc +NAME_SYM = Color_Calc +VERSION = 0.29_0002 +VERSION_MACRO = VERSION +VERSION_SYM = 0_29_0002 +DEFINE_VERSION = -D$(VERSION_MACRO)=\"$(VERSION)\" +XS_VERSION = 0.29_0002 +XS_VERSION_MACRO = XS_VERSION +XS_DEFINE_VERSION = -D$(XS_VERSION_MACRO)=\"$(XS_VERSION)\" +INST_ARCHLIB = blib/arch +INST_SCRIPT = blib/script +INST_BIN = blib/bin +INST_LIB = blib/lib +INST_MAN1DIR = blib/man1 +INST_MAN3DIR = blib/man3 +MAN1EXT = 1p +MAN3EXT = 3pm +INSTALLDIRS = site +DESTDIR = +PREFIX = /usr +PERLPREFIX = $(PREFIX) +SITEPREFIX = $(PREFIX)/local +VENDORPREFIX = $(PREFIX) +INSTALLPRIVLIB = $(PERLPREFIX)/share/perl/5.8 +DESTINSTALLPRIVLIB = $(DESTDIR)$(INSTALLPRIVLIB) +INSTALLSITELIB = $(SITEPREFIX)/share/perl/5.8.4 +DESTINSTALLSITELIB = $(DESTDIR)$(INSTALLSITELIB) +INSTALLVENDORLIB = $(VENDORPREFIX)/share/perl5 +DESTINSTALLVENDORLIB = $(DESTDIR)$(INSTALLVENDORLIB) +INSTALLARCHLIB = $(PERLPREFIX)/lib/perl/5.8 +DESTINSTALLARCHLIB = $(DESTDIR)$(INSTALLARCHLIB) +INSTALLSITEARCH = $(SITEPREFIX)/lib/perl/5.8.4 +DESTINSTALLSITEARCH = $(DESTDIR)$(INSTALLSITEARCH) +INSTALLVENDORARCH = $(VENDORPREFIX)/lib/perl5 +DESTINSTALLVENDORARCH = $(DESTDIR)$(INSTALLVENDORARCH) +INSTALLBIN = $(PERLPREFIX)/bin +DESTINSTALLBIN = $(DESTDIR)$(INSTALLBIN) +INSTALLSITEBIN = $(SITEPREFIX)/bin +DESTINSTALLSITEBIN = $(DESTDIR)$(INSTALLSITEBIN) +INSTALLVENDORBIN = $(VENDORPREFIX)/bin +DESTINSTALLVENDORBIN = $(DESTDIR)$(INSTALLVENDORBIN) +INSTALLSCRIPT = $(PERLPREFIX)/bin +DESTINSTALLSCRIPT = $(DESTDIR)$(INSTALLSCRIPT) +INSTALLMAN1DIR = $(PERLPREFIX)/share/man/man1 +DESTINSTALLMAN1DIR = $(DESTDIR)$(INSTALLMAN1DIR) +INSTALLSITEMAN1DIR = $(SITEPREFIX)/man/man1 +DESTINSTALLSITEMAN1DIR = $(DESTDIR)$(INSTALLSITEMAN1DIR) +INSTALLVENDORMAN1DIR = $(VENDORPREFIX)/share/man/man1 +DESTINSTALLVENDORMAN1DIR = $(DESTDIR)$(INSTALLVENDORMAN1DIR) +INSTALLMAN3DIR = $(PERLPREFIX)/share/man/man3 +DESTINSTALLMAN3DIR = $(DESTDIR)$(INSTALLMAN3DIR) +INSTALLSITEMAN3DIR = $(SITEPREFIX)/man/man3 +DESTINSTALLSITEMAN3DIR = $(DESTDIR)$(INSTALLSITEMAN3DIR) +INSTALLVENDORMAN3DIR = $(VENDORPREFIX)/share/man/man3 +DESTINSTALLVENDORMAN3DIR = $(DESTDIR)$(INSTALLVENDORMAN3DIR) +PERL_LIB = /usr/share/perl/5.8 +PERL_ARCHLIB = /usr/lib/perl/5.8 +LIBPERL_A = libperl.a +FIRST_MAKEFILE = Makefile +MAKEFILE_OLD = $(FIRST_MAKEFILE).old +MAKE_APERL_FILE = $(FIRST_MAKEFILE).aperl +PERLMAINCC = $(CC) +PERL_INC = /usr/lib/perl/5.8/CORE +PERL = /usr/bin/perl +FULLPERL = /usr/bin/perl +ABSPERL = $(PERL) +PERLRUN = $(PERL) +FULLPERLRUN = $(FULLPERL) +ABSPERLRUN = $(ABSPERL) +PERLRUNINST = $(PERLRUN) "-I$(INST_ARCHLIB)" "-I$(INST_LIB)" +FULLPERLRUNINST = $(FULLPERLRUN) "-I$(INST_ARCHLIB)" "-I$(INST_LIB)" +ABSPERLRUNINST = $(ABSPERLRUN) "-I$(INST_ARCHLIB)" "-I$(INST_LIB)" +PERL_CORE = 0 +PERM_RW = 644 +PERM_RWX = 755 + +MAKEMAKER = /usr/share/perl/5.8/ExtUtils/MakeMaker.pm +MM_VERSION = 6.17 +MM_REVISION = 1.133 + +# FULLEXT = Pathname for extension directory (eg Foo/Bar/Oracle). +# BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT. (eg Oracle) +# PARENT_NAME = NAME without BASEEXT and no trailing :: (eg Foo::Bar) +# DLBASE = Basename part of dynamic library. May be just equal BASEEXT. +FULLEXT = Color/Calc +BASEEXT = Calc +PARENT_NAME = Color +DLBASE = $(BASEEXT) +VERSION_FROM = Calc.pm +OBJECT = +LDFROM = $(OBJECT) +LINKTYPE = dynamic + +# Handy lists of source code files: +XS_FILES = +C_FILES = +O_FILES = +H_FILES = +MAN1PODS = +MAN3PODS = Calc.pm + +# Where is the Config information that we are using/depend on +CONFIGDEP = $(PERL_ARCHLIB)$(DIRFILESEP)Config.pm $(PERL_INC)$(DIRFILESEP)config.h + +# Where to build things +INST_LIBDIR = $(INST_LIB)/Color +INST_ARCHLIBDIR = $(INST_ARCHLIB)/Color + +INST_AUTODIR = $(INST_LIB)/auto/$(FULLEXT) +INST_ARCHAUTODIR = $(INST_ARCHLIB)/auto/$(FULLEXT) + +INST_STATIC = +INST_DYNAMIC = +INST_BOOT = + +# Extra linker info +EXPORT_LIST = +PERL_ARCHIVE = +PERL_ARCHIVE_AFTER = + + +TO_INST_PM = Calc.pm \ + Calc/WWW.pm \ + Calc/hex.pm \ + Calc/html.pm \ + Calc/object.pm \ + Calc/tuple.pm + +PM_TO_BLIB = Calc/WWW.pm \ + $(INST_LIB)/Color/Calc/WWW.pm \ + Calc/tuple.pm \ + $(INST_LIB)/Color/Calc/tuple.pm \ + Calc/hex.pm \ + $(INST_LIB)/Color/Calc/hex.pm \ + Calc/object.pm \ + $(INST_LIB)/Color/Calc/object.pm \ + Calc/html.pm \ + $(INST_LIB)/Color/Calc/html.pm \ + Calc.pm \ + $(INST_LIB)/Color/Calc.pm + + +# --- MakeMaker platform_constants section: +MM_Unix_VERSION = 1.42 +PERL_MALLOC_DEF = -DPERL_EXTMALLOC_DEF -Dmalloc=Perl_malloc -Dfree=Perl_mfree -Drealloc=Perl_realloc -Dcalloc=Perl_calloc + + +# --- MakeMaker tool_autosplit section: +# Usage: $(AUTOSPLITFILE) FileToSplit AutoDirToSplitInto +AUTOSPLITFILE = $(PERLRUN) -e 'use AutoSplit; autosplit($$ARGV[0], $$ARGV[1], 0, 1, 1)' + + + +# --- MakeMaker tool_xsubpp section: + + +# --- MakeMaker tools_other section: +SHELL = /bin/sh +CHMOD = chmod +CP = cp +MV = mv +NOOP = $(SHELL) -c true +NOECHO = @ +RM_F = rm -f +RM_RF = rm -rf +TEST_F = test -f +TOUCH = touch +UMASK_NULL = umask 0 +DEV_NULL = > /dev/null 2>&1 +MKPATH = $(PERLRUN) "-MExtUtils::Command" -e mkpath +EQUALIZE_TIMESTAMP = $(PERLRUN) "-MExtUtils::Command" -e eqtime +ECHO = echo +ECHO_N = echo -n +UNINST = 0 +VERBINST = 0 +MOD_INSTALL = $(PERLRUN) -MExtUtils::Install -e 'install({@ARGV}, '\''$(VERBINST)'\'', 0, '\''$(UNINST)'\'');' +DOC_INSTALL = $(PERLRUN) "-MExtUtils::Command::MM" -e perllocal_install +UNINSTALL = $(PERLRUN) "-MExtUtils::Command::MM" -e uninstall +WARN_IF_OLD_PACKLIST = $(PERLRUN) "-MExtUtils::Command::MM" -e warn_if_old_packlist + + +# --- MakeMaker makemakerdflt section: +makemakerdflt: all + $(NOECHO) $(NOOP) + + +# --- MakeMaker dist section: +TAR = tar +TARFLAGS = cvf +ZIP = zip +ZIPFLAGS = -r +COMPRESS = gzip --best +SUFFIX = .gz +SHAR = shar +PREOP = $(NOECHO) $(NOOP) +POSTOP = $(NOECHO) $(NOOP) +TO_UNIX = $(NOECHO) $(NOOP) +CI = ci -u +RCS_LABEL = rcs -Nv$(VERSION_SYM): -q +DIST_CP = best +DIST_DEFAULT = tardist +DISTNAME = Color-Calc +DISTVNAME = Color-Calc-0.29_0002 + + +# --- MakeMaker macro section: + + +# --- MakeMaker depend section: + + +# --- MakeMaker cflags section: + + +# --- MakeMaker const_loadlibs section: + + +# --- MakeMaker const_cccmd section: + + +# --- MakeMaker post_constants section: + + +# --- MakeMaker pasthru section: + +PASTHRU = LIB="$(LIB)"\ + LIBPERL_A="$(LIBPERL_A)"\ + LINKTYPE="$(LINKTYPE)"\ + PREFIX="$(PREFIX)"\ + OPTIMIZE="$(OPTIMIZE)"\ + PASTHRU_DEFINE="$(PASTHRU_DEFINE)"\ + PASTHRU_INC="$(PASTHRU_INC)" + + +# --- MakeMaker special_targets section: +.SUFFIXES: .xs .c .C .cpp .i .s .cxx .cc $(OBJ_EXT) + +.PHONY: all config static dynamic test linkext manifest + + + +# --- MakeMaker c_o section: + + +# --- MakeMaker xs_c section: + + +# --- MakeMaker xs_o section: + + +# --- MakeMaker top_targets section: +all :: pure_all manifypods + $(NOECHO) $(NOOP) + + +pure_all :: config pm_to_blib subdirs linkext + $(NOECHO) $(NOOP) + +subdirs :: $(MYEXTLIB) + $(NOECHO) $(NOOP) + +config :: $(FIRST_MAKEFILE) $(INST_LIBDIR)$(DIRFILESEP).exists + $(NOECHO) $(NOOP) + +config :: $(INST_ARCHAUTODIR)$(DIRFILESEP).exists + $(NOECHO) $(NOOP) + +config :: $(INST_AUTODIR)$(DIRFILESEP).exists + $(NOECHO) $(NOOP) + +$(INST_AUTODIR)/.exists :: /usr/lib/perl/5.8/CORE/perl.h + $(NOECHO) $(MKPATH) $(INST_AUTODIR) + $(NOECHO) $(EQUALIZE_TIMESTAMP) /usr/lib/perl/5.8/CORE/perl.h $(INST_AUTODIR)/.exists + + -$(NOECHO) $(CHMOD) $(PERM_RWX) $(INST_AUTODIR) + +$(INST_LIBDIR)/.exists :: /usr/lib/perl/5.8/CORE/perl.h + $(NOECHO) $(MKPATH) $(INST_LIBDIR) + $(NOECHO) $(EQUALIZE_TIMESTAMP) /usr/lib/perl/5.8/CORE/perl.h $(INST_LIBDIR)/.exists + + -$(NOECHO) $(CHMOD) $(PERM_RWX) $(INST_LIBDIR) + +$(INST_ARCHAUTODIR)/.exists :: /usr/lib/perl/5.8/CORE/perl.h + $(NOECHO) $(MKPATH) $(INST_ARCHAUTODIR) + $(NOECHO) $(EQUALIZE_TIMESTAMP) /usr/lib/perl/5.8/CORE/perl.h $(INST_ARCHAUTODIR)/.exists + + -$(NOECHO) $(CHMOD) $(PERM_RWX) $(INST_ARCHAUTODIR) + +config :: $(INST_MAN3DIR)$(DIRFILESEP).exists + $(NOECHO) $(NOOP) + + +$(INST_MAN3DIR)/.exists :: /usr/lib/perl/5.8/CORE/perl.h + $(NOECHO) $(MKPATH) $(INST_MAN3DIR) + $(NOECHO) $(EQUALIZE_TIMESTAMP) /usr/lib/perl/5.8/CORE/perl.h $(INST_MAN3DIR)/.exists + + -$(NOECHO) $(CHMOD) $(PERM_RWX) $(INST_MAN3DIR) + +help: + perldoc ExtUtils::MakeMaker + + +# --- MakeMaker linkext section: + +linkext :: $(LINKTYPE) + $(NOECHO) $(NOOP) + + +# --- MakeMaker dlsyms section: + + +# --- MakeMaker dynamic section: + +dynamic :: $(FIRST_MAKEFILE) $(INST_DYNAMIC) $(INST_BOOT) + $(NOECHO) $(NOOP) + + +# --- MakeMaker dynamic_bs section: + +BOOTSTRAP = + + +# --- MakeMaker dynamic_lib section: + + +# --- MakeMaker static section: + +## $(INST_PM) has been moved to the all: target. +## It remains here for awhile to allow for old usage: "make static" +static :: $(FIRST_MAKEFILE) $(INST_STATIC) + $(NOECHO) $(NOOP) + + +# --- MakeMaker static_lib section: + + +# --- MakeMaker manifypods section: + +POD2MAN_EXE = $(PERLRUN) "-MExtUtils::Command::MM" -e pod2man "--" +POD2MAN = $(POD2MAN_EXE) + + +manifypods : pure_all \ + Calc.pm \ + Calc.pm + $(NOECHO) $(POD2MAN) --section=$(MAN3EXT) --perm_rw=$(PERM_RW)\ + Calc.pm $(INST_MAN3DIR)/Color::Calc.$(MAN3EXT) + + + + +# --- MakeMaker processPL section: + + +# --- MakeMaker installbin section: + + +# --- MakeMaker subdirs section: + +# none + +# --- MakeMaker clean_subdirs section: +clean_subdirs : + $(NOECHO) $(NOOP) + + +# --- MakeMaker clean section: + +# Delete temporary files but do not touch installed files. We don't delete +# the Makefile here so a later make realclean still has a makefile to use. + +clean :: clean_subdirs + -$(RM_RF) ./blib $(MAKE_APERL_FILE) $(INST_ARCHAUTODIR)/extralibs.all $(INST_ARCHAUTODIR)/extralibs.ld perlmain.c tmon.out mon.out so_locations pm_to_blib *$(OBJ_EXT) *$(LIB_EXT) perl.exe perl perl$(EXE_EXT) $(BOOTSTRAP) $(BASEEXT).bso $(BASEEXT).def lib$(BASEEXT).def $(BASEEXT).exp $(BASEEXT).x core core.*perl.*.? *perl.core core.[0-9] core.[0-9][0-9] core.[0-9][0-9][0-9] core.[0-9][0-9][0-9][0-9] core.[0-9][0-9][0-9][0-9][0-9] + -$(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD) $(DEV_NULL) + + +# --- MakeMaker realclean_subdirs section: +realclean_subdirs : + $(NOECHO) $(NOOP) + + +# --- MakeMaker realclean section: + +# Delete temporary files (via clean) and also delete installed files +realclean purge :: clean realclean_subdirs + $(RM_RF) $(INST_AUTODIR) $(INST_ARCHAUTODIR) + $(RM_RF) $(DISTVNAME) + $(RM_F) $(INST_LIB)/Color/Calc/html.pm $(INST_LIB)/Color/Calc/tuple.pm $(INST_LIB)/Color/Calc/hex.pm $(MAKEFILE_OLD) $(INST_LIB)/Color/Calc.pm $(INST_LIB)/Color/Calc/WWW.pm $(INST_LIB)/Color/Calc/object.pm + $(RM_F) $(FIRST_MAKEFILE) + + +# --- MakeMaker metafile section: +metafile : + $(NOECHO) $(ECHO) '# http://module-build.sourceforge.net/META-spec.html' > META.yml + $(NOECHO) $(ECHO) '#XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX#' >> META.yml + $(NOECHO) $(ECHO) 'name: Color-Calc' >> META.yml + $(NOECHO) $(ECHO) 'version: 0.29_0002' >> META.yml + $(NOECHO) $(ECHO) 'version_from: Calc.pm' >> META.yml + $(NOECHO) $(ECHO) 'installdirs: site' >> META.yml + $(NOECHO) $(ECHO) 'requires:' >> META.yml + $(NOECHO) $(ECHO) ' Graphics::ColorNames: 0.32' >> META.yml + $(NOECHO) $(ECHO) ' Graphics::ColorNames::SVG: 0' >> META.yml + $(NOECHO) $(ECHO) ' Params::Validate: 0.75' >> META.yml + $(NOECHO) $(ECHO) '' >> META.yml + $(NOECHO) $(ECHO) 'distribution_type: module' >> META.yml + $(NOECHO) $(ECHO) 'generated_by: ExtUtils::MakeMaker version 6.17' >> META.yml + + +# --- MakeMaker metafile_addtomanifest section: +metafile_addtomanifest: + $(NOECHO) $(PERLRUN) -MExtUtils::Manifest=maniadd -e 'eval { maniadd({q{META.yml} => q{Module meta-data (added by MakeMaker)}}) } ' \ + -e ' or print "Could not add META.yml to MANIFEST: $${'\''@'\''}\n"' + + +# --- MakeMaker dist_basics section: +distclean :: realclean distcheck + $(NOECHO) $(NOOP) + +distcheck : + $(PERLRUN) "-MExtUtils::Manifest=fullcheck" -e fullcheck + +skipcheck : + $(PERLRUN) "-MExtUtils::Manifest=skipcheck" -e skipcheck + +manifest : + $(PERLRUN) "-MExtUtils::Manifest=mkmanifest" -e mkmanifest + +veryclean : realclean + $(RM_F) *~ *.orig */*~ */*.orig + + + +# --- MakeMaker dist_core section: + +dist : $(DIST_DEFAULT) $(FIRST_MAKEFILE) + $(NOECHO) $(PERLRUN) -l -e 'print '\''Warning: Makefile possibly out of date with $(VERSION_FROM)'\''' \ + -e ' if -e '\''$(VERSION_FROM)'\'' and -M '\''$(VERSION_FROM)'\'' < -M '\''$(FIRST_MAKEFILE)'\'';' + +tardist : $(DISTVNAME).tar$(SUFFIX) + $(NOECHO) $(NOOP) + +uutardist : $(DISTVNAME).tar$(SUFFIX) + uuencode $(DISTVNAME).tar$(SUFFIX) $(DISTVNAME).tar$(SUFFIX) > $(DISTVNAME).tar$(SUFFIX)_uu + +$(DISTVNAME).tar$(SUFFIX) : distdir + $(PREOP) + $(TO_UNIX) + $(TAR) $(TARFLAGS) $(DISTVNAME).tar $(DISTVNAME) + $(RM_RF) $(DISTVNAME) + $(COMPRESS) $(DISTVNAME).tar + $(POSTOP) + +zipdist : $(DISTVNAME).zip + $(NOECHO) $(NOOP) + +$(DISTVNAME).zip : distdir + $(PREOP) + $(ZIP) $(ZIPFLAGS) $(DISTVNAME).zip $(DISTVNAME) + $(RM_RF) $(DISTVNAME) + $(POSTOP) + +shdist : distdir + $(PREOP) + $(SHAR) $(DISTVNAME) > $(DISTVNAME).shar + $(RM_RF) $(DISTVNAME) + $(POSTOP) + + +# --- MakeMaker distdir section: +distdir : metafile metafile_addtomanifest + $(RM_RF) $(DISTVNAME) + $(PERLRUN) "-MExtUtils::Manifest=manicopy,maniread" \ + -e "manicopy(maniread(),'$(DISTVNAME)', '$(DIST_CP)');" + + + +# --- MakeMaker dist_test section: + +disttest : distdir + cd $(DISTVNAME) && $(ABSPERLRUN) Makefile.PL + cd $(DISTVNAME) && $(MAKE) $(PASTHRU) + cd $(DISTVNAME) && $(MAKE) test $(PASTHRU) + + +# --- MakeMaker dist_ci section: + +ci : + $(PERLRUN) "-MExtUtils::Manifest=maniread" \ + -e "@all = keys %{ maniread() };" \ + -e "print(qq{Executing $(CI) @all\n}); system(qq{$(CI) @all});" \ + -e "print(qq{Executing $(RCS_LABEL) ...\n}); system(qq{$(RCS_LABEL) @all});" + + +# --- MakeMaker install section: + +install :: all pure_install doc_install + +install_perl :: all pure_perl_install doc_perl_install + +install_site :: all pure_site_install doc_site_install + +install_vendor :: all pure_vendor_install doc_vendor_install + +pure_install :: pure_$(INSTALLDIRS)_install + +doc_install :: doc_$(INSTALLDIRS)_install + +pure__install : pure_site_install + $(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site + +doc__install : doc_site_install + $(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site + +pure_perl_install :: + $(NOECHO) umask 022; $(MOD_INSTALL) \ + $(INST_LIB) $(DESTINSTALLPRIVLIB) \ + $(INST_ARCHLIB) $(DESTINSTALLARCHLIB) \ + $(INST_BIN) $(DESTINSTALLBIN) \ + $(INST_SCRIPT) $(DESTINSTALLSCRIPT) \ + $(INST_MAN1DIR) $(DESTINSTALLMAN1DIR) \ + $(INST_MAN3DIR) $(DESTINSTALLMAN3DIR) + $(NOECHO) $(WARN_IF_OLD_PACKLIST) \ + $(SITEARCHEXP)/auto/$(FULLEXT) + + +pure_site_install :: + $(NOECHO) umask 02; $(MOD_INSTALL) \ + read $(SITEARCHEXP)/auto/$(FULLEXT)/.packlist \ + write $(DESTINSTALLSITEARCH)/auto/$(FULLEXT)/.packlist \ + $(INST_LIB) $(DESTINSTALLSITELIB) \ + $(INST_ARCHLIB) $(DESTINSTALLSITEARCH) \ + $(INST_BIN) $(DESTINSTALLSITEBIN) \ + $(INST_SCRIPT) $(DESTINSTALLSCRIPT) \ + $(INST_MAN1DIR) $(DESTINSTALLSITEMAN1DIR) \ + $(INST_MAN3DIR) $(DESTINSTALLSITEMAN3DIR) + $(NOECHO) $(WARN_IF_OLD_PACKLIST) \ + $(PERL_ARCHLIB)/auto/$(FULLEXT) + +pure_vendor_install :: + $(NOECHO) umask 022; $(MOD_INSTALL) \ + $(INST_LIB) $(DESTINSTALLVENDORLIB) \ + $(INST_ARCHLIB) $(DESTINSTALLVENDORARCH) \ + $(INST_BIN) $(DESTINSTALLVENDORBIN) \ + $(INST_SCRIPT) $(DESTINSTALLSCRIPT) \ + $(INST_MAN1DIR) $(DESTINSTALLVENDORMAN1DIR) \ + $(INST_MAN3DIR) $(DESTINSTALLVENDORMAN3DIR) + +doc_perl_install :: + +doc_site_install :: + $(NOECHO) $(ECHO) Appending installation info to $(DESTINSTALLSITEARCH)/perllocal.pod + -$(NOECHO) umask 02; $(MKPATH) $(DESTINSTALLSITEARCH) + -$(NOECHO) umask 02; $(DOC_INSTALL) \ + "Module" "$(NAME)" \ + "installed into" "$(INSTALLSITELIB)" \ + LINKTYPE "$(LINKTYPE)" \ + VERSION "$(VERSION)" \ + EXE_FILES "$(EXE_FILES)" \ + >> $(DESTINSTALLSITEARCH)/perllocal.pod + +doc_vendor_install :: + + +uninstall :: uninstall_from_$(INSTALLDIRS)dirs + +uninstall_from_perldirs :: + $(NOECHO) $(UNINSTALL) $(PERL_ARCHLIB)/auto/$(FULLEXT)/.packlist + +uninstall_from_sitedirs :: + $(NOECHO) $(UNINSTALL) $(SITEARCHEXP)/auto/$(FULLEXT)/.packlist + +uninstall_from_vendordirs :: + $(NOECHO) $(UNINSTALL) $(VENDORARCHEXP)/auto/$(FULLEXT)/.packlist + + +# --- MakeMaker force section: +# Phony target to force checking subdirectories. +FORCE: + $(NOECHO) $(NOOP) + + +# --- MakeMaker perldepend section: + + +# --- MakeMaker makefile section: + +# We take a very conservative approach here, but it's worth it. +# We move Makefile to Makefile.old here to avoid gnu make looping. +$(FIRST_MAKEFILE) : Makefile.PL $(CONFIGDEP) + $(NOECHO) $(ECHO) "Makefile out-of-date with respect to $?" + $(NOECHO) $(ECHO) "Cleaning current config before rebuilding Makefile..." + $(NOECHO) $(RM_F) $(MAKEFILE_OLD) + $(NOECHO) $(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD) + -$(MAKE) -f $(MAKEFILE_OLD) clean $(DEV_NULL) || $(NOOP) + $(PERLRUN) Makefile.PL + $(NOECHO) $(ECHO) "==> Your Makefile has been rebuilt. <==" + $(NOECHO) $(ECHO) "==> Please rerun the make command. <==" + false + + + +# --- MakeMaker staticmake section: + +# --- MakeMaker makeaperl section --- +MAP_TARGET = perl +FULLPERL = /usr/bin/perl + +$(MAP_TARGET) :: static $(MAKE_APERL_FILE) + $(MAKE) -f $(MAKE_APERL_FILE) $@ + +$(MAKE_APERL_FILE) : $(FIRST_MAKEFILE) + $(NOECHO) $(ECHO) Writing \"$(MAKE_APERL_FILE)\" for this $(MAP_TARGET) + $(NOECHO) $(PERLRUNINST) \ + Makefile.PL DIR= \ + MAKEFILE=$(MAKE_APERL_FILE) LINKTYPE=static \ + MAKEAPERL=1 NORECURS=1 CCCDLFLAGS= + + +# --- MakeMaker test section: + +TEST_VERBOSE=0 +TEST_TYPE=test_$(LINKTYPE) +TEST_FILE = test.pl +TEST_FILES = t/*.t +TESTDB_SW = -d + +testdb :: testdb_$(LINKTYPE) + +test :: $(TEST_TYPE) + +test_dynamic :: pure_all + PERL_DL_NONLAZY=1 $(FULLPERLRUN) "-MExtUtils::Command::MM" "-e" "test_harness($(TEST_VERBOSE), '$(INST_LIB)', '$(INST_ARCHLIB)')" $(TEST_FILES) + +testdb_dynamic :: pure_all + PERL_DL_NONLAZY=1 $(FULLPERLRUN) $(TESTDB_SW) "-I$(INST_LIB)" "-I$(INST_ARCHLIB)" $(TEST_FILE) + +test_ : test_dynamic + +test_static :: test_dynamic +testdb_static :: testdb_dynamic + + +# --- MakeMaker ppd section: +# Creates a PPD (Perl Package Description) for a binary distribution. +ppd: + $(NOECHO) $(ECHO) '<SOFTPKG NAME="$(DISTNAME)" VERSION="0,29_0002,0,0">' > $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <TITLE>$(DISTNAME)</TITLE>' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <ABSTRACT>Simple calculations with RGB colors.</ABSTRACT>' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <AUTHOR>Claus Färber &lt;perl@faerber.muc.de&gt;</AUTHOR>' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <IMPLEMENTATION>' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <DEPENDENCY NAME="Graphics-ColorNames" VERSION="0,32,0,0" />' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <DEPENDENCY NAME="Graphics-ColorNames-SVG" VERSION="0,0,0,0" />' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <DEPENDENCY NAME="Params-Validate" VERSION="0,75,0,0" />' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <OS NAME="$(OSNAME)" />' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <ARCHITECTURE NAME="i386-linux-thread-multi" />' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' <CODEBASE HREF="" />' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) ' </IMPLEMENTATION>' >> $(DISTNAME).ppd + $(NOECHO) $(ECHO) '</SOFTPKG>' >> $(DISTNAME).ppd + + +# --- MakeMaker pm_to_blib section: + +pm_to_blib: $(TO_INST_PM) + $(NOECHO) $(PERLRUN) -MExtUtils::Install -e 'pm_to_blib({@ARGV}, '\''$(INST_LIB)/auto'\'', '\''$(PM_FILTER)'\'')'\ + Calc/WWW.pm $(INST_LIB)/Color/Calc/WWW.pm \ + Calc/tuple.pm $(INST_LIB)/Color/Calc/tuple.pm \ + Calc/hex.pm $(INST_LIB)/Color/Calc/hex.pm \ + Calc/object.pm $(INST_LIB)/Color/Calc/object.pm \ + Calc/html.pm $(INST_LIB)/Color/Calc/html.pm \ + Calc.pm $(INST_LIB)/Color/Calc.pm + $(NOECHO) $(TOUCH) $@ + +# --- MakeMaker selfdocument section: + + +# --- MakeMaker postamble section: + + +# End. diff --git a/t/10_object-orientated.t b/t/10_object-orientated.t new file mode 100644 index 0000000..c817d65 --- /dev/null +++ b/t/10_object-orientated.t @@ -0,0 +1,67 @@ +use Test::More tests => 48; +use Color::Calc(); + +my $cc = Color::Calc->new( 'OutputFormat' => 'hex' ); +is($cc->get ('red'), 'ff0000'); +is($cc->mix ('red','blue'), '800080'); + +is($cc->blend_bw ('red'), 'ff8080'); +is($cc->blend ('red'), '808080'); +is($cc->bw ('red'), '4d4d4d'); +is($cc->contrast_bw ('red'), 'ffffff'); +is($cc->contrast ('red'), '00ffff'); +is($cc->dark ('red'), '800000'); +is($cc->gray ('red'), '4d4d4d'); +is($cc->grey ('red'), '4d4d4d'); +is($cc->invert ('red'), '00ffff'); +is($cc->light ('red'), 'ff8080'); + +$cc = Color::Calc->new( 'OutputFormat' => 'html' ); +is($cc->get ('F00'), 'red'); +is($cc->mix ('red','blue'), 'purple'); + +is($cc->blend_bw ('red'), '#ff8080'); +is($cc->blend ('red'), 'gray'); +is($cc->bw ('red'), '#4d4d4d'); +is($cc->contrast_bw ('red'), 'white'); +is($cc->contrast ('red'), 'aqua'); +is($cc->dark ('red'), 'maroon'); +is($cc->gray ('red'), '#4d4d4d'); +is($cc->grey ('red'), '#4d4d4d'); +is($cc->invert ('red'), 'aqua'); +is($cc->light ('red'), '#ff8080'); + +$cc = Color::Calc->new( 'OutputFormat' => 'object' ); +SKIP: { +eval { require Graphics::ColorObject; }; +skip "Graphics::ColorObject not installed", 12 if $@; + +is(lc $cc->get ('red')->as_RGBhex, 'ff0000'); +is(lc $cc->mix ('red','blue')->as_RGBhex, '800080'); + +is(lc $cc->blend_bw ('red')->as_RGBhex, 'ff8080'); +is(lc $cc->blend ('red')->as_RGBhex, '808080'); +is(lc $cc->bw ('red')->as_RGBhex, '4d4d4d'); +is(lc $cc->contrast_bw ('red')->as_RGBhex, 'ffffff'); +is(lc $cc->contrast ('red')->as_RGBhex, '00ffff'); +is(lc $cc->dark ('red')->as_RGBhex, '800000'); +is(lc $cc->gray ('red')->as_RGBhex, '4d4d4d'); +is(lc $cc->grey ('red')->as_RGBhex, '4d4d4d'); +is(lc $cc->invert ('red')->as_RGBhex, '00ffff'); +is(lc $cc->light ('red')->as_RGBhex, 'ff8080'); +} + +$cc = Color::Calc->new( 'OutputFormat' => 'tuple' ); +is(join(',',$cc->get ('red')), '0255,0,0'); +is(join(',',$cc->mix ('red','blue')), '0128,0,0128'); + +is(join(',',$cc->blend_bw ('red')), '0255,0128,0128'); +is(join(',',$cc->blend ('red')), '0128,0128,0128'); +is(join(',',$cc->bw ('red')), '77,77,77'); +is(join(',',$cc->contrast_bw ('red')), '0255,0255,0255'); +is(join(',',$cc->contrast ('red')), '0,0255,0255'); +is(join(',',$cc->dark ('red')), '0128,0,0'); +is(join(',',$cc->gray ('red')), '77,77,77'); +is(join(',',$cc->grey ('red')), '77,77,77'); +is(join(',',$cc->invert ('red')), '0,0255,0255'); +is(join(',',$cc->light ('red')), '0255,0128,0128'); diff --git a/t/11_import_MODEval.t b/t/11_import_MODEval.t new file mode 100644 index 0000000..9ae8bb7 --- /dev/null +++ b/t/11_import_MODEval.t @@ -0,0 +1,71 @@ +use Test::More tests => 52; +use Color::Calc; + +local $Color::Calc::MODE = 'hex'; +is(color_get ('red'), 'ff0000'); +is(color ('red'), 'ff0000'); +is(color_mix ('red','blue'), '800080'); + +is(color_blend_bw ('red'), 'ff8080'); +is(color_blend ('red'), '808080'); +is(color_bw ('red'), '4d4d4d'); +is(color_contrast_bw ('red'), 'ffffff'); +is(color_contrast ('red'), '00ffff'); +is(color_dark ('red'), '800000'); +is(color_gray ('red'), '4d4d4d'); +is(color_grey ('red'), '4d4d4d'); +is(color_invert ('red'), '00ffff'); +is(color_light ('red'), 'ff8080'); + +local $Color::Calc::MODE = 'html'; +is(color_get ('F00'), 'red'); +is(color ('F00'), 'red'); +is(color_mix ('red','blue'), 'purple'); + +is(color_blend_bw ('red'), '#ff8080'); +is(color_blend ('red'), 'gray'); +is(color_bw ('red'), '#4d4d4d'); +is(color_contrast_bw ('red'), 'white'); +is(color_contrast ('red'), 'aqua'); +is(color_dark ('red'), 'maroon'); +is(color_gray ('red'), '#4d4d4d'); +is(color_grey ('red'), '#4d4d4d'); +is(color_invert ('red'), 'aqua'); +is(color_light ('red'), '#ff8080'); + +local $Color::Calc::MODE = 'object'; +SKIP: { +eval { require Graphics::ColorObject; }; +skip "Graphics::ColorObject not installed", 12 if $@; + +is(lc color_get ('red')->as_RGBhex, 'ff0000'); +is(lc color ('red')->as_RGBhex, 'ff0000'); +is(lc color_mix ('red','blue')->as_RGBhex, '800080'); + +is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); +is(lc color_blend ('red')->as_RGBhex, '808080'); +is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); +is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); +is(lc color_contrast ('red')->as_RGBhex, '00ffff'); +is(lc color_dark ('red')->as_RGBhex, '800000'); +is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); +is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); +is(lc color_invert ('red')->as_RGBhex, '00ffff'); +is(lc color_light ('red')->as_RGBhex, 'ff8080'); +} + +local $Color::Calc::MODE = 'tuple'; +is(join(',',color_get ('red')), '0255,0,0'); +is(join(',',color ('red')), '0255,0,0'); +is(join(',',color_mix ('red','blue')), '0128,0,0128'); + +is(join(',',color_blend_bw ('red')), '0255,0128,0128'); +is(join(',',color_blend ('red')), '0128,0128,0128'); +is(join(',',color_bw ('red')), '77,77,77'); +is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); +is(join(',',color_contrast ('red')), '0,0255,0255'); +is(join(',',color_dark ('red')), '0128,0,0'); +is(join(',',color_gray ('red')), '77,77,77'); +is(join(',',color_grey ('red')), '77,77,77'); +is(join(',',color_invert ('red')), '0,0255,0255'); +is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/11_import_hex.t b/t/11_import_hex.t new file mode 100644 index 0000000..9f208c1 --- /dev/null +++ b/t/11_import_hex.t @@ -0,0 +1,17 @@ +use Test::More tests => 13; +use Color::Calc( 'OutputFormat' => 'hex' ); + +is(color_get ('red'), 'ff0000'); +is(color ('red'), 'ff0000'); +is(color_mix ('red','blue'), '800080'); + +is(color_blend_bw ('red'), 'ff8080'); +is(color_blend ('red'), '808080'); +is(color_bw ('red'), '4d4d4d'); +is(color_contrast_bw ('red'), 'ffffff'); +is(color_contrast ('red'), '00ffff'); +is(color_dark ('red'), '800000'); +is(color_gray ('red'), '4d4d4d'); +is(color_grey ('red'), '4d4d4d'); +is(color_invert ('red'), '00ffff'); +is(color_light ('red'), 'ff8080'); diff --git a/t/11_import_html.t b/t/11_import_html.t new file mode 100644 index 0000000..791d2bd --- /dev/null +++ b/t/11_import_html.t @@ -0,0 +1,17 @@ +use Test::More tests => 13; +use Color::Calc( 'OutputFormat' => 'html' ); + +is(color_get ('F00'), 'red'); +is(color ('F00'), 'red'); +is(color_mix ('red','blue'), 'purple'); + +is(color_blend_bw ('red'), '#ff8080'); +is(color_blend ('red'), 'gray'); +is(color_bw ('red'), '#4d4d4d'); +is(color_contrast_bw ('red'), 'white'); +is(color_contrast ('red'), 'aqua'); +is(color_dark ('red'), 'maroon'); +is(color_gray ('red'), '#4d4d4d'); +is(color_grey ('red'), '#4d4d4d'); +is(color_invert ('red'), 'aqua'); +is(color_light ('red'), '#ff8080'); diff --git a/t/11_import_object.t b/t/11_import_object.t new file mode 100644 index 0000000..6453a23 --- /dev/null +++ b/t/11_import_object.t @@ -0,0 +1,22 @@ +use Test::More tests => 13; +use Color::Calc( 'OutputFormat' => 'object' ); + +SKIP: { +eval { require Graphics::ColorObject; }; +skip "Graphics::ColorObject not installed", 12 if $@; + +is(lc color_get ('red')->as_RGBhex, 'ff0000'); +is(lc color ('red')->as_RGBhex, 'ff0000'); +is(lc color_mix ('red','blue')->as_RGBhex, '800080'); + +is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); +is(lc color_blend ('red')->as_RGBhex, '808080'); +is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); +is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); +is(lc color_contrast ('red')->as_RGBhex, '00ffff'); +is(lc color_dark ('red')->as_RGBhex, '800000'); +is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); +is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); +is(lc color_invert ('red')->as_RGBhex, '00ffff'); +is(lc color_light ('red')->as_RGBhex, 'ff8080'); +} diff --git a/t/11_import_tuple.t b/t/11_import_tuple.t new file mode 100644 index 0000000..c23ba39 --- /dev/null +++ b/t/11_import_tuple.t @@ -0,0 +1,17 @@ +use Test::More tests => 13; +use Color::Calc( 'OutputFormat' => 'tuple' ); + +is(join(',',color_get ('red')), '0255,0,0'); +is(join(',',color ('red')), '0255,0,0'); +is(join(',',color_mix ('red','blue')), '0128,0,0128'); + +is(join(',',color_blend_bw ('red')), '0255,0128,0128'); +is(join(',',color_blend ('red')), '0128,0128,0128'); +is(join(',',color_bw ('red')), '77,77,77'); +is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); +is(join(',',color_contrast ('red')), '0,0255,0255'); +is(join(',',color_dark ('red')), '0128,0,0'); +is(join(',',color_gray ('red')), '77,77,77'); +is(join(',',color_grey ('red')), '77,77,77'); +is(join(',',color_invert ('red')), '0,0255,0255'); +is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/12_import_module_WWW.t b/t/12_import_module_WWW.t new file mode 100644 index 0000000..5c2c616 --- /dev/null +++ b/t/12_import_module_WWW.t @@ -0,0 +1,19 @@ +use Test::More tests => 14; +use Color::Calc::WWW; + +is(color_get ('F00'), 'red'); +is(color_get ('green'), 'green'); + +is(color ('F00'), 'red'); +is(color_mix ('red','blue'), 'purple'); + +is(color_blend_bw ('red'), '#ff8080'); +is(color_blend ('red'), 'gray'); +is(color_bw ('red'), '#4d4d4d'); +is(color_contrast_bw ('red'), 'white'); +is(color_contrast ('red'), 'aqua'); +is(color_dark ('red'), 'maroon'); +is(color_gray ('red'), '#4d4d4d'); +is(color_grey ('red'), '#4d4d4d'); +is(color_invert ('red'), 'aqua'); +is(color_light ('red'), '#ff8080'); diff --git a/t/18_DEPRECATED_class-method_MODEval.t b/t/18_DEPRECATED_class-method_MODEval.t new file mode 100644 index 0000000..7956512 --- /dev/null +++ b/t/18_DEPRECATED_class-method_MODEval.t @@ -0,0 +1,67 @@ +use Test::More tests => 48; +use Color::Calc(); + +local $Color::Calc::MODE = 'hex'; +is(Color::Calc::get ('red'), 'ff0000'); +is(Color::Calc::mix ('red','blue'), '800080'); + +is(Color::Calc::blend_bw ('red'), 'ff8080'); +is(Color::Calc::blend ('red'), '808080'); +is(Color::Calc::bw ('red'), '4d4d4d'); +is(Color::Calc::contrast_bw ('red'), 'ffffff'); +is(Color::Calc::contrast ('red'), '00ffff'); +is(Color::Calc::dark ('red'), '800000'); +is(Color::Calc::gray ('red'), '4d4d4d'); +is(Color::Calc::grey ('red'), '4d4d4d'); +is(Color::Calc::invert ('red'), '00ffff'); +is(Color::Calc::light ('red'), 'ff8080'); + +local $Color::Calc::MODE = 'html'; +is(Color::Calc::get ('F00'), 'red'); +is(Color::Calc::mix ('red','blue'), 'purple'); + +is(Color::Calc::blend_bw ('red'), '#ff8080'); +is(Color::Calc::blend ('red'), 'gray'); +is(Color::Calc::bw ('red'), '#4d4d4d'); +is(Color::Calc::contrast_bw ('red'), 'white'); +is(Color::Calc::contrast ('red'), 'aqua'); +is(Color::Calc::dark ('red'), 'maroon'); +is(Color::Calc::gray ('red'), '#4d4d4d'); +is(Color::Calc::grey ('red'), '#4d4d4d'); +is(Color::Calc::invert ('red'), 'aqua'); +is(Color::Calc::light ('red'), '#ff8080'); + +local $Color::Calc::MODE = 'object'; +SKIP: { +eval { require Graphics::ColorObject; }; +skip "Graphics::ColorObject not installed", 12 if $@; + +is(lc Color::Calc::get ('red')->as_RGBhex, 'ff0000'); +is(lc Color::Calc::mix ('red','blue')->as_RGBhex, '800080'); + +is(lc Color::Calc::blend_bw ('red')->as_RGBhex, 'ff8080'); +is(lc Color::Calc::blend ('red')->as_RGBhex, '808080'); +is(lc Color::Calc::bw ('red')->as_RGBhex, '4d4d4d'); +is(lc Color::Calc::contrast_bw ('red')->as_RGBhex, 'ffffff'); +is(lc Color::Calc::contrast ('red')->as_RGBhex, '00ffff'); +is(lc Color::Calc::dark ('red')->as_RGBhex, '800000'); +is(lc Color::Calc::gray ('red')->as_RGBhex, '4d4d4d'); +is(lc Color::Calc::grey ('red')->as_RGBhex, '4d4d4d'); +is(lc Color::Calc::invert ('red')->as_RGBhex, '00ffff'); +is(lc Color::Calc::light ('red')->as_RGBhex, 'ff8080'); +} + +local $Color::Calc::MODE = 'tuple'; +is(join(',',Color::Calc::get ('red')), '0255,0,0'); +is(join(',',Color::Calc::mix ('red','blue')), '0128,0,0128'); + +is(join(',',Color::Calc::blend_bw ('red')), '0255,0128,0128'); +is(join(',',Color::Calc::blend ('red')), '0128,0128,0128'); +is(join(',',Color::Calc::bw ('red')), '77,77,77'); +is(join(',',Color::Calc::contrast_bw ('red')), '0255,0255,0255'); +is(join(',',Color::Calc::contrast ('red')), '0,0255,0255'); +is(join(',',Color::Calc::dark ('red')), '0128,0,0'); +is(join(',',Color::Calc::gray ('red')), '77,77,77'); +is(join(',',Color::Calc::grey ('red')), '77,77,77'); +is(join(',',Color::Calc::invert ('red')), '0,0255,0255'); +is(join(',',Color::Calc::light ('red')), '0255,0128,0128'); diff --git a/t/18_DEPRECATED_class-method_suffix.t b/t/18_DEPRECATED_class-method_suffix.t new file mode 100644 index 0000000..d4668d7 --- /dev/null +++ b/t/18_DEPRECATED_class-method_suffix.t @@ -0,0 +1,63 @@ +use Test::More tests => (12*4); +use Color::Calc(); + +is(Color::Calc::get_hex ('red'), 'ff0000'); +is(Color::Calc::mix_hex ('red','blue'), '800080'); + +is(Color::Calc::blend_bw_hex ('red'), 'ff8080'); +is(Color::Calc::blend_hex ('red'), '808080'); +is(Color::Calc::bw_hex ('red'), '4d4d4d'); +is(Color::Calc::contrast_bw_hex ('red'), 'ffffff'); +is(Color::Calc::contrast_hex ('red'), '00ffff'); +is(Color::Calc::dark_hex ('red'), '800000'); +is(Color::Calc::gray_hex ('red'), '4d4d4d'); +is(Color::Calc::grey_hex ('red'), '4d4d4d'); +is(Color::Calc::invert_hex ('red'), '00ffff'); +is(Color::Calc::light_hex ('red'), 'ff8080'); + +is(Color::Calc::get_html ('F00'), 'red'); +is(Color::Calc::mix_html ('red','blue'), 'purple'); + +is(Color::Calc::blend_bw_html ('red'), '#ff8080'); +is(Color::Calc::blend_html ('red'), 'gray'); +is(Color::Calc::bw_html ('red'), '#4d4d4d'); +is(Color::Calc::contrast_bw_html ('red'), 'white'); +is(Color::Calc::contrast_html ('red'), 'aqua'); +is(Color::Calc::dark_html ('red'), 'maroon'); +is(Color::Calc::gray_html ('red'), '#4d4d4d'); +is(Color::Calc::grey_html ('red'), '#4d4d4d'); +is(Color::Calc::invert_html ('red'), 'aqua'); +is(Color::Calc::light_html ('red'), '#ff8080'); + +SKIP: { +eval { require Graphics::ColorObject; }; +skip "Graphics::ColorObject not installed", 12 if $@; + +is(lc Color::Calc::get_object ('red')->as_RGBhex, 'ff0000'); +is(lc Color::Calc::mix_object ('red','blue')->as_RGBhex, '800080'); + +is(lc Color::Calc::blend_bw_object ('red')->as_RGBhex, 'ff8080'); +is(lc Color::Calc::blend_object ('red')->as_RGBhex, '808080'); +is(lc Color::Calc::bw_object ('red')->as_RGBhex, '4d4d4d'); +is(lc Color::Calc::contrast_bw_object ('red')->as_RGBhex, 'ffffff'); +is(lc Color::Calc::contrast_object ('red')->as_RGBhex, '00ffff'); +is(lc Color::Calc::dark_object ('red')->as_RGBhex, '800000'); +is(lc Color::Calc::gray_object ('red')->as_RGBhex, '4d4d4d'); +is(lc Color::Calc::grey_object ('red')->as_RGBhex, '4d4d4d'); +is(lc Color::Calc::invert_object ('red')->as_RGBhex, '00ffff'); +is(lc Color::Calc::light_object ('red')->as_RGBhex, 'ff8080'); +} + +is(join(',',Color::Calc::get_tuple ('red')), '0255,0,0'); +is(join(',',Color::Calc::mix_tuple ('red','blue')), '0128,0,0128'); + +is(join(',',Color::Calc::blend_bw_tuple ('red')), '0255,0128,0128'); +is(join(',',Color::Calc::blend_tuple ('red')), '0128,0128,0128'); +is(join(',',Color::Calc::bw_tuple ('red')), '77,77,77'); +is(join(',',Color::Calc::contrast_bw_tuple ('red')), '0255,0255,0255'); +is(join(',',Color::Calc::contrast_tuple ('red')), '0,0255,0255'); +is(join(',',Color::Calc::dark_tuple ('red')), '0128,0,0'); +is(join(',',Color::Calc::gray_tuple ('red')), '77,77,77'); +is(join(',',Color::Calc::grey_tuple ('red')), '77,77,77'); +is(join(',',Color::Calc::invert_tuple ('red')), '0,0255,0255'); +is(join(',',Color::Calc::light_tuple ('red')), '0255,0128,0128'); diff --git a/t/18_DEPRECATED_import_MODEval.t b/t/18_DEPRECATED_import_MODEval.t new file mode 100644 index 0000000..9ae8bb7 --- /dev/null +++ b/t/18_DEPRECATED_import_MODEval.t @@ -0,0 +1,71 @@ +use Test::More tests => 52; +use Color::Calc; + +local $Color::Calc::MODE = 'hex'; +is(color_get ('red'), 'ff0000'); +is(color ('red'), 'ff0000'); +is(color_mix ('red','blue'), '800080'); + +is(color_blend_bw ('red'), 'ff8080'); +is(color_blend ('red'), '808080'); +is(color_bw ('red'), '4d4d4d'); +is(color_contrast_bw ('red'), 'ffffff'); +is(color_contrast ('red'), '00ffff'); +is(color_dark ('red'), '800000'); +is(color_gray ('red'), '4d4d4d'); +is(color_grey ('red'), '4d4d4d'); +is(color_invert ('red'), '00ffff'); +is(color_light ('red'), 'ff8080'); + +local $Color::Calc::MODE = 'html'; +is(color_get ('F00'), 'red'); +is(color ('F00'), 'red'); +is(color_mix ('red','blue'), 'purple'); + +is(color_blend_bw ('red'), '#ff8080'); +is(color_blend ('red'), 'gray'); +is(color_bw ('red'), '#4d4d4d'); +is(color_contrast_bw ('red'), 'white'); +is(color_contrast ('red'), 'aqua'); +is(color_dark ('red'), 'maroon'); +is(color_gray ('red'), '#4d4d4d'); +is(color_grey ('red'), '#4d4d4d'); +is(color_invert ('red'), 'aqua'); +is(color_light ('red'), '#ff8080'); + +local $Color::Calc::MODE = 'object'; +SKIP: { +eval { require Graphics::ColorObject; }; +skip "Graphics::ColorObject not installed", 12 if $@; + +is(lc color_get ('red')->as_RGBhex, 'ff0000'); +is(lc color ('red')->as_RGBhex, 'ff0000'); +is(lc color_mix ('red','blue')->as_RGBhex, '800080'); + +is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); +is(lc color_blend ('red')->as_RGBhex, '808080'); +is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); +is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); +is(lc color_contrast ('red')->as_RGBhex, '00ffff'); +is(lc color_dark ('red')->as_RGBhex, '800000'); +is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); +is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); +is(lc color_invert ('red')->as_RGBhex, '00ffff'); +is(lc color_light ('red')->as_RGBhex, 'ff8080'); +} + +local $Color::Calc::MODE = 'tuple'; +is(join(',',color_get ('red')), '0255,0,0'); +is(join(',',color ('red')), '0255,0,0'); +is(join(',',color_mix ('red','blue')), '0128,0,0128'); + +is(join(',',color_blend_bw ('red')), '0255,0128,0128'); +is(join(',',color_blend ('red')), '0128,0128,0128'); +is(join(',',color_bw ('red')), '77,77,77'); +is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); +is(join(',',color_contrast ('red')), '0,0255,0255'); +is(join(',',color_dark ('red')), '0128,0,0'); +is(join(',',color_gray ('red')), '77,77,77'); +is(join(',',color_grey ('red')), '77,77,77'); +is(join(',',color_invert ('red')), '0,0255,0255'); +is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/18_DEPRECATED_import_suffix.t b/t/18_DEPRECATED_import_suffix.t new file mode 100644 index 0000000..c71157e --- /dev/null +++ b/t/18_DEPRECATED_import_suffix.t @@ -0,0 +1,67 @@ +use Test::More tests => 52; +use Color::Calc; + +is(color_get_hex ('red'), 'ff0000'); +is(color_hex ('red'), 'ff0000'); +is(color_mix_hex ('red','blue'), '800080'); + +is(color_blend_bw_hex ('red'), 'ff8080'); +is(color_blend_hex ('red'), '808080'); +is(color_bw_hex ('red'), '4d4d4d'); +is(color_contrast_bw_hex ('red'), 'ffffff'); +is(color_contrast_hex ('red'), '00ffff'); +is(color_dark_hex ('red'), '800000'); +is(color_gray_hex ('red'), '4d4d4d'); +is(color_grey_hex ('red'), '4d4d4d'); +is(color_invert_hex ('red'), '00ffff'); +is(color_light_hex ('red'), 'ff8080'); + +is(color_get_html ('F00'), 'red'); +is(color_html ('F00'), 'red'); +is(color_mix_html ('red','blue'), 'purple'); + +is(color_blend_bw_html ('red'), '#ff8080'); +is(color_blend_html ('red'), 'gray'); +is(color_bw_html ('red'), '#4d4d4d'); +is(color_contrast_bw_html ('red'), 'white'); +is(color_contrast_html ('red'), 'aqua'); +is(color_dark_html ('red'), 'maroon'); +is(color_gray_html ('red'), '#4d4d4d'); +is(color_grey_html ('red'), '#4d4d4d'); +is(color_invert_html ('red'), 'aqua'); +is(color_light_html ('red'), '#ff8080'); + +SKIP: { +eval { require Graphics::ColorObject; }; +skip "Graphics::ColorObject not installed", 12 if $@; + +is(lc color_get_object ('red')->as_RGBhex, 'ff0000'); +is(lc color_object ('red')->as_RGBhex, 'ff0000'); +is(lc color_mix_object ('red','blue')->as_RGBhex, '800080'); + +is(lc color_blend_bw_object ('red')->as_RGBhex, 'ff8080'); +is(lc color_blend_object ('red')->as_RGBhex, '808080'); +is(lc color_bw_object ('red')->as_RGBhex, '4d4d4d'); +is(lc color_contrast_bw_object ('red')->as_RGBhex, 'ffffff'); +is(lc color_contrast_object ('red')->as_RGBhex, '00ffff'); +is(lc color_dark_object ('red')->as_RGBhex, '800000'); +is(lc color_gray_object ('red')->as_RGBhex, '4d4d4d'); +is(lc color_grey_object ('red')->as_RGBhex, '4d4d4d'); +is(lc color_invert_object ('red')->as_RGBhex, '00ffff'); +is(lc color_light_object ('red')->as_RGBhex, 'ff8080'); +} + +is(join(',',color_get_tuple ('red')), '0255,0,0'); +is(join(',',color_tuple ('red')), '0255,0,0'); +is(join(',',color_mix_tuple ('red','blue')), '0128,0,0128'); + +is(join(',',color_blend_bw_tuple ('red')), '0255,0128,0128'); +is(join(',',color_blend_tuple ('red')), '0128,0128,0128'); +is(join(',',color_bw_tuple ('red')), '77,77,77'); +is(join(',',color_contrast_bw_tuple ('red')), '0255,0255,0255'); +is(join(',',color_contrast_tuple ('red')), '0,0255,0255'); +is(join(',',color_dark_tuple ('red')), '0128,0,0'); +is(join(',',color_gray_tuple ('red')), '77,77,77'); +is(join(',',color_grey_tuple ('red')), '77,77,77'); +is(join(',',color_invert_tuple ('red')), '0,0255,0255'); +is(join(',',color_light_tuple ('red')), '0255,0128,0128'); diff --git a/t/19_DEPRECATED_module_class-method.t b/t/19_DEPRECATED_module_class-method.t new file mode 100644 index 0000000..caa1c77 --- /dev/null +++ b/t/19_DEPRECATED_module_class-method.t @@ -0,0 +1,66 @@ +use Test::More tests => 48; +use Color::Calc::hex(); +use Color::Calc::html(); +use Color::Calc::object(); +use Color::Calc::tuple(); + +is(Color::Calc::hex::get ('red'), 'ff0000'); +is(Color::Calc::hex::mix ('red','blue'), '800080'); + +is(Color::Calc::hex::blend_bw ('red'), 'ff8080'); +is(Color::Calc::hex::blend ('red'), '808080'); +is(Color::Calc::hex::bw ('red'), '4d4d4d'); +is(Color::Calc::hex::contrast_bw ('red'), 'ffffff'); +is(Color::Calc::hex::contrast ('red'), '00ffff'); +is(Color::Calc::hex::dark ('red'), '800000'); +is(Color::Calc::hex::gray ('red'), '4d4d4d'); +is(Color::Calc::hex::grey ('red'), '4d4d4d'); +is(Color::Calc::hex::invert ('red'), '00ffff'); +is(Color::Calc::hex::light ('red'), 'ff8080'); + +is(Color::Calc::html::get ('F00'), 'red'); +is(Color::Calc::html::mix ('red','blue'), 'purple'); + +is(Color::Calc::html::blend_bw ('red'), '#ff8080'); +is(Color::Calc::html::blend ('red'), 'gray'); +is(Color::Calc::html::bw ('red'), '#4d4d4d'); +is(Color::Calc::html::contrast_bw ('red'), 'white'); +is(Color::Calc::html::contrast ('red'), 'aqua'); +is(Color::Calc::html::dark ('red'), 'maroon'); +is(Color::Calc::html::gray ('red'), '#4d4d4d'); +is(Color::Calc::html::grey ('red'), '#4d4d4d'); +is(Color::Calc::html::invert ('red'), 'aqua'); +is(Color::Calc::html::light ('red'), '#ff8080'); + +SKIP: { +eval { require Graphics::ColorObject; }; +skip "Graphics::ColorObject not installed", 12 if $@; + +is(lc Color::Calc::object::get ('red')->as_RGBhex, 'ff0000'); +is(lc Color::Calc::object::mix ('red','blue')->as_RGBhex, '800080'); + +is(lc Color::Calc::object::blend_bw ('red')->as_RGBhex, 'ff8080'); +is(lc Color::Calc::object::blend ('red')->as_RGBhex, '808080'); +is(lc Color::Calc::object::bw ('red')->as_RGBhex, '4d4d4d'); +is(lc Color::Calc::object::contrast_bw ('red')->as_RGBhex, 'ffffff'); +is(lc Color::Calc::object::contrast ('red')->as_RGBhex, '00ffff'); +is(lc Color::Calc::object::dark ('red')->as_RGBhex, '800000'); +is(lc Color::Calc::object::gray ('red')->as_RGBhex, '4d4d4d'); +is(lc Color::Calc::object::grey ('red')->as_RGBhex, '4d4d4d'); +is(lc Color::Calc::object::invert ('red')->as_RGBhex, '00ffff'); +is(lc Color::Calc::object::light ('red')->as_RGBhex, 'ff8080'); +} + +is(join(',',Color::Calc::tuple::get ('red')), '0255,0,0'); +is(join(',',Color::Calc::tuple::mix ('red','blue')), '0128,0,0128'); + +is(join(',',Color::Calc::tuple::blend_bw ('red')), '0255,0128,0128'); +is(join(',',Color::Calc::tuple::blend ('red')), '0128,0128,0128'); +is(join(',',Color::Calc::tuple::bw ('red')), '77,77,77'); +is(join(',',Color::Calc::tuple::contrast_bw ('red')), '0255,0255,0255'); +is(join(',',Color::Calc::tuple::contrast ('red')), '0,0255,0255'); +is(join(',',Color::Calc::tuple::dark ('red')), '0128,0,0'); +is(join(',',Color::Calc::tuple::gray ('red')), '77,77,77'); +is(join(',',Color::Calc::tuple::grey ('red')), '77,77,77'); +is(join(',',Color::Calc::tuple::invert ('red')), '0,0255,0255'); +is(join(',',Color::Calc::tuple::light ('red')), '0255,0128,0128'); diff --git a/t/19_DEPRECATED_module_import_hex.t b/t/19_DEPRECATED_module_import_hex.t new file mode 100644 index 0000000..115fb84 --- /dev/null +++ b/t/19_DEPRECATED_module_import_hex.t @@ -0,0 +1,17 @@ +use Test::More tests => 13; +use Color::Calc::hex; + +is(color_get ('red'), 'ff0000'); +is(color ('red'), 'ff0000'); +is(color_mix ('red','blue'), '800080'); + +is(color_blend_bw ('red'), 'ff8080'); +is(color_blend ('red'), '808080'); +is(color_bw ('red'), '4d4d4d'); +is(color_contrast_bw ('red'), 'ffffff'); +is(color_contrast ('red'), '00ffff'); +is(color_dark ('red'), '800000'); +is(color_gray ('red'), '4d4d4d'); +is(color_grey ('red'), '4d4d4d'); +is(color_invert ('red'), '00ffff'); +is(color_light ('red'), 'ff8080'); diff --git a/t/19_DEPRECATED_module_import_html.t b/t/19_DEPRECATED_module_import_html.t new file mode 100644 index 0000000..ad085af --- /dev/null +++ b/t/19_DEPRECATED_module_import_html.t @@ -0,0 +1,19 @@ +use Test::More tests => 14; +use Color::Calc::html; + +is(color_get ('F00'), 'red'); +is(color_get ('green'), 'lime'); # !!! input uses X11 color names !!! + +is(color ('F00'), 'red'); +is(color_mix ('red','blue'), 'purple'); + +is(color_blend_bw ('red'), '#ff8080'); +is(color_blend ('red'), 'gray'); +is(color_bw ('red'), '#4d4d4d'); +is(color_contrast_bw ('red'), 'white'); +is(color_contrast ('red'), 'aqua'); +is(color_dark ('red'), 'maroon'); +is(color_gray ('red'), '#4d4d4d'); +is(color_grey ('red'), '#4d4d4d'); +is(color_invert ('red'), 'aqua'); +is(color_light ('red'), '#ff8080'); diff --git a/t/19_DEPRECATED_module_import_object.t b/t/19_DEPRECATED_module_import_object.t new file mode 100644 index 0000000..d8a78c4 --- /dev/null +++ b/t/19_DEPRECATED_module_import_object.t @@ -0,0 +1,22 @@ +use Test::More tests => 13; +use Color::Calc::object; + +SKIP: { +eval { require Graphics::ColorObject; }; +skip "Graphics::ColorObject not installed", 12 if $@; + +is(lc color_get ('red')->as_RGBhex, 'ff0000'); +is(lc color ('red')->as_RGBhex, 'ff0000'); +is(lc color_mix ('red','blue')->as_RGBhex, '800080'); + +is(lc color_blend_bw ('red')->as_RGBhex, 'ff8080'); +is(lc color_blend ('red')->as_RGBhex, '808080'); +is(lc color_bw ('red')->as_RGBhex, '4d4d4d'); +is(lc color_contrast_bw ('red')->as_RGBhex, 'ffffff'); +is(lc color_contrast ('red')->as_RGBhex, '00ffff'); +is(lc color_dark ('red')->as_RGBhex, '800000'); +is(lc color_gray ('red')->as_RGBhex, '4d4d4d'); +is(lc color_grey ('red')->as_RGBhex, '4d4d4d'); +is(lc color_invert ('red')->as_RGBhex, '00ffff'); +is(lc color_light ('red')->as_RGBhex, 'ff8080'); +} diff --git a/t/19_DEPRECATED_module_import_tuple.t b/t/19_DEPRECATED_module_import_tuple.t new file mode 100644 index 0000000..e373b0d --- /dev/null +++ b/t/19_DEPRECATED_module_import_tuple.t @@ -0,0 +1,17 @@ +use Test::More tests => 13; +use Color::Calc::tuple; + +is(join(',',color_get ('red')), '0255,0,0'); +is(join(',',color ('red')), '0255,0,0'); +is(join(',',color_mix ('red','blue')), '0128,0,0128'); + +is(join(',',color_blend_bw ('red')), '0255,0128,0128'); +is(join(',',color_blend ('red')), '0128,0128,0128'); +is(join(',',color_bw ('red')), '77,77,77'); +is(join(',',color_contrast_bw ('red')), '0255,0255,0255'); +is(join(',',color_contrast ('red')), '0,0255,0255'); +is(join(',',color_dark ('red')), '0128,0,0'); +is(join(',',color_gray ('red')), '77,77,77'); +is(join(',',color_grey ('red')), '77,77,77'); +is(join(',',color_invert ('red')), '0,0255,0255'); +is(join(',',color_light ('red')), '0255,0128,0128'); diff --git a/t/20_input_formats_oo.t b/t/20_input_formats_oo.t new file mode 100644 index 0000000..12c61ed --- /dev/null +++ b/t/20_input_formats_oo.t @@ -0,0 +1,12 @@ +use Test::More tests => 8; +use Color::Calc(); +my $cc = Color::Calc->new( 'OutputFormat' => 'hex' ); + +is($cc->mix ('F00','00F'), '800080'); +is($cc->mix ('#F00','#00F'), '800080'); +is($cc->mix ('FF0000','0000FF'), '800080'); +is($cc->mix ('#FF0000','#0000FF'), '800080'); +is($cc->mix ([255,0,0],[0,0,255]), '800080'); +is($cc->mix ('0255',0,0,0,0,255), '800080'); +is($cc->mix (['0255',0,0],0,0,255), '800080'); +is($cc->mix ('0255',0,0,[0,0,255]), '800080'); diff --git a/t/21_input_formats_import.t b/t/21_input_formats_import.t new file mode 100644 index 0000000..7499f67 --- /dev/null +++ b/t/21_input_formats_import.t @@ -0,0 +1,11 @@ +use Test::More tests => 8; +use Color::Calc( 'OutputFormat' => 'hex' ); + +is(color_mix ('F00','00F'), '800080'); +is(color_mix ('#F00','#00F'), '800080'); +is(color_mix ('FF0000','0000FF'), '800080'); +is(color_mix ('#FF0000','#0000FF'), '800080'); +is(color_mix ([255,0,0],[0,0,255]), '800080'); +is(color_mix ('0255',0,0,0,0,255), '800080'); +is(color_mix (['0255',0,0],0,0,255), '800080'); +is(color_mix ('0255',0,0,[0,0,255]), '800080'); diff --git a/t/30_color_schemes_oo.t b/t/30_color_schemes_oo.t new file mode 100644 index 0000000..6a3d3a1 --- /dev/null +++ b/t/30_color_schemes_oo.t @@ -0,0 +1,9 @@ +use Test::More tests => 2; +use Color::Calc(); + + +my $cc = Color::Calc->new( 'OutputFormat' => 'html' ); +is($cc->get ('green'), 'lime'); + +$cc = Color::Calc->new( 'ColorScheme' => 'HTML', 'OutputFormat' => 'html' ); +is($cc->get ('green'), 'green'); diff --git a/t/31_color_schemes_import_HTML.t b/t/31_color_schemes_import_HTML.t new file mode 100644 index 0000000..1ed8946 --- /dev/null +++ b/t/31_color_schemes_import_HTML.t @@ -0,0 +1,3 @@ +use Test::More tests => 1; +use Color::Calc('ColorScheme' => 'HTML', 'OutputFormat' => 'html'); +is(color_get ('green'), 'green'); diff --git a/t/31_color_schemes_import_X.t b/t/31_color_schemes_import_X.t new file mode 100644 index 0000000..fa2b656 --- /dev/null +++ b/t/31_color_schemes_import_X.t @@ -0,0 +1,3 @@ +use Test::More tests => 2; +use Color::Calc('OutputFormat' => 'html' ); +is($cc->get ('green'), 'lime');
cfaerber/Graphics-ColorNames-WWW
2b0b8ad9aabf4e8e491acee10b37f6e1188b2af4
Color-Calc-0.29_0001
diff --git a/Calc.pm b/Calc.pm index e3524b9..11a0423 100644 --- a/Calc.pm +++ b/Calc.pm @@ -1,477 +1,624 @@ package Color::Calc; use strict; use Carp; use POSIX; +use Params::Validate qw(:all); + use Graphics::ColorNames qw( hex2tuple tuple2hex ); use Graphics::ColorNames::HTML; -our $VERSION = '0.20'; +our $VERSION = '0.29_0001'; $VERSION = eval $VERSION; -our $AUTOLOAD; our $MODE = (); -use Exporter; - -our @__subs; - -BEGIN { -our @__subs = qw( blend blend_bw bw contrast contrast_bw dark get grey invert -light mix); -sub __suffixes { ($_, $_.'_tuple', $_.'_hex', $_.'_html', $_.'_object', $_.'_pdf') }; - -our @ISA = qw(Exporter); -our @EXPORT = map &__suffixes, ('color', map { 'color_'.$_ } @__subs); -} - -my %ColorNames = (); -tie %ColorNames, 'Graphics::ColorNames'; - my %__HTMLColors = (); +our @__subs = qw( blend blend_bw bw contrast contrast_bw dark get grey invert light mix ); + +my %__formats = ( + 'tuple' => sub { return @_; }, + 'hex' => sub { return tuple2hex((@_)); }, + 'html' => sub { my $col = lc(tuple2hex((@_))); return $__HTMLColors{$col} || '#'.$col; }, + 'object' => sub { eval { require Graphics::ColorObject; }; return Graphics::ColorObject->new_RGB255( [(@_)] ); }, + 'pdf' => sub { eval { require PDF::API2::Color; }; return PDF::API2::Color->newRGB( map { $_ / 255 } ((@_))); }, +); +my @__formats = keys %__formats; +my $__formats_re = join('|', @__formats,'__MODEvar'); + { my $table = Graphics::ColorNames::HTML::NamesRgbTable(); %__HTMLColors = map { ( sprintf('%06x', $$table{$_}) => $_ ) } grep { $_ ne 'fuscia' } keys %$table; }; +our @EXPORT = ('color', map({"color_$_"} @__formats, map({my $s=$_; (map{$s.'_'.$_} @__formats)} @__subs), @__subs)); +our @ISA = ('Exporter'); + +my %new_param = ( + 'ColorScheme' => { type => SCALAR, optional => 1 }, + 'OutputFormat' => { type => SCALAR, untaint => 1, regexp => qr($__formats_re), optional => 1 }, +); + +sub new { + my $pkg = shift; validate(@_, \%new_param); + my $self = {@_}; bless($self, $pkg); + + if(!ref($self->{'ColorScheme'})) { + my %ColorNames; + tie %ColorNames, 'Graphics::ColorNames', ($self->{'ColorScheme'} || 'X'); + $self->{'ColorScheme'} = \%ColorNames; + } + + $self->set_output_format($self->{'OutputFormat'} || 'tuple'); + + return $self; +} + +my $__default_object; +sub __get_default { + $__default_object = __PACKAGE__->new('OutputFormat' => '__MODEvar') unless $__default_object; + return $__default_object; +} + +my $__tuple_object; +sub __get_tuple { + $__tuple_object = __PACKAGE__->new('OutputFormat' => 'tuple') unless $__tuple_object; + return $__tuple_object; +} + +my %import_param = ( + %new_param, + 'Prefix' => { type => SCALAR, optional => 1, regexp => qr/^[[:alpha:]\d]\w*$/ }, + '__Prefix' => { type => SCALAR, optional => 1, regexp => qr/^[[:alpha:]\d]\w*$/ }, + '__Suffix' => { type => SCALAR, optional => 1, regexp => qr/^\w+$/ }, +); + +my %import_param_names = map { ($_=>1) } keys %import_param; + +sub import { + my $pkg = shift; + if(!@_ || !exists $import_param_names{$_[0]}) { + local $Exporter::ExportLevel; $Exporter::ExportLevel++; + return Exporter::import($pkg, @_); + } + __import(caller(0),@_); +} + +sub __import { + my $pkg = shift; + validate(@_, \%import_param); + my %param = @_; + + my $std_prefix = (exists $param{'Prefix'}) ? $param{'Prefix'} : 'color'; + delete $param{'Prefix'}; + + my $prefix = (exists $param{'__Prefix'}) ? $param{'__Prefix'} : $std_prefix ? $std_prefix.'_' : ''; + delete $param{'__Prefix'}; + my $suffix = (exists $param{'__Suffix'}) ? $param{'__Suffix'} : ''; + delete $param{'__Suffix'}; + + my $obj = new(__PACKAGE__, %param); + + { + no strict 'refs'; + { + $prefix = $pkg.'::'.$prefix; + foreach my $sub (@__subs) { + my $name = $prefix.$sub.$suffix; + *$name = sub { $obj->$sub(@_); }; + }; + }; + + if($std_prefix) { + my $name = $pkg.'::'.$std_prefix.$suffix; + *$name = sub { $obj->get(@_); }; + } + } +} + + +sub __normtuple_in { + return map { ($_ < 0) ? 0 : (($_ > 255) ? 255 : int($_+.5)) } @_; +} + +sub __normtuple_out { + return map { (length $_) == 3 ? '0'.$_ : $_ } __normtuple_in(@_) +} + +sub __normtuple { + return __normtuple_out(__normtuple_in(@_)); +} + +sub __is_col_val { + return undef unless defined $_[0]; + return undef if $_[0] eq ''; + my ($n,$u) = POSIX::strtod($_[0]); + return undef if $u != 0; + return ($n <= 255) && ($n>= 0); +} + +# Note: Color::Object was supported in versions before 0.2. This +# is kept for compatibility, but no longer documented. +# +# Note: versions before 0.2 allowed calling some functions (those +# with one parameter) with a list instead of an arrayref. This is +# kept for compatibility, but no longer documented. + +sub __get { + my ($self,$p,$q) = @_; + + if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 0 ) { + $$p[0] = $$p[0]->[0]; + } + + if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 2 ) { + return __normtuple_in(@{shift @$p}); + } + elsif( UNIVERSAL::isa($$p[0],'Color::Object') || + UNIVERSAL::isa($$p[0],'PDF::API2::Color')) { + return (map { 255 * $_; } (shift(@{$p})->asRGB)); + } + elsif( UNIVERSAL::isa($$p[0],'Graphics::ColorObject')) { + return (shift(@{$p})->as_RGB255()); + } + elsif( $#$p >= (2 + ($q||0)) && + __is_col_val($$p[0]) && + __is_col_val($$p[1]) && + __is_col_val($$p[2])) { + return (splice @$p, 0, 3); + } + elsif( $$p[0] =~ m/^#?([0-9A-F])([0-9A-F])([0-9A-F])$/i ) { + shift @$p; + return (map { hex($_) * 17 } ($1,$2,$3)); + } + elsif( $$p[0] =~ m/^#?([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])$/i ) { + shift @$p; + return (map { hex($_) } ($1,$2,$3)); + } + else { + my $col = $self->{'ColorScheme'}->{$$p[0]}; + if($col) { + shift @$p; + return hex2tuple($col); + } else { + carp("Invalid color name '$$p[0]'"); + return undef; + } + } +} + +sub set_output_format { + validate_pos(@_, { isa => __PACKAGE__ }, { type => SCALAR, regexp => qr($__formats_re) }); + my $self = shift; + + my $old = $self->{'OutputFormat'}; + $self->{'OutputFormat'} = shift; + + $self->{'__put'} = $self->{'OutputFormat'} eq '__MODEvar' + ? sub{ return $__formats{$MODE || 'tuple'}->(@_); } + : $__formats{$self->{'OutputFormat'}}; + + return $old; +} + +sub __put { + my $self = shift; + return $self->{'__put'}->(@_); +} + +sub __get_self { + my $p = shift; + + if(UNIVERSAL::isa($p->[0], __PACKAGE__)) { + return shift @$p; + } else { + return __get_default; + } +} + +sub get { + my $self = __get_self(\@_); + return $self->__put(__normtuple_out($self->__get(\@_))); +} + + +sub invert { + my $self = __get_self(\@_); + return __normtuple_out(map { 255 - $_ } $self->__get(\@_)); +} + +sub bw { + my $self = __get_self(\@_); + my @c = $self->__get(\@_); + my $g = $c[0]*.3 + $c[1]*.59 + $c[2]*.11; + return _put(__normtuple($g,$g,$g)); +} + +*grey = \&bw; +*gray = \&bw; + + +sub mix { + my $self = __get_self(\@_); + my @c1 = ($self->__get(\@_,1)); + my @c2 = ($self->__get(\@_)); + my $alpha = shift(@_); $alpha = 0.5 unless defined $alpha; + + return $self->__put(__normtuple( + ($c1[0] + ($c2[0]-$c1[0])*$alpha), + ($c1[1] + ($c2[1]-$c1[1])*$alpha), + ($c1[2] + ($c2[2]-$c1[2])*$alpha) )); +} + +sub light { + my $self = __get_self(\@_); + return $self->__put(__get_tuple->mix([$self->__get(\@_)],[255,255,255],shift)); +} + + +sub dark { + my $self = __get_self(\@_); + return $self->__put(__get_tuple->mix([$self->__get(\@_)],[0,0,0],shift)); +} + + +sub contrast { + my $self = __get_self(\@_); + my @rgb = $self->__get(\@_); + my $cut = (shift || .5) * 255; + return $self->__put(map { $_ >= $cut ? 0 : '0255' } @rgb); +} + + +sub contrast_bw { + my $self = __get_self(\@_); + return $self->__put(__get_tuple->contrast([grey_tuple(@_)], shift)); +} + + +sub blend { + my $self = __get_self(\@_); + my @c1 = $self->__get(\@_); + return __get_tuple->mix(\@c1,[contrast(\@c1)],shift); +} + + +sub blend_bw { + my $self = __get_self(\@_); + my @c = $self->__get(\@_); + return __get_tuple->mix(\@c,[contrast_bw(\@c)],shift); +} + + +foreach my $format (@__formats) { + __import(__PACKAGE__, 'Prefix' => 'color', '__Suffix' => "_$format", 'OutputFormat' => $format); + __import(__PACKAGE__, 'Prefix' => '', '__Suffix' => "_$format", 'OutputFormat' => $format); +} + +__import(__PACKAGE__, 'Prefix' => 'color', 'OutputFormat' => '__MODEvar'); + +#- ----------------------------- +# + =head1 NAME Color::Calc - Simple calculations with RGB colors. =head1 SYNOPSIS use Color::Calc (); my $background = 'green'; print 'background: ',Color::Calc::color_html($background),';'; print 'border-top: solid 1px ',Color::Calc::light_html($background),';'; print 'border-bottom: solid 1px ',Color::Calc::dark_html($background),';'; print 'color: ',contrast_bw_html($background),';'; =head1 DESCRIPTION The C<Color::Calc> module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. -=head2 Color Input Formats +=head2 Color Formats + +=head3 Input -All of the functions accept colors as parameters in the following +All of the methods accept colors as parameters in the following formats: -=over 4 +=over =item * An arrayref pointing to an array with three elements in the range C<0>..C<255> corresponding to the red, green, and blue component. =item * A string containing a hexadecimal RGB value in the form C<#I<RRGGBB>>/C<#I<RGB>> or C<I<RGB>>/C<I<RRGGBB>>. =item * A color name accepted by C<Graphics::ColorNames>. =item * A C<PDF::API2::Color> reference. =item * A C<Graphics::ColorObject> reference. =item * -The return value of any of the public C<Color::Calc::>* functions, even if it -is a list returned by C<I<xxx>_tuple>. +A return value of any (public) C<Color::Calc> method even if the +C<tuple> output format is selected. =back -=head2 Color Output Formats +=head3 Output C<Color::Calc> can return colors in the following modes: -=over 4 +=over -=item * tuple +=item tuple Returns a list of three values in the range 0..255. -=item * hex +=item hex Returns a hexadecimal RGB value in the format RRGGBB. -=item * html +=item html Returns a value compatible with W3C's HTML and CSS specifications, i.e. I<#RRGGBB> or one of the sixteen color names. -=item * pdf +=item pdf Returns a C<PDF::API2::Color> reference. The module C<PDF::API2::Color> must be installed. -=item * object +=item object Returns a C<Graphics::ColorObject> reference. The module C<Graphics::ColorObject> must be installed. -=back - -You can select the mode using one of the following methods: - -=over 4 - -=item * Add a suffix C<_I<mode>> to the function name: - -Call the function C<mix> as C<mix_hex>, for example. - -=item * Set C<$Color::Calc::MODE>: - -This is a global variable. +=item __MODEvar -Valid values are 'tuple', 'hex', 'html', 'obj', 'pdf', or 'object' -(the default ist 'tuple' to maintain compatibility with earlier -versions). - -=item * Use a different module - -You can use one of the modules C<Color::Calc::hex>, -C<Color::Calc::html>, C<Color::Calc::tulpe> C<Color::Calc::obj>, -C<Color::Calc::pdf>, or C<Color::Calc::object>. - -The function C<Color::Calc::html::mix> is equivalent to -C<Color::Calc::mix_html>, for example. - -These modules export their functions with the C<color_> prefix by -default, just as the main module. +(DEPRECATED) Uses the value of C<$Color::Calc::MODE> to select the +output format. You should use C<local> when setting this variable. =back -=head2 Accessing the Functions - -The functions can be accessed in several ways: +=head2 Object-Orientated interface -=over 4 + use Color::Calc(); + my $cc = new Color::Calc( 'ColorScheme' => 'X', OutputFormat => 'HTML' ); + print $cc->invert( 'white' ); -=item * +=over -The functions are exported by default with a prefix of C<color_>: +=item new - use Color::Calc; - print color_dark_hex('#FFFFFF'); # returns '808080'; + $cc = new Color::Calc( 'ColorScheme' => $name, 'OutputFormat' => $format ); -=item * +Creates a new C<Color::Calc> object which can be used to access the color +calculation methods. -If you prefer not to import the functions, you can call them by -specifying the package name; in this case, you may leave out the -prefix C<color_>: +=over - use Color::Calc (); - print Color::Calc::dark_hex('#FFFFFF'); # returns '808080'; - print Color::Calc::color_dark_hex('#FFFFFF'); # returns '808080'; +=item ColorScheme -=back +One of the color schemes accepted by C<Graphics::ColorNames>. Used to translate +color names on input. See the documentation of C<Graphics::ColorNames> for +possible values. -Note that I<function> and color_I<function> are fully equivalent -except that only color_I<function> is exported by default. +Default: C<X> (please note that this is incompatible with HTML +color names). -=head2 Available Functions +=item OutputFormat -The following functions are available: +Sets the output format of the object's methods. See above for possible values. -=over 4 +Default: C<__MODEvar> -=item * color($color) +=back -=item * color_get($color) +=item $cc->get($color) -Returns the color as-is (but in the format specified). This +Returns the color as-is (but in the selected output format). This function can be used for color format conversion/normalisation. -=cut - -sub __normtuple_in { - return map { ($_ < 0) ? 0 : (($_ > 255) ? 255 : int($_+.5)) } @_; -} - -sub __normtuple_out { - return map { (length $_) == 3 ? '0'.$_ : $_ } __normtuple_in(@_) -} - -sub __normtuple { - return __normtuple_out(__normtuple_in(@_)); -} - -sub __is_col_val { - return undef unless defined $_[0]; - return undef if $_[0] eq ''; - my ($n,$u) = POSIX::strtod($_[0]); - return undef if $u != 0; - return ($n <= 255) && ($n>= 0); -} - -# Note: Color::Object was supported in versions before 0.2. This -# is kept for compatibility, but no longer documented. -# -# Note: versions before 0.2 allowed calling some functions (those -# with one parameter) with a list instead of an arrayref. This is -# kept for compatibility, but no longer documented. - -sub __get(\@;$) { - my ($p,$q) = @_; - - if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 0 ) { - $$p[0] = $$p[0]->[0]; - } - - if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 2 ) { - return __normtuple_in(@{shift @$p}); - } - elsif( UNIVERSAL::isa($$p[0],'Color::Object') || - UNIVERSAL::isa($$p[0],'PDF::API2::Color')) { - return (map { 255 * $_; } (shift(@{$p})->asRGB)); - } - elsif( UNIVERSAL::isa($$p[0],'Graphics::ColorObject')) { - return (shift(@{$p})->as_RGB255()); - } - elsif( $#$p >= (2 + ($q||0)) && - __is_col_val($$p[0]) && - __is_col_val($$p[1]) && - __is_col_val($$p[2])) { - return (splice @$p, 0, 3); - } - elsif( $$p[0] =~ m/^#?([0-9A-F])([0-9A-F])([0-9A-F])$/i ) { - shift @$p; - return (map { hex($_) * 17 } ($1,$2,$3)); - } - elsif( $$p[0] =~ m/^#?([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])$/i ) { - shift @$p; - return (map { hex($_) } ($1,$2,$3)); - } - else { - my $col = $ColorNames{$$p[0]}; - if($col) { - shift @$p; - return hex2tuple($col); - } else { - carp("Invalid color name '$$p[0]'"); - return undef; - } - } -} - -sub get_tuple { return __normtuple_out(__get(@_)); } -*color_tuple = \&get_tuple; - -=item * color_invert($color) +=item $cc->invert($color) Returns the inverse of $color. -=cut - -sub invert_tuple { - return __normtuple_out(map { 255 - $_ } __get(@_)); -} - -=item * color_bw($color) -=item * color_grey($color) +=item $cc->bw($color) +=item $cc->grey($color) Converts $color to greyscale. -=cut - -sub bw_tuple { - my @c = __get(@_); - my $g = $c[0]*.3 + $c[1]*.59 + $c[2]*.11; - return __normtuple($g,$g,$g); -} - -*grey_tuple = \&bw_tuple; -*gray_tuple = \&bw_tuple; - -=item * color_mix($color1, $color2 [, $alpha]) +=item $cc->mix($color1, $color2 [, $alpha]) Returns a color that is the mixture of $color1 and $color2. The optional $alpha parameter can be a value between 0.0 (use $color1 only) and 1.0 (use $color2 only), the default is 0.5. -=cut - -sub mix_tuple { - my @c1 = (__get @_,1); - my @c2 = (__get @_); - my $alpha = shift(@_); $alpha = 0.5 unless defined $alpha; - - return __normtuple( - ($c1[0] + ($c2[0]-$c1[0])*$alpha), - ($c1[1] + ($c2[1]-$c1[1])*$alpha), - ($c1[2] + ($c2[2]-$c1[2])*$alpha) ); -} - -=item * color_light($color [, $alpha]) +=item $cc->color_light($color [, $alpha]) Returns a lighter version of $color, i.e. returns -mix($color,[255,255,255],$alpha); +$cc->mix($color,[255,255,255],$alpha); The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use 'white' only), the default is 0.5. -=cut - -sub light_tuple { - return mix_tuple([__get @_],[255,255,255],shift); -} - -=item * color_dark($color [, $alpha]) +=item $cc->dark($color [, $alpha]) Returns a darker version of $color, i.e. returns -mix($color,[0,0,0],$alpha); +$cc->mix($color,[0,0,0],$alpha); The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use 'black' only), the default is 0.5. -=cut - -sub dark_tuple { - return mix_tuple([__get @_],[0,0,0],shift); -} - -=item * color_contrast($color [, $cut]) +=item $cc->contrast($color [, $cut]) Returns a color that has the highest possible contrast to the input color. This is done by setting the red, green, and blue values to 0 if the corresponding value in the input is above C<($cut * 255)> and to 255 otherwise. The default for C<$cut> is .5, representing a cutoff between 127 and 128. -=cut - -sub contrast_tuple { - my @rgb = __get @_; - my $cut = (shift || .5) * 255; - return map { $_ >= $cut ? 0 : '0255' } @rgb; -} - -=item * color_contrast_bw($color [, $cut]) +=item $cc->contrast_bw($color [, $cut]) Returns black or white, whichever has the higher contrast to $color. This is done by setting returning black if the grey value of $color is above C<($cut * 255)> and white otherwise. The default for C<$cut> is .5, representing a cutoff between 127 and 128. -=cut - -sub contrast_bw_tuple { - return contrast_tuple([grey_tuple(@_)], shift); -} - -=item * color_blend($color [, $alpha]) +=item $cc->blend($color [, $alpha]) Returns a color that blends into the background, i.e. it returns -mix($color,contrast($color),$alpha). +$cc->mix($color,$cc->contrast($color),$alpha). The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use C<contrast($color)> only), the default is 0.5. The idea is that C<$color> is the foreground color, so C<contrast($color)> is similar to the background color. Mixing them returns a color somewhere between them. You might want to use mix($color, $background, $alpha) instead if you know the real background color. -=cut - -sub blend_tuple { - my @c1 = __get @_; - return mix_tuple(\@c1,[contrast(\@c1)],shift); -} - -=item * color_blend_bw($color [, $alpha]) +=item $cc->blend_bw($color [, $alpha]) Returns a mix of $color and black or white, whichever has the higher contrast to $color. The optional $alpha parameter can be a value between 0.0 (use $color only) and 1.0 (use black/white only), the default is 0.5. =back -=cut +=head2 Procedural Interface With Importing -sub blend_bw_tuple { - my @c = __get @_; - return mix_tuple(\@c,[contrast_bw(\@c)],shift); -} +You can also choose to import customised funtions into your +namespace: -BEGIN { - -foreach my $sub (('color',@__subs)) { - no strict 'refs'; - my $name = $sub.'_tuple'; - - my $hex = $sub.'_hex'; - *$hex = sub { return tuple2hex(&$name(@_)); }; - - my $html = $sub.'_html'; - *$html = sub { - my $col = lc(tuple2hex(&$name(@_))); - return $__HTMLColors{$col} || '#'.$col; - }; - - my $obj = $sub.'_object'; - *$obj = sub { - eval { require Graphics::ColorObject; }; - return Graphics::ColorObject->new_RGB255( [&$name(@_)] ); - }; - - my $pdf = $sub.'_pdf'; - *$pdf = sub { - eval { require PDF::API2::Color; }; - return PDF::API2::Color->newRGB( map { $_ / 255 } (&$name(@_))); - }; - - *$sub = sub { - my $name = $sub.'_'.(lc($MODE || 'tuple')); - return (&$name(@_)); - }; -} + use Color::Calc( + 'ColorScheme' => 'X', + 'OutputFormat' => 'HTML', + 'Prefix' => 'cc' ); + print cc_invert( 'white' ); # prints 'black' -foreach my $sub ( map &__suffixes, @__subs ) -{ - no strict 'refs'; - my $csub = "color_$sub"; - *$csub = \&$sub; -}; +On import, you can specify the following parameters: + +=over + +=item ColorScheme + +See above. + +=item OutputFormat + +See above. + +=item Prefix + +Adds the prefix and an underscore to the front of the method +names. You can call the methods as I<prefix>_I<method_name>. You +can also call I<prefix> instead of I<prefix>C<_get>. + +Default: C<color> + +=back + +Please note that specifying an empty list of parameters means +"don't import anything". Omit the list to import the default +functions. + +You can also C<use> the following modules to import the function +with pre-defined parameters. + +=over + +=item C<use Color::Calc::WWW> + +Same as C<use Color::Calc( ColorScheme =&gt; 'Netscape', OutputFormat => 'html' )> + +=item C<use Color::Calc::html> + +(DEPRECATED) Same as C<use Color::Calc( OutputFormat =&gt; 'html')> + +Please note that this only selects HTML as the C<OutputFormat> but +not as the C<ColorScheme> (which defaults to 'X'), which is +probably not what you expect. Use C<Color::Calc::WWW> instead. + +=item C<use Color::Calc::hex> + +Same as C<use Color::Calc( OutputFormat =&gt; 'hex')> + +=item C<use Color::Calc::object> + +Same as C<use Color::Calc( OutputFormat =&gt; 'object')> + +=item C<use Color::Calc::pdf> + +Same as C<use Color::Calc( OutputFormat =&gt; 'pdf')> + +=item C<use Color::Calc::tuple> + +Same as C<use Color::Calc( OutputFormat =&gt; 'tuple')> + +=back + +=head2 Procedural Interface Without Importing + +(DEPRECATED) You can also access the methods as class methods of +the various packages with and without the C<color> prefix: + + use Color::Calc::WWW(); + + print Color::Calc::WWW::color('FFF'); # prints 'white' + print Color::Calc::WWW::color_invert('FFF'); # prints 'black' + print Color::Calc::html::invert('FFF'); # prints 'black' + +For the main module C<Color::Calc>, you can also add a suffix +C<_I<output_format>> to select the output format: + + use Color::Calc(); + + print Color::Calc::color_html('FFF'); # prints 'white' + print Color::Calc::color_invert_html('FFF'); # prints 'black' + print Color::Calc::invert_hex('FFF'); # prints '000000' -} =head1 SEE ALSO L<Graphics::ColorNames> (required); L<Color::Object> (optional) =head1 AUTHOR Claus A. Färber <perl@faerber.muc.de> =head1 COPYRIGHT -Copyright © 2004 Claus A. Färber All rights reserved. This program -is free software; you can redistribute it and/or modify it under -the same terms as Perl itself. +Copyright © 2004, 2005 Claus A. Färber All rights reserved. This program is +free software; you can redistribute it and/or modify it under the same terms as +Perl itself. =cut 1; diff --git a/Changes b/Changes index b3c2f34..9ac82f5 100644 --- a/Changes +++ b/Changes @@ -1,22 +1,28 @@ Revision history for Perl extension Color::Calc. +0.29_0001 Fri Mar 25 12:00:00 2005 + - added object-orientated interface + - added procedural interface with customisation on import + - added Color::Calc::WWW + - color scheme is now selectable + 0.20 Mon Mar 28 00:00:00 2004 - added Color::Calc::<xxx> modules to select return type - added $Color::Calc::MODE to select return type - return value of xxx_tuple can be used as parameter - <xxx>_html returns color names instead of #RRGGBB if possible - support for Graphics::ColorObject (input/output) - support for PDF::API2::Color (input/output) - fixed import list 0.12 Thu Mar 18 00:00:00 2004 - added xxx_html - should work with perl 5.005 now 0.10 Sun May 04 00:00:00 2003 - added tests - added more functions - some documentation corrections 0.02 Sat Apr 26 00:00:00 2003 - first public release diff --git a/MANIFEST b/MANIFEST index 2934caa..fc68d74 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,21 +1,22 @@ README Changes MANIFEST Makefile.PL Calc.pm Calc/hex.pm Calc/html.pm Calc/tuple.pm Calc/object.pm Calc/pdf.pm t/30_mix.t t/20_hex.t t/21_html.t t/90_Graphics-ColorObject.t t/13_param_2.t t/14_param_3.t t/10_suffixes.t t/00_basic.t t/91_PDF-API2-Color.t t/12_param_1.t t/11_modes.t +META.yml Module meta-data (added by MakeMaker) diff --git a/META.yml b/META.yml new file mode 100644 index 0000000..a7ae86b --- /dev/null +++ b/META.yml @@ -0,0 +1,12 @@ +# http://module-build.sourceforge.net/META-spec.html +#XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX# +name: Color-Calc +version: 0.29_0001 +version_from: Calc.pm +installdirs: site +requires: + Graphics::ColorNames: 0.32 + Params::Validate: 0.75 + +distribution_type: module +generated_by: ExtUtils::MakeMaker version 6.17 diff --git a/Makefile.PL b/Makefile.PL index 1cb49a3..1127e31 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,13 +1,14 @@ use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'Color::Calc', 'VERSION_FROM' => 'Calc.pm', # finds $VERSION 'PREREQ_PM' => { - 'Graphics::ColorNames' => 0.32, + 'Graphics::ColorNames' => 0.32, + 'Params::Validate' => 0.75, }, ($] >= 5.005 ? ## Add these new keywords supported since 5.005 (ABSTRACT_FROM => 'Calc.pm', # retrieve abstract from module AUTHOR => 'Claus Färber <perl@faerber.muc.de>') : ()), ); diff --git a/t/00_basic.t b/t/00_basic.t index d3707c7..7681466 100644 --- a/t/00_basic.t +++ b/t/00_basic.t @@ -1,6 +1,6 @@ -use Test::More tests => 1; -BEGIN { use_ok('Color::Calc') }; -# is(uc(color_contrast_hex('#000000')),'FFFFFF'); -# is(color_contrast_html('#000000'),'white'); -# $Color::Calc::MODE = 'html'; -# is(color('000000'),'black'); +use Test::More tests => 2; + +use_ok('Color::Calc'); + +my $cc = new Color::Calc; +isa_ok($cc, 'Color::Calc');
cfaerber/Graphics-ColorNames-WWW
79b8d12ee64dba7ecc1cbdf4695b142b95297cd7
Color-Calc-0.20a
diff --git a/Calc.pm b/Calc.pm index 897359a..e3524b9 100644 --- a/Calc.pm +++ b/Calc.pm @@ -1,313 +1,477 @@ package Color::Calc; use strict; +use Carp; +use POSIX; + use Graphics::ColorNames qw( hex2tuple tuple2hex ); +use Graphics::ColorNames::HTML; + +our $VERSION = '0.20'; +$VERSION = eval $VERSION; -our $VERSION = 0.12; our $AUTOLOAD; +our $MODE = (); use Exporter; +our @__subs; + +BEGIN { +our @__subs = qw( blend blend_bw bw contrast contrast_bw dark get grey invert +light mix); +sub __suffixes { ($_, $_.'_tuple', $_.'_hex', $_.'_html', $_.'_object', $_.'_pdf') }; + our @ISA = qw(Exporter); -our @EXPORT = qw( - color_mix color_mix_hex color_mix_html - color_contrast color_contrast_hex color_contrast_html - color_blend color_blend_hex color_blend_html - color_invert color_invert_hex color_invert_html - color_light color_light_hex color_light_html - color_dark color_dark_hex color_dark_html -); +our @EXPORT = map &__suffixes, ('color', map { 'color_'.$_ } @__subs); +} my %ColorNames = (); tie %ColorNames, 'Graphics::ColorNames'; +my %__HTMLColors = (); +{ + my $table = Graphics::ColorNames::HTML::NamesRgbTable(); + %__HTMLColors = map + { ( sprintf('%06x', $$table{$_}) => $_ ) } + grep { $_ ne 'fuscia' } + keys %$table; +}; + =head1 NAME Color::Calc - Simple calculations with RGB colors. =head1 SYNOPSIS use Color::Calc (); my $background = 'green'; - print 'background: ',$background,';'; - print 'border-top: solid 1px #',Color::Calc::light_hex($background),';'; - print 'border-bottom: solid 1px #',Color::Calc::dark_hex($background),';'; - print 'color: #',contrast_hex($background),';'; + print 'background: ',Color::Calc::color_html($background),';'; + print 'border-top: solid 1px ',Color::Calc::light_html($background),';'; + print 'border-bottom: solid 1px ',Color::Calc::dark_html($background),';'; + print 'color: ',contrast_bw_html($background),';'; =head1 DESCRIPTION The C<Color::Calc> module implements simple calculations with RGB -colors. This can be used to create a full color scheme from a few +colors. This can be used to create a full color scheme from a few colors. =head2 Color Input Formats -All of the functions accept colors as parameters in the following formats: +All of the functions accept colors as parameters in the following +formats: =over 4 -=item * +=item * -An arrayref pointing to an array with three elements in the range 0..255 -corresponding to the red, green, and blue component. +An arrayref pointing to an array with three elements in the range +C<0>..C<255> corresponding to the red, green, and blue component. -=item * +=item * -A string containing a hexadecimal RGB value in the form of #RRGGBB or RRGGBB. +A string containing a hexadecimal RGB value in the form +C<#I<RRGGBB>>/C<#I<RGB>> or C<I<RGB>>/C<I<RRGGBB>>. =item * A color name accepted by C<Graphics::ColorNames>. =item * -A C<Color::Object> reference. +A C<PDF::API2::Color> reference. -=back +=item * -Instead of an arrayref, you can also pass a list with three values for -functions that take a single parameter. +A C<Graphics::ColorObject> reference. + +=item * + +The return value of any of the public C<Color::Calc::>* functions, even if it +is a list returned by C<I<xxx>_tuple>. + +=back =head2 Color Output Formats -Each of the functions exists in different variants that provide different output -formats: +C<Color::Calc> can return colors in the following modes: =over 4 -=item * I<function> +=item * tuple Returns a list of three values in the range 0..255. -=item * I<function>_hex +=item * hex Returns a hexadecimal RGB value in the format RRGGBB. -=item * I<function>_html +=item * html + +Returns a value compatible with W3C's HTML and CSS specifications, +i.e. I<#RRGGBB> or one of the sixteen color names. + +=item * pdf + +Returns a C<PDF::API2::Color> reference. The module +C<PDF::API2::Color> must be installed. + +=item * object + +Returns a C<Graphics::ColorObject> reference. The module +C<Graphics::ColorObject> must be installed. + +=back + +You can select the mode using one of the following methods: + +=over 4 + +=item * Add a suffix C<_I<mode>> to the function name: + +Call the function C<mix> as C<mix_hex>, for example. + +=item * Set C<$Color::Calc::MODE>: + +This is a global variable. + +Valid values are 'tuple', 'hex', 'html', 'obj', 'pdf', or 'object' +(the default ist 'tuple' to maintain compatibility with earlier +versions). + +=item * Use a different module + +You can use one of the modules C<Color::Calc::hex>, +C<Color::Calc::html>, C<Color::Calc::tulpe> C<Color::Calc::obj>, +C<Color::Calc::pdf>, or C<Color::Calc::object>. + +The function C<Color::Calc::html::mix> is equivalent to +C<Color::Calc::mix_html>, for example. -Returns a value compatible with W3C's HTML and CSS specifications, typically #RRGGBB. +These modules export their functions with the C<color_> prefix by +default, just as the main module. =back =head2 Accessing the Functions The functions can be accessed in several ways: =over 4 =item * The functions are exported by default with a prefix of C<color_>: use Color::Calc; print color_dark_hex('#FFFFFF'); # returns '808080'; =item * -If you prefer not to import the functions, you can call them by specifying the -package name: +If you prefer not to import the functions, you can call them by +specifying the package name; in this case, you may leave out the +prefix C<color_>: use Color::Calc (); print Color::Calc::dark_hex('#FFFFFF'); # returns '808080'; + print Color::Calc::color_dark_hex('#FFFFFF'); # returns '808080'; =back -Note that I<function> and color_I<function> are fully equivalent except that -only color_I<function> is exported by default. +Note that I<function> and color_I<function> are fully equivalent +except that only color_I<function> is exported by default. =head2 Available Functions The following functions are available: =over 4 -=item * get($color) +=item * color($color) + +=item * color_get($color) Returns the color as-is (but in the format specified). This -function is mostly used internally, but it's available for -completeness. +function can be used for color format conversion/normalisation. =cut -sub get -{ - if( $#_ == 2 ) { - return @_; +sub __normtuple_in { + return map { ($_ < 0) ? 0 : (($_ > 255) ? 255 : int($_+.5)) } @_; +} + +sub __normtuple_out { + return map { (length $_) == 3 ? '0'.$_ : $_ } __normtuple_in(@_) +} + +sub __normtuple { + return __normtuple_out(__normtuple_in(@_)); +} + +sub __is_col_val { + return undef unless defined $_[0]; + return undef if $_[0] eq ''; + my ($n,$u) = POSIX::strtod($_[0]); + return undef if $u != 0; + return ($n <= 255) && ($n>= 0); +} + +# Note: Color::Object was supported in versions before 0.2. This +# is kept for compatibility, but no longer documented. +# +# Note: versions before 0.2 allowed calling some functions (those +# with one parameter) with a list instead of an arrayref. This is +# kept for compatibility, but no longer documented. + +sub __get(\@;$) { + my ($p,$q) = @_; + + if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 0 ) { + $$p[0] = $$p[0]->[0]; + } + + if ((ref $$p[0]) eq 'ARRAY' && $#{$$p[0]} == 2 ) { + return __normtuple_in(@{shift @$p}); + } + elsif( UNIVERSAL::isa($$p[0],'Color::Object') || + UNIVERSAL::isa($$p[0],'PDF::API2::Color')) { + return (map { 255 * $_; } (shift(@{$p})->asRGB)); } - elsif( UNIVERSAL::isa($_[0],'ARRAY') && $#{$_[0]} == 2 ) { - return @{$_[0]}; + elsif( UNIVERSAL::isa($$p[0],'Graphics::ColorObject')) { + return (shift(@{$p})->as_RGB255()); } - elsif( UNIVERSAL::isa($_[0],'Color::Object') ) { - return map { $_*=255;$_; } ($_[0]->asRGB); + elsif( $#$p >= (2 + ($q||0)) && + __is_col_val($$p[0]) && + __is_col_val($$p[1]) && + __is_col_val($$p[2])) { + return (splice @$p, 0, 3); + } + elsif( $$p[0] =~ m/^#?([0-9A-F])([0-9A-F])([0-9A-F])$/i ) { + shift @$p; + return (map { hex($_) * 17 } ($1,$2,$3)); + } + elsif( $$p[0] =~ m/^#?([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])([0-9A-F][0-9A-F])$/i ) { + shift @$p; + return (map { hex($_) } ($1,$2,$3)); } else { - return hex2tuple( $ColorNames{$_[0]} ); + my $col = $ColorNames{$$p[0]}; + if($col) { + shift @$p; + return hex2tuple($col); + } else { + carp("Invalid color name '$$p[0]'"); + return undef; + } } } -=item * mix($color1, $color2, $alpha) +sub get_tuple { return __normtuple_out(__get(@_)); } +*color_tuple = \&get_tuple; -Returns a color that is the mixture of $color1 and $color2. +=item * color_invert($color) -The optional $alpha parameter can be a value between 0.0 (use -$color1 only) and 1.0 (use $color2 only), the default is 0.5. +Returns the inverse of $color. =cut -sub mix { - my @c1 = get(shift); - my @c2 = get(shift); - my $alpha = shift; $alpha = 0.5 unless defined $alpha; - - return( - ($c1[0] + ($c2[0]-$c1[0])*$alpha), - ($c1[1] + ($c2[1]-$c1[1])*$alpha), - ($c1[2] + ($c2[2]-$c1[2])*$alpha) ); +sub invert_tuple { + return __normtuple_out(map { 255 - $_ } __get(@_)); } -=item * contrast($color) - -Returns a color that has the highest possible contrast to the -input color. +=item * color_bw($color) +=item * color_grey($color) -This is done by setting the red, green, and blue values to 0 if -the corresponding value in the input is >= 128 and to 255 -otherwise. +Converts $color to greyscale. =cut -sub contrast { - return map { $_>=0x80 ? 0 : 255 } get(@_); +sub bw_tuple { + my @c = __get(@_); + my $g = $c[0]*.3 + $c[1]*.59 + $c[2]*.11; + return __normtuple($g,$g,$g); } -=item * blend($color,$alpha) +*grey_tuple = \&bw_tuple; +*gray_tuple = \&bw_tuple; -Returns a color that blends into the background by using less -contrast, i.e. it returns mix($color,contrast($color),$alpha). +=item * color_mix($color1, $color2 [, $alpha]) -The $alpha parameter is optional. +Returns a color that is the mixture of $color1 and $color2. + +The optional $alpha parameter can be a value between 0.0 (use $color1 +only) and 1.0 (use $color2 only), the default is 0.5. =cut -sub blend { - return mix($_[0],[contrast($_[0])],$_[1]); +sub mix_tuple { + my @c1 = (__get @_,1); + my @c2 = (__get @_); + my $alpha = shift(@_); $alpha = 0.5 unless defined $alpha; + + return __normtuple( + ($c1[0] + ($c2[0]-$c1[0])*$alpha), + ($c1[1] + ($c2[1]-$c1[1])*$alpha), + ($c1[2] + ($c2[2]-$c1[2])*$alpha) ); } -=item * invert($color) +=item * color_light($color [, $alpha]) -Returns the inverse color. +Returns a lighter version of $color, i.e. returns +mix($color,[255,255,255],$alpha); + +The optional $alpha parameter can be a value between 0.0 (use $color +only) and 1.0 (use 'white' only), the default is 0.5. =cut -sub invert { - return map { 255 - $_ } get(@_); +sub light_tuple { + return mix_tuple([__get @_],[255,255,255],shift); } -=item * light($color,$alpha) +=item * color_dark($color [, $alpha]) -Returns a lighter version of $color, i.e. returns -mix($color,'FFFFFF',$alpha); +Returns a darker version of $color, i.e. returns +mix($color,[0,0,0],$alpha); -The $alpha parameter is optional. +The optional $alpha parameter can be a value between 0.0 (use $color +only) and 1.0 (use 'black' only), the default is 0.5. =cut -sub light { - return mix($_[0],'FFFFFF',$_[1]); +sub dark_tuple { + return mix_tuple([__get @_],[0,0,0],shift); } -=item * dark($color) +=item * color_contrast($color [, $cut]) -Returns a darker version of $color, i.e. returns -mix($color,'000000',$alpha); +Returns a color that has the highest possible contrast to the input +color. + +This is done by setting the red, green, and blue values to 0 if the +corresponding value in the input is above C<($cut * 255)> and to 255 otherwise. + +The default for C<$cut> is .5, representing a cutoff between 127 and 128. =cut -sub dark { - return mix($_[0],'000000',$_[1]); +sub contrast_tuple { + my @rgb = __get @_; + my $cut = (shift || .5) * 255; + return map { $_ >= $cut ? 0 : '0255' } @rgb; } -=item * grey($color) +=item * color_contrast_bw($color [, $cut]) -Converts $color to greyscale. +Returns black or white, whichever has the higher contrast to $color. + +This is done by setting returning black if the grey value of $color is above +C<($cut * 255)> and white otherwise. + +The default for C<$cut> is .5, representing a cutoff between 127 and 128. =cut -sub grey { - my @c = get(@_); - my $g = ($c[0] + $c[1] + $c[2]) / 3; - return ($g,$g,$g); +sub contrast_bw_tuple { + return contrast_tuple([grey_tuple(@_)], shift); } -=item * contrast_bw($color) +=item * color_blend($color [, $alpha]) -Returns black or white, whichever has the higher contrast to $color. +Returns a color that blends into the background, i.e. it returns +mix($color,contrast($color),$alpha). + +The optional $alpha parameter can be a value between 0.0 (use $color +only) and 1.0 (use C<contrast($color)> only), the default is 0.5. + +The idea is that C<$color> is the foreground color, so C<contrast($color)> is +similar to the background color. Mixing them returns a color somewhere between +them. +You might want to use mix($color, $background, $alpha) instead if you know the +real background color. =cut -sub contrast_bw { - return contrast(grey(@_)); +sub blend_tuple { + my @c1 = __get @_; + return mix_tuple(\@c1,[contrast(\@c1)],shift); } -=item * blend_bw($color,$alpha) +=item * color_blend_bw($color [, $alpha]) Returns a mix of $color and black or white, whichever has the higher contrast to $color. -sub blend_bw { - return mix($_[0],[contrast_bw($_[0])],$_[1]); -} +The optional $alpha parameter can be a value between 0.0 (use $color +only) and 1.0 (use black/white only), the default is 0.5. =back =cut -sub AUTOLOAD -{ - { - no strict 'refs'; - - if($AUTOLOAD =~ m/(.*)_hex$/) { - my $name = $1; - *$AUTOLOAD = sub { - return tuple2hex(&$name(@_)); - }; - goto &$AUTOLOAD; - } - - if($AUTOLOAD =~ m/(.*)_html$/) { - my $name = $1; - *$AUTOLOAD = sub { - return '#'.tuple2hex(&$name(@_)); - }; - goto &$AUTOLOAD; - } +sub blend_bw_tuple { + my @c = __get @_; + return mix_tuple(\@c,[contrast_bw(\@c)],shift); +} - elsif($AUTOLOAD =~ m/^(.*::)colou?r_(.*)$/) { - my $name = $1.$2; - *$AUTOLOAD = \&$name; - goto &$AUTOLOAD; - } - } +BEGIN { + +foreach my $sub (('color',@__subs)) { + no strict 'refs'; + my $name = $sub.'_tuple'; + + my $hex = $sub.'_hex'; + *$hex = sub { return tuple2hex(&$name(@_)); }; + + my $html = $sub.'_html'; + *$html = sub { + my $col = lc(tuple2hex(&$name(@_))); + return $__HTMLColors{$col} || '#'.$col; + }; + + my $obj = $sub.'_object'; + *$obj = sub { + eval { require Graphics::ColorObject; }; + return Graphics::ColorObject->new_RGB255( [&$name(@_)] ); + }; + + my $pdf = $sub.'_pdf'; + *$pdf = sub { + eval { require PDF::API2::Color; }; + return PDF::API2::Color->newRGB( map { $_ / 255 } (&$name(@_))); + }; + + *$sub = sub { + my $name = $sub.'_'.(lc($MODE || 'tuple')); + return (&$name(@_)); + }; } -1; +foreach my $sub ( map &__suffixes, @__subs ) +{ + no strict 'refs'; + my $csub = "color_$sub"; + *$csub = \&$sub; +}; -__END__ +} =head1 SEE ALSO -L<Graphics::ColorNames> -L<Color::Object> +L<Graphics::ColorNames> (required); +L<Color::Object> (optional) =head1 AUTHOR Claus A. Färber <perl@faerber.muc.de> =head1 COPYRIGHT -Copyright © 2003 Claus A. Färber All rights reserved. This program +Copyright © 2004 Claus A. Färber All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut + +1; diff --git a/Calc/hex.pm b/Calc/hex.pm new file mode 100644 index 0000000..a3c59ee --- /dev/null +++ b/Calc/hex.pm @@ -0,0 +1,23 @@ +package Color::Calc::hex; + +use strict; +use Carp; + +use Exporter; +use Color::Calc(); + +our @ISA = qw(Exporter); +our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); + +*color = \&Color::Calc::color_hex; + +foreach my $sub (@Color::Calc::__subs) { + my $su1 = 'color_'.$sub; + my $dst = 'Color::Calc::'.$sub.'_hex'; + + no strict 'refs'; + *$sub = \&$dst; + *$su1 = \&$dst; +}; + +1; diff --git a/Calc/html.pm b/Calc/html.pm new file mode 100644 index 0000000..f0daa19 --- /dev/null +++ b/Calc/html.pm @@ -0,0 +1,23 @@ +package Color::Calc::html; + +use strict; +use Carp; + +use Exporter; +use Color::Calc(); + +our @ISA = qw(Exporter); +our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); + +*color = \&Color::Calc::color_html; + +foreach my $sub (@Color::Calc::__subs) { + my $su1 = 'color_'.$sub; + my $dst = 'Color::Calc::'.$sub.'_html'; + + no strict 'refs'; + *$sub = \&$dst; + *$su1 = \&$dst; +}; + +1; diff --git a/Calc/object.pm b/Calc/object.pm new file mode 100644 index 0000000..779aced --- /dev/null +++ b/Calc/object.pm @@ -0,0 +1,24 @@ +package Color::Calc::object; +use Graphics::ColorObject; + +use strict; +use Carp; + +use Exporter; +use Color::Calc(); + +our @ISA = qw(Exporter); +our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); + +*color = \&Color::Calc::color_object; + +foreach my $sub (@Color::Calc::__subs) { + my $su1 = 'color_'.$sub; + my $dst = 'Color::Calc::'.$sub.'_object'; + + no strict 'refs'; + *$sub = \&$dst; + *$su1 = \&$dst; +}; + +1; diff --git a/Calc/pdf.pm b/Calc/pdf.pm new file mode 100644 index 0000000..7072b8d --- /dev/null +++ b/Calc/pdf.pm @@ -0,0 +1,24 @@ +package Color::Calc::pdf; +use PDF::API2::Color; + +use strict; +use Carp; + +use Exporter; +use Color::Calc(); + +our @ISA = qw(Exporter); +our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); + +*color = \&Color::Calc::color_pdf; + +foreach my $sub (@Color::Calc::__subs) { + my $su1 = 'color_'.$sub; + my $dst = 'Color::Calc::'.$sub.'_pdf'; + + no strict 'refs'; + *$sub = \&$dst; + *$su1 = \&$dst; +}; + +1; diff --git a/Calc/tuple.pm b/Calc/tuple.pm new file mode 100644 index 0000000..c04f54b --- /dev/null +++ b/Calc/tuple.pm @@ -0,0 +1,23 @@ +package Color::Calc::tuple; + +use strict; +use Carp; + +use Exporter; +use Color::Calc(); + +our @ISA = qw(Exporter); +our @EXPORT = ('color', map { 'color_'.$_ } @Color::Calc::__subs); + +*color = \&Color::Calc::color_tuple; + +foreach my $sub (@Color::Calc::__subs) { + my $su1 = 'color_'.$sub; + my $dst = 'Color::Calc::'.$sub.'_tuple'; + + no strict 'refs'; + *$sub = \&$dst; + *$su1 = \&$dst; +}; + +1; diff --git a/Changes b/Changes index 502ca4e..b3c2f34 100644 --- a/Changes +++ b/Changes @@ -1,13 +1,22 @@ Revision history for Perl extension Color::Calc. +0.20 Mon Mar 28 00:00:00 2004 + - added Color::Calc::<xxx> modules to select return type + - added $Color::Calc::MODE to select return type + - return value of xxx_tuple can be used as parameter + - <xxx>_html returns color names instead of #RRGGBB if possible + - support for Graphics::ColorObject (input/output) + - support for PDF::API2::Color (input/output) + - fixed import list + 0.12 Thu Mar 18 00:00:00 2004 - added xxx_html - should work with perl 5.005 now 0.10 Sun May 04 00:00:00 2003 - added tests - added more functions - some documentation corrections 0.02 Sat Apr 26 00:00:00 2003 - first public release diff --git a/MANIFEST b/MANIFEST index d717794..2934caa 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,6 +1,21 @@ README -MANIFEST Changes -Calc.pm +MANIFEST Makefile.PL -t/1use.t +Calc.pm +Calc/hex.pm +Calc/html.pm +Calc/tuple.pm +Calc/object.pm +Calc/pdf.pm +t/30_mix.t +t/20_hex.t +t/21_html.t +t/90_Graphics-ColorObject.t +t/13_param_2.t +t/14_param_3.t +t/10_suffixes.t +t/00_basic.t +t/91_PDF-API2-Color.t +t/12_param_1.t +t/11_modes.t diff --git a/Makefile.PL b/Makefile.PL index f0b8373..1cb49a3 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,14 +1,13 @@ -use 5.005; use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'Color::Calc', 'VERSION_FROM' => 'Calc.pm', # finds $VERSION 'PREREQ_PM' => { 'Graphics::ColorNames' => 0.32, }, ($] >= 5.005 ? ## Add these new keywords supported since 5.005 (ABSTRACT_FROM => 'Calc.pm', # retrieve abstract from module AUTHOR => 'Claus Färber <perl@faerber.muc.de>') : ()), ); diff --git a/README b/README index 0ac9c6c..60892c8 100644 --- a/README +++ b/README @@ -1,31 +1,37 @@ -Color::Calc 0.10 -=========== +Color::Calc 0.2 +=============== The "Color::Calc" module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. The module is useful for CGI (or embedded perl) programmes that create HTML or CSS output. INSTALLATION To install this module type the following: perl Makefile.PL make make test make install DEPENDENCIES This module requires these other modules and libraries: Graphics::ColorNames +The following modules are optional: + + Color::Object + PDF::API2::Color + Graphics::ColorObject + COPYRIGHT AND LICENCE -Copyright © 2003 Claus A. Färber +Copyright © 2004 Claus A. Färber This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/t/00_basic.t b/t/00_basic.t new file mode 100644 index 0000000..d3707c7 --- /dev/null +++ b/t/00_basic.t @@ -0,0 +1,6 @@ +use Test::More tests => 1; +BEGIN { use_ok('Color::Calc') }; +# is(uc(color_contrast_hex('#000000')),'FFFFFF'); +# is(color_contrast_html('#000000'),'white'); +# $Color::Calc::MODE = 'html'; +# is(color('000000'),'black'); diff --git a/t/10_suffixes.t b/t/10_suffixes.t new file mode 100644 index 0000000..54f5f07 --- /dev/null +++ b/t/10_suffixes.t @@ -0,0 +1,6 @@ +use Test::More tests => 3; +use Color::Calc; + +is((join '-', color_tuple('red')), '0255-0-0'); +is(color_hex([255,0,0]), 'ff0000'); +is(color_html([255,0,0]), 'red'); diff --git a/t/11_modes.t b/t/11_modes.t new file mode 100644 index 0000000..809774f --- /dev/null +++ b/t/11_modes.t @@ -0,0 +1,13 @@ +use Test::More tests => 4; +use Color::Calc; + +is((join '-', color('red')), '0255-0-0'); + +$Color::Calc::MODE = 'tuple'; +is((join '-', color('red')), '0255-0-0'); + +$Color::Calc::MODE = 'hex'; +is(color('red'), 'ff0000'); + +$Color::Calc::MODE = 'html'; +is(color('red'), 'red'); diff --git a/t/12_param_1.t b/t/12_param_1.t new file mode 100644 index 0000000..1e69bf6 --- /dev/null +++ b/t/12_param_1.t @@ -0,0 +1,12 @@ +use Test::More tests => 7; +use Color::Calc; + +$Color::Calc::MODE = 'hex'; + +is(color('red'), 'ff0000'); +is(color([255,0,0]), 'ff0000'); +is(color('F00'), 'ff0000'); +is(color('255','0','0'),'ff0000'); +is(color('FF0000'), 'ff0000'); +is(color('#F00'), 'ff0000'); +is(color('#FF0000'), 'ff0000'); diff --git a/t/13_param_2.t b/t/13_param_2.t new file mode 100644 index 0000000..693b049 --- /dev/null +++ b/t/13_param_2.t @@ -0,0 +1,12 @@ +use Test::More tests => 4; +use Color::Calc; + +$Color::Calc::MODE = 'hex'; + +# R G B ALPHA +is(color_dark('255','000','000', ),'800000'); +is(color_dark('255','000','000', .4 ),'990000'); + +# RGB ALPHA +is(color_dark('FF0', ),'808000'); +is(color_dark('FF0', .4 ),'999900'); diff --git a/t/14_param_3.t b/t/14_param_3.t new file mode 100644 index 0000000..6fa8359 --- /dev/null +++ b/t/14_param_3.t @@ -0,0 +1,14 @@ +use Test::More tests => 5; +use Color::Calc; + +$Color::Calc::MODE = 'hex'; + +# R G B RGB ALPHA +is(color_mix('255','000','000','000' ),'800000'); +is(color_mix('255','000','000','000', .4 ),'990000'); +# RGB R G B ALPHA +is(color_mix('FF0','000','000','000', ),'808000'); +is(color_mix('FF0','000','000','000', .4 ),'999900'); +# RGB RGB ALPHA +is(color_mix('255','000','000' ),'225555'); + diff --git a/t/20_hex.t b/t/20_hex.t new file mode 100644 index 0000000..8ec5ef1 --- /dev/null +++ b/t/20_hex.t @@ -0,0 +1,9 @@ +use Test::More tests => 6; +use Color::Calc::hex; + +is(color('red'), 'ff0000'); +is(color([255,0,0]), 'ff0000'); +is(color('F00'), 'ff0000'); +is(color('FF0000'), 'ff0000'); +is(color('#F00'), 'ff0000'); +is(color('#FF0000'), 'ff0000'); diff --git a/t/21_html.t b/t/21_html.t new file mode 100644 index 0000000..78177da --- /dev/null +++ b/t/21_html.t @@ -0,0 +1,9 @@ +use Test::More tests => 6; +use Color::Calc::html; + +is(color('red'), 'red'); +is(color([255,0,0]), 'red'); +is(color('F00'), 'red'); +is(color('FF0000'), 'red'); +is(color('#F00'), 'red'); +is(color('#FF0000'), 'red'); diff --git a/t/30_mix.t b/t/30_mix.t new file mode 100644 index 0000000..6d08ecf --- /dev/null +++ b/t/30_mix.t @@ -0,0 +1,16 @@ +use Test::More tests => 10; +use Color::Calc::hex; + +is(color_mix('black','white'), '808080'); +is(color_mix('black','white',0.25), '404040'); + +is(color_light('white'), 'ffffff'); +is(color_light('black'), '808080'); +is(color_light('black',0.25), '404040'); + +is(color_dark('black'), '000000'); +is(color_dark('white'), '808080'); +is(color_dark('white',0.25), 'bfbfbf'); + +is(color_dark('CCCCCC'), '666666'); +is(color_light('CCCCCC'), 'e6e6e6'); diff --git a/t/90_Graphics-ColorObject.t b/t/90_Graphics-ColorObject.t new file mode 100644 index 0000000..71dd11a --- /dev/null +++ b/t/90_Graphics-ColorObject.t @@ -0,0 +1,10 @@ +use Test::More tests => 2; +use Color::Calc; + +SKIP: { + eval { require Graphics::ColorObject; }; + skip "Graphics::ColorObject not installed", 2 if $@; + + is(color_object('red')->as_RGBhex, 'FF0000'); + is(color_mix_object('red','blue')->as_RGBhex, '808000'); +}; diff --git a/t/91_PDF-API2-Color.t b/t/91_PDF-API2-Color.t new file mode 100644 index 0000000..90036c1 --- /dev/null +++ b/t/91_PDF-API2-Color.t @@ -0,0 +1,12 @@ +use Test::More tests => 2; +use Color::Calc; + +SKIP: { + +no warnings 'redefine'; + eval { require PDF::API2::Color; }; + skip "PDF::API2::Color not installed", 2 if $@; + + is(color_pdf('red')->asHex, '#FF0000'); + is(color_mix_pdf('red','blue')->asHex, '#800080'); +};
cfaerber/Graphics-ColorNames-WWW
a41f32be59073b616dca774191d04dd94f0e9aa7
Color-Calc-0.12
diff --git a/Calc.pm b/Calc.pm index e85387d..897359a 100644 --- a/Calc.pm +++ b/Calc.pm @@ -1,313 +1,313 @@ package Color::Calc; use strict; use Graphics::ColorNames qw( hex2tuple tuple2hex ); -our $VERSION = 0.11; +our $VERSION = 0.12; our $AUTOLOAD; use Exporter; our @ISA = qw(Exporter); our @EXPORT = qw( color_mix color_mix_hex color_mix_html color_contrast color_contrast_hex color_contrast_html color_blend color_blend_hex color_blend_html color_invert color_invert_hex color_invert_html color_light color_light_hex color_light_html color_dark color_dark_hex color_dark_html ); my %ColorNames = (); tie %ColorNames, 'Graphics::ColorNames'; =head1 NAME Color::Calc - Simple calculations with RGB colors. =head1 SYNOPSIS use Color::Calc (); my $background = 'green'; print 'background: ',$background,';'; print 'border-top: solid 1px #',Color::Calc::light_hex($background),';'; print 'border-bottom: solid 1px #',Color::Calc::dark_hex($background),';'; print 'color: #',contrast_hex($background),';'; =head1 DESCRIPTION The C<Color::Calc> module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. =head2 Color Input Formats All of the functions accept colors as parameters in the following formats: =over 4 =item * An arrayref pointing to an array with three elements in the range 0..255 corresponding to the red, green, and blue component. =item * A string containing a hexadecimal RGB value in the form of #RRGGBB or RRGGBB. =item * A color name accepted by C<Graphics::ColorNames>. =item * A C<Color::Object> reference. =back Instead of an arrayref, you can also pass a list with three values for functions that take a single parameter. =head2 Color Output Formats Each of the functions exists in different variants that provide different output formats: =over 4 =item * I<function> Returns a list of three values in the range 0..255. =item * I<function>_hex Returns a hexadecimal RGB value in the format RRGGBB. =item * I<function>_html Returns a value compatible with W3C's HTML and CSS specifications, typically #RRGGBB. =back =head2 Accessing the Functions The functions can be accessed in several ways: =over 4 =item * The functions are exported by default with a prefix of C<color_>: use Color::Calc; print color_dark_hex('#FFFFFF'); # returns '808080'; =item * If you prefer not to import the functions, you can call them by specifying the package name: use Color::Calc (); print Color::Calc::dark_hex('#FFFFFF'); # returns '808080'; =back Note that I<function> and color_I<function> are fully equivalent except that only color_I<function> is exported by default. =head2 Available Functions The following functions are available: =over 4 =item * get($color) Returns the color as-is (but in the format specified). This function is mostly used internally, but it's available for completeness. =cut sub get { if( $#_ == 2 ) { return @_; } elsif( UNIVERSAL::isa($_[0],'ARRAY') && $#{$_[0]} == 2 ) { return @{$_[0]}; } elsif( UNIVERSAL::isa($_[0],'Color::Object') ) { return map { $_*=255;$_; } ($_[0]->asRGB); } else { return hex2tuple( $ColorNames{$_[0]} ); } } =item * mix($color1, $color2, $alpha) Returns a color that is the mixture of $color1 and $color2. The optional $alpha parameter can be a value between 0.0 (use $color1 only) and 1.0 (use $color2 only), the default is 0.5. =cut sub mix { my @c1 = get(shift); my @c2 = get(shift); my $alpha = shift; $alpha = 0.5 unless defined $alpha; return( ($c1[0] + ($c2[0]-$c1[0])*$alpha), ($c1[1] + ($c2[1]-$c1[1])*$alpha), ($c1[2] + ($c2[2]-$c1[2])*$alpha) ); } =item * contrast($color) Returns a color that has the highest possible contrast to the input color. This is done by setting the red, green, and blue values to 0 if the corresponding value in the input is >= 128 and to 255 otherwise. =cut sub contrast { return map { $_>=0x80 ? 0 : 255 } get(@_); } =item * blend($color,$alpha) Returns a color that blends into the background by using less contrast, i.e. it returns mix($color,contrast($color),$alpha). The $alpha parameter is optional. =cut sub blend { return mix($_[0],[contrast($_[0])],$_[1]); } =item * invert($color) Returns the inverse color. =cut sub invert { return map { 255 - $_ } get(@_); } =item * light($color,$alpha) Returns a lighter version of $color, i.e. returns mix($color,'FFFFFF',$alpha); The $alpha parameter is optional. =cut sub light { return mix($_[0],'FFFFFF',$_[1]); } =item * dark($color) Returns a darker version of $color, i.e. returns mix($color,'000000',$alpha); =cut sub dark { return mix($_[0],'000000',$_[1]); } =item * grey($color) Converts $color to greyscale. =cut sub grey { my @c = get(@_); my $g = ($c[0] + $c[1] + $c[2]) / 3; return ($g,$g,$g); } =item * contrast_bw($color) Returns black or white, whichever has the higher contrast to $color. =cut sub contrast_bw { return contrast(grey(@_)); } =item * blend_bw($color,$alpha) Returns a mix of $color and black or white, whichever has the higher contrast to $color. sub blend_bw { return mix($_[0],[contrast_bw($_[0])],$_[1]); } =back =cut sub AUTOLOAD { { no strict 'refs'; if($AUTOLOAD =~ m/(.*)_hex$/) { my $name = $1; *$AUTOLOAD = sub { return tuple2hex(&$name(@_)); }; goto &$AUTOLOAD; } - if($AUTOLOAD =~ m/(.*)_hex$/) { + if($AUTOLOAD =~ m/(.*)_html$/) { my $name = $1; *$AUTOLOAD = sub { return '#'.tuple2hex(&$name(@_)); }; goto &$AUTOLOAD; } elsif($AUTOLOAD =~ m/^(.*::)colou?r_(.*)$/) { my $name = $1.$2; *$AUTOLOAD = \&$name; goto &$AUTOLOAD; } } } 1; __END__ =head1 SEE ALSO L<Graphics::ColorNames> L<Color::Object> =head1 AUTHOR Claus A. Färber <perl@faerber.muc.de> =head1 COPYRIGHT Copyright © 2003 Claus A. Färber All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/Changes b/Changes index 576ec2a..502ca4e 100644 --- a/Changes +++ b/Changes @@ -1,13 +1,13 @@ Revision history for Perl extension Color::Calc. -0.11 Thu Mar 18 00:00:00 2004 +0.12 Thu Mar 18 00:00:00 2004 - added xxx_html - should work with perl 5.005 now 0.10 Sun May 04 00:00:00 2003 - added tests - added more functions - some documentation corrections 0.02 Sat Apr 26 00:00:00 2003 - first public release diff --git a/t/1use.t b/t/1use.t index 78c0031..4e392d0 100644 --- a/t/1use.t +++ b/t/1use.t @@ -1,6 +1,4 @@ -use Test::More tests => 2; -BEGIN { - use_ok('Color::Calc') -}; - +use Test::More tests => 3; +BEGIN { use_ok('Color::Calc') }; is(uc(color_contrast_hex('#000000')),'FFFFFF'); +is(uc(color_contrast_html('#000000')),'#FFFFFF');
cfaerber/Graphics-ColorNames-WWW
8a5d6e99082793cfb78ae698ea637ad01805aca1
Color-Calc-0.11
diff --git a/Calc.pm b/Calc.pm index 74197b8..e85387d 100644 --- a/Calc.pm +++ b/Calc.pm @@ -1,301 +1,313 @@ package Color::Calc; use strict; use Graphics::ColorNames qw( hex2tuple tuple2hex ); -our $VERSION = 0.10; +our $VERSION = 0.11; our $AUTOLOAD; use Exporter; our @ISA = qw(Exporter); our @EXPORT = qw( - color_mix color_mix_hex - color_contrast color_contrast_hex - color_blend color_blend_hex - color_invert color_invert_hex - color_light color_light_hex - color_dark color_dark_hex + color_mix color_mix_hex color_mix_html + color_contrast color_contrast_hex color_contrast_html + color_blend color_blend_hex color_blend_html + color_invert color_invert_hex color_invert_html + color_light color_light_hex color_light_html + color_dark color_dark_hex color_dark_html ); my %ColorNames = (); tie %ColorNames, 'Graphics::ColorNames'; =head1 NAME Color::Calc - Simple calculations with RGB colors. =head1 SYNOPSIS use Color::Calc (); my $background = 'green'; print 'background: ',$background,';'; print 'border-top: solid 1px #',Color::Calc::light_hex($background),';'; print 'border-bottom: solid 1px #',Color::Calc::dark_hex($background),';'; print 'color: #',contrast_hex($background),';'; =head1 DESCRIPTION The C<Color::Calc> module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. =head2 Color Input Formats All of the functions accept colors as parameters in the following formats: =over 4 =item * An arrayref pointing to an array with three elements in the range 0..255 corresponding to the red, green, and blue component. =item * A string containing a hexadecimal RGB value in the form of #RRGGBB or RRGGBB. =item * A color name accepted by C<Graphics::ColorNames>. =item * A C<Color::Object> reference. =back Instead of an arrayref, you can also pass a list with three values for functions that take a single parameter. =head2 Color Output Formats Each of the functions exists in different variants that provide different output formats: =over 4 =item * I<function> Returns a list of three values in the range 0..255. =item * I<function>_hex Returns a hexadecimal RGB value in the format RRGGBB. +=item * I<function>_html + +Returns a value compatible with W3C's HTML and CSS specifications, typically #RRGGBB. + =back =head2 Accessing the Functions The functions can be accessed in several ways: =over 4 =item * The functions are exported by default with a prefix of C<color_>: use Color::Calc; print color_dark_hex('#FFFFFF'); # returns '808080'; =item * If you prefer not to import the functions, you can call them by specifying the package name: use Color::Calc (); print Color::Calc::dark_hex('#FFFFFF'); # returns '808080'; =back Note that I<function> and color_I<function> are fully equivalent except that only color_I<function> is exported by default. =head2 Available Functions The following functions are available: =over 4 =item * get($color) Returns the color as-is (but in the format specified). This function is mostly used internally, but it's available for completeness. =cut sub get { if( $#_ == 2 ) { return @_; } elsif( UNIVERSAL::isa($_[0],'ARRAY') && $#{$_[0]} == 2 ) { return @{$_[0]}; } elsif( UNIVERSAL::isa($_[0],'Color::Object') ) { return map { $_*=255;$_; } ($_[0]->asRGB); } else { return hex2tuple( $ColorNames{$_[0]} ); } } =item * mix($color1, $color2, $alpha) Returns a color that is the mixture of $color1 and $color2. The optional $alpha parameter can be a value between 0.0 (use $color1 only) and 1.0 (use $color2 only), the default is 0.5. =cut sub mix { my @c1 = get(shift); my @c2 = get(shift); my $alpha = shift; $alpha = 0.5 unless defined $alpha; return( ($c1[0] + ($c2[0]-$c1[0])*$alpha), ($c1[1] + ($c2[1]-$c1[1])*$alpha), ($c1[2] + ($c2[2]-$c1[2])*$alpha) ); } =item * contrast($color) Returns a color that has the highest possible contrast to the input color. This is done by setting the red, green, and blue values to 0 if the corresponding value in the input is >= 128 and to 255 otherwise. =cut sub contrast { return map { $_>=0x80 ? 0 : 255 } get(@_); } =item * blend($color,$alpha) Returns a color that blends into the background by using less contrast, i.e. it returns mix($color,contrast($color),$alpha). The $alpha parameter is optional. =cut sub blend { return mix($_[0],[contrast($_[0])],$_[1]); } =item * invert($color) Returns the inverse color. =cut sub invert { return map { 255 - $_ } get(@_); } =item * light($color,$alpha) Returns a lighter version of $color, i.e. returns mix($color,'FFFFFF',$alpha); The $alpha parameter is optional. =cut sub light { return mix($_[0],'FFFFFF',$_[1]); } =item * dark($color) Returns a darker version of $color, i.e. returns mix($color,'000000',$alpha); =cut sub dark { return mix($_[0],'000000',$_[1]); } =item * grey($color) Converts $color to greyscale. =cut sub grey { my @c = get(@_); my $g = ($c[0] + $c[1] + $c[2]) / 3; return ($g,$g,$g); } =item * contrast_bw($color) Returns black or white, whichever has the higher contrast to $color. =cut sub contrast_bw { return contrast(grey(@_)); } =item * blend_bw($color,$alpha) Returns a mix of $color and black or white, whichever has the higher contrast to $color. sub blend_bw { return mix($_[0],[contrast_bw($_[0])],$_[1]); } =back =cut sub AUTOLOAD { { no strict 'refs'; if($AUTOLOAD =~ m/(.*)_hex$/) { my $name = $1; *$AUTOLOAD = sub { return tuple2hex(&$name(@_)); }; goto &$AUTOLOAD; } + if($AUTOLOAD =~ m/(.*)_hex$/) { + my $name = $1; + *$AUTOLOAD = sub { + return '#'.tuple2hex(&$name(@_)); + }; + goto &$AUTOLOAD; + } + elsif($AUTOLOAD =~ m/^(.*::)colou?r_(.*)$/) { my $name = $1.$2; *$AUTOLOAD = \&$name; goto &$AUTOLOAD; } } } 1; __END__ =head1 SEE ALSO L<Graphics::ColorNames> L<Color::Object> =head1 AUTHOR Claus A. Färber <perl@faerber.muc.de> =head1 COPYRIGHT Copyright © 2003 Claus A. Färber All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/Changes b/Changes index 8afdece..576ec2a 100644 --- a/Changes +++ b/Changes @@ -1,9 +1,13 @@ Revision history for Perl extension Color::Calc. +0.11 Thu Mar 18 00:00:00 2004 + - added xxx_html + - should work with perl 5.005 now + 0.10 Sun May 04 00:00:00 2003 - added tests - added more functions - some documentation corrections 0.02 Sat Apr 26 00:00:00 2003 - first public release diff --git a/Makefile.PL b/Makefile.PL index b8b7cc7..f0b8373 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,14 +1,14 @@ -use 5.008; +use 5.005; use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'Color::Calc', 'VERSION_FROM' => 'Calc.pm', # finds $VERSION 'PREREQ_PM' => { 'Graphics::ColorNames' => 0.32, }, ($] >= 5.005 ? ## Add these new keywords supported since 5.005 (ABSTRACT_FROM => 'Calc.pm', # retrieve abstract from module AUTHOR => 'Claus Färber <perl@faerber.muc.de>') : ()), );
cfaerber/Graphics-ColorNames-WWW
d7b32ec542d09095b9e980a732fe341418fb159d
Color-Calc-0.1
diff --git a/Calc.pm b/Calc.pm index 238f932..74197b8 100644 --- a/Calc.pm +++ b/Calc.pm @@ -1,271 +1,301 @@ package Color::Calc; use strict; use Graphics::ColorNames qw( hex2tuple tuple2hex ); -our $VERSION = 0.02; +our $VERSION = 0.10; our $AUTOLOAD; use Exporter; our @ISA = qw(Exporter); our @EXPORT = qw( color_mix color_mix_hex color_contrast color_contrast_hex color_blend color_blend_hex color_invert color_invert_hex color_light color_light_hex color_dark color_dark_hex ); my %ColorNames = (); tie %ColorNames, 'Graphics::ColorNames'; =head1 NAME Color::Calc - Simple calculations with RGB colors. =head1 SYNOPSIS use Color::Calc (); my $background = 'green'; print 'background: ',$background,';'; print 'border-top: solid 1px #',Color::Calc::light_hex($background),';'; print 'border-bottom: solid 1px #',Color::Calc::dark_hex($background),';'; print 'color: #',contrast_hex($background),';'; =head1 DESCRIPTION The C<Color::Calc> module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. =head2 Color Input Formats All of the functions accept colors as parameters in the following formats: =over 4 -=item * +=item * An arrayref pointing to an array with three elements in the range 0..255 corresponding to the red, green, and blue component. -=item * +=item * A string containing a hexadecimal RGB value in the form of #RRGGBB or RRGGBB. -=item * +=item * A color name accepted by C<Graphics::ColorNames>. =item * A C<Color::Object> reference. =back Instead of an arrayref, you can also pass a list with three values for functions that take a single parameter. =head2 Color Output Formats Each of the functions exists in different variants that provide different output formats: =over 4 =item * I<function> Returns a list of three values in the range 0..255. =item * I<function>_hex Returns a hexadecimal RGB value in the format RRGGBB. =back =head2 Accessing the Functions The functions can be accessed in several ways: =over 4 =item * The functions are exported by default with a prefix of C<color_>: use Color::Calc; print color_dark_hex('#FFFFFF'); # returns '808080'; =item * If you prefer not to import the functions, you can call them by specifying the package name: - use Color::Calc () + use Color::Calc (); print Color::Calc::dark_hex('#FFFFFF'); # returns '808080'; =back Note that I<function> and color_I<function> are fully equivalent except that only color_I<function> is exported by default. =head2 Available Functions The following functions are available: =over 4 =item * get($color) Returns the color as-is (but in the format specified). This function is mostly used internally, but it's available for completeness. =cut sub get { if( $#_ == 2 ) { return @_; } elsif( UNIVERSAL::isa($_[0],'ARRAY') && $#{$_[0]} == 2 ) { return @{$_[0]}; } elsif( UNIVERSAL::isa($_[0],'Color::Object') ) { return map { $_*=255;$_; } ($_[0]->asRGB); } else { return hex2tuple( $ColorNames{$_[0]} ); } } =item * mix($color1, $color2, $alpha) -Returns a color that is the mixture of $color1 and $color2. +Returns a color that is the mixture of $color1 and $color2. The optional $alpha parameter can be a value between 0.0 (use $color1 only) and 1.0 (use $color2 only), the default is 0.5. =cut sub mix { my @c1 = get(shift); my @c2 = get(shift); my $alpha = shift; $alpha = 0.5 unless defined $alpha; return( ($c1[0] + ($c2[0]-$c1[0])*$alpha), ($c1[1] + ($c2[1]-$c1[1])*$alpha), ($c1[2] + ($c2[2]-$c1[2])*$alpha) ); } =item * contrast($color) Returns a color that has the highest possible contrast to the input color. This is done by setting the red, green, and blue values to 0 if the corresponding value in the input is >= 128 and to 255 otherwise. =cut sub contrast { return map { $_>=0x80 ? 0 : 255 } get(@_); } =item * blend($color,$alpha) Returns a color that blends into the background by using less contrast, i.e. it returns mix($color,contrast($color),$alpha). The $alpha parameter is optional. =cut sub blend { return mix($_[0],[contrast($_[0])],$_[1]); } =item * invert($color) Returns the inverse color. =cut sub invert { return map { 255 - $_ } get(@_); } =item * light($color,$alpha) Returns a lighter version of $color, i.e. returns mix($color,'FFFFFF',$alpha); The $alpha parameter is optional. =cut sub light { return mix($_[0],'FFFFFF',$_[1]); } -=item * invert($color) - -Returns the inverse color. +=item * dark($color) Returns a darker version of $color, i.e. returns mix($color,'000000',$alpha); =cut sub dark { return mix($_[0],'000000',$_[1]); } +=item * grey($color) + +Converts $color to greyscale. + +=cut + +sub grey { + my @c = get(@_); + my $g = ($c[0] + $c[1] + $c[2]) / 3; + return ($g,$g,$g); +} + +=item * contrast_bw($color) + +Returns black or white, whichever has the higher contrast to $color. + +=cut + +sub contrast_bw { + return contrast(grey(@_)); +} + +=item * blend_bw($color,$alpha) + +Returns a mix of $color and black or white, whichever has the higher contrast +to $color. + +sub blend_bw { + return mix($_[0],[contrast_bw($_[0])],$_[1]); +} + =back =cut -sub AUTOLOAD +sub AUTOLOAD { { no strict 'refs'; if($AUTOLOAD =~ m/(.*)_hex$/) { my $name = $1; *$AUTOLOAD = sub { return tuple2hex(&$name(@_)); }; goto &$AUTOLOAD; } elsif($AUTOLOAD =~ m/^(.*::)colou?r_(.*)$/) { my $name = $1.$2; *$AUTOLOAD = \&$name; goto &$AUTOLOAD; } - - else { - die 'Blubb.'; - } } } 1; __END__ +=head1 SEE ALSO + +L<Graphics::ColorNames> +L<Color::Object> + =head1 AUTHOR Claus A. Färber <perl@faerber.muc.de> =head1 COPYRIGHT Copyright © 2003 Claus A. Färber All rights reserved. This program is free software; you can redistribute it and/or modify it under -the same terms as Perl itself. +the same terms as Perl itself. =cut diff --git a/Changes b/Changes index 5c84f7b..8afdece 100644 --- a/Changes +++ b/Changes @@ -1,4 +1,9 @@ Revision history for Perl extension Color::Calc. +0.10 Sun May 04 00:00:00 2003 + - added tests + - added more functions + - some documentation corrections + 0.02 Sat Apr 26 00:00:00 2003 - first public release diff --git a/MANIFEST b/MANIFEST index d186762..d717794 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,5 +1,6 @@ README -MANIFEST This list of files +MANIFEST Changes Calc.pm Makefile.PL +t/1use.t diff --git a/README b/README index 60a85de..0ac9c6c 100644 --- a/README +++ b/README @@ -1,31 +1,31 @@ -Color::Calc 0.02 +Color::Calc 0.10 =========== The "Color::Calc" module implements simple calculations with RGB colors. This can be used to create a full color scheme from a few colors. The module is useful for CGI (or embedded perl) programmes that create HTML or CSS output. INSTALLATION To install this module type the following: perl Makefile.PL make make test make install DEPENDENCIES This module requires these other modules and libraries: Graphics::ColorNames COPYRIGHT AND LICENCE Copyright © 2003 Claus A. Färber This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/t/1use.t b/t/1use.t new file mode 100644 index 0000000..78c0031 --- /dev/null +++ b/t/1use.t @@ -0,0 +1,6 @@ +use Test::More tests => 2; +BEGIN { + use_ok('Color::Calc') +}; + +is(uc(color_contrast_hex('#000000')),'FFFFFF');
cfaerber/Graphics-ColorNames-WWW
763845b7aedcebad44936173ccd8da303c60d9a9
Color-Calc-0.02
diff --git a/Calc.pm b/Calc.pm new file mode 100644 index 0000000..238f932 --- /dev/null +++ b/Calc.pm @@ -0,0 +1,271 @@ +package Color::Calc; + +use strict; +use Graphics::ColorNames qw( hex2tuple tuple2hex ); + +our $VERSION = 0.02; +our $AUTOLOAD; + +use Exporter; + +our @ISA = qw(Exporter); +our @EXPORT = qw( + color_mix color_mix_hex + color_contrast color_contrast_hex + color_blend color_blend_hex + color_invert color_invert_hex + color_light color_light_hex + color_dark color_dark_hex +); + +my %ColorNames = (); +tie %ColorNames, 'Graphics::ColorNames'; + +=head1 NAME + +Color::Calc - Simple calculations with RGB colors. + +=head1 SYNOPSIS + + use Color::Calc (); + my $background = 'green'; + print 'background: ',$background,';'; + print 'border-top: solid 1px #',Color::Calc::light_hex($background),';'; + print 'border-bottom: solid 1px #',Color::Calc::dark_hex($background),';'; + print 'color: #',contrast_hex($background),';'; + +=head1 DESCRIPTION + +The C<Color::Calc> module implements simple calculations with RGB +colors. This can be used to create a full color scheme from a few +colors. + +=head2 Color Input Formats + +All of the functions accept colors as parameters in the following formats: + +=over 4 + +=item * + +An arrayref pointing to an array with three elements in the range 0..255 +corresponding to the red, green, and blue component. + +=item * + +A string containing a hexadecimal RGB value in the form of #RRGGBB or RRGGBB. + +=item * + +A color name accepted by C<Graphics::ColorNames>. + +=item * + +A C<Color::Object> reference. + +=back + +Instead of an arrayref, you can also pass a list with three values for +functions that take a single parameter. + +=head2 Color Output Formats + +Each of the functions exists in different variants that provide different output +formats: + +=over 4 + +=item * I<function> + +Returns a list of three values in the range 0..255. + +=item * I<function>_hex + +Returns a hexadecimal RGB value in the format RRGGBB. + +=back + +=head2 Accessing the Functions + +The functions can be accessed in several ways: + +=over 4 + +=item * + +The functions are exported by default with a prefix of C<color_>: + + use Color::Calc; + print color_dark_hex('#FFFFFF'); # returns '808080'; + +=item * + +If you prefer not to import the functions, you can call them by specifying the +package name: + + use Color::Calc () + print Color::Calc::dark_hex('#FFFFFF'); # returns '808080'; + +=back + +Note that I<function> and color_I<function> are fully equivalent except that +only color_I<function> is exported by default. + +=head2 Available Functions + +The following functions are available: + +=over 4 + +=item * get($color) + +Returns the color as-is (but in the format specified). This +function is mostly used internally, but it's available for +completeness. + +=cut + +sub get +{ + if( $#_ == 2 ) { + return @_; + } + elsif( UNIVERSAL::isa($_[0],'ARRAY') && $#{$_[0]} == 2 ) { + return @{$_[0]}; + } + elsif( UNIVERSAL::isa($_[0],'Color::Object') ) { + return map { $_*=255;$_; } ($_[0]->asRGB); + } + else { + return hex2tuple( $ColorNames{$_[0]} ); + } +} + +=item * mix($color1, $color2, $alpha) + +Returns a color that is the mixture of $color1 and $color2. + +The optional $alpha parameter can be a value between 0.0 (use +$color1 only) and 1.0 (use $color2 only), the default is 0.5. + +=cut + +sub mix { + my @c1 = get(shift); + my @c2 = get(shift); + my $alpha = shift; $alpha = 0.5 unless defined $alpha; + + return( + ($c1[0] + ($c2[0]-$c1[0])*$alpha), + ($c1[1] + ($c2[1]-$c1[1])*$alpha), + ($c1[2] + ($c2[2]-$c1[2])*$alpha) ); +} + +=item * contrast($color) + +Returns a color that has the highest possible contrast to the +input color. + +This is done by setting the red, green, and blue values to 0 if +the corresponding value in the input is >= 128 and to 255 +otherwise. + +=cut + +sub contrast { + return map { $_>=0x80 ? 0 : 255 } get(@_); +} + +=item * blend($color,$alpha) + +Returns a color that blends into the background by using less +contrast, i.e. it returns mix($color,contrast($color),$alpha). + +The $alpha parameter is optional. + +=cut + +sub blend { + return mix($_[0],[contrast($_[0])],$_[1]); +} + +=item * invert($color) + +Returns the inverse color. + +=cut + +sub invert { + return map { 255 - $_ } get(@_); +} + +=item * light($color,$alpha) + +Returns a lighter version of $color, i.e. returns +mix($color,'FFFFFF',$alpha); + +The $alpha parameter is optional. + +=cut + +sub light { + return mix($_[0],'FFFFFF',$_[1]); +} + +=item * invert($color) + +Returns the inverse color. + +Returns a darker version of $color, i.e. returns +mix($color,'000000',$alpha); + +=cut + +sub dark { + return mix($_[0],'000000',$_[1]); +} + +=back + +=cut + +sub AUTOLOAD +{ + { + no strict 'refs'; + + if($AUTOLOAD =~ m/(.*)_hex$/) { + my $name = $1; + *$AUTOLOAD = sub { + return tuple2hex(&$name(@_)); + }; + goto &$AUTOLOAD; + } + + elsif($AUTOLOAD =~ m/^(.*::)colou?r_(.*)$/) { + my $name = $1.$2; + *$AUTOLOAD = \&$name; + goto &$AUTOLOAD; + } + + else { + die 'Blubb.'; + } + } +} + +1; + +__END__ + +=head1 AUTHOR + +Claus A. Färber <perl@faerber.muc.de> + +=head1 COPYRIGHT + +Copyright © 2003 Claus A. Färber All rights reserved. This program +is free software; you can redistribute it and/or modify it under +the same terms as Perl itself. + +=cut diff --git a/Changes b/Changes new file mode 100644 index 0000000..5c84f7b --- /dev/null +++ b/Changes @@ -0,0 +1,4 @@ +Revision history for Perl extension Color::Calc. + +0.02 Sat Apr 26 00:00:00 2003 + - first public release diff --git a/MANIFEST b/MANIFEST new file mode 100644 index 0000000..d186762 --- /dev/null +++ b/MANIFEST @@ -0,0 +1,5 @@ +README +MANIFEST This list of files +Changes +Calc.pm +Makefile.PL diff --git a/Makefile.PL b/Makefile.PL new file mode 100644 index 0000000..b8b7cc7 --- /dev/null +++ b/Makefile.PL @@ -0,0 +1,14 @@ +use 5.008; +use ExtUtils::MakeMaker; +# See lib/ExtUtils/MakeMaker.pm for details of how to influence +# the contents of the Makefile that is written. +WriteMakefile( + 'NAME' => 'Color::Calc', + 'VERSION_FROM' => 'Calc.pm', # finds $VERSION + 'PREREQ_PM' => { + 'Graphics::ColorNames' => 0.32, + }, + ($] >= 5.005 ? ## Add these new keywords supported since 5.005 + (ABSTRACT_FROM => 'Calc.pm', # retrieve abstract from module + AUTHOR => 'Claus Färber <perl@faerber.muc.de>') : ()), +); diff --git a/README b/README new file mode 100644 index 0000000..60a85de --- /dev/null +++ b/README @@ -0,0 +1,31 @@ +Color::Calc 0.02 +=========== + +The "Color::Calc" module implements simple calculations with RGB +colors. This can be used to create a full color scheme from a few +colors. + +The module is useful for CGI (or embedded perl) programmes that +create HTML or CSS output. + +INSTALLATION + +To install this module type the following: + + perl Makefile.PL + make + make test + make install + +DEPENDENCIES + +This module requires these other modules and libraries: + + Graphics::ColorNames + +COPYRIGHT AND LICENCE + +Copyright © 2003 Claus A. Färber + +This library is free software; you can redistribute it and/or +modify it under the same terms as Perl itself.
jtzemp/base62
6dd5739f830cc92535dbd1b35563fdf1e3cb1d1e
Add more detail to changelog
diff --git a/CHANGELOG.md b/CHANGELOG.md index 283f94d..f23f08d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,26 +1,26 @@ # Base62 changelog ## 2.0.0 (not yet released) -* The `Integer` and `String` extensions are no longer loaded by default. `require 'base62/ext'` to do this. +* The `Integer#base62_encode` and `String#base62_decode` extensions are no longer loaded by default. `require 'base62/ext'` to do this from now on. ## 1.0.0 (2014-01-16) * Lasse Bunk refactored and modernized the whole shebang. ## 0.1.3 (2010-11-24) * Cleaned out the crap that's not needed like hoe and rake tasks and newgem stuff ## 0.1.2 (2010-11-24) * Derrick Camerino added a Gemspec ## 0.1.1 (2009-11-4) * Ruby 1.9 compatible thx to Saadiq Rodgers-King ## 0.1.0 (2008-10-04) * 1 major enhancement: * Initial release
jtzemp/base62
7ac9c3a349c1a7126614dbfeb6fa61658122e3a3
Separate Integer and String extensions into separate file
diff --git a/CHANGELOG.md b/CHANGELOG.md index ec3f96b..283f94d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,22 +1,26 @@ # Base62 changelog +## 2.0.0 (not yet released) + +* The `Integer` and `String` extensions are no longer loaded by default. `require 'base62/ext'` to do this. + ## 1.0.0 (2014-01-16) * Lasse Bunk refactored and modernized the whole shebang. ## 0.1.3 (2010-11-24) * Cleaned out the crap that's not needed like hoe and rake tasks and newgem stuff ## 0.1.2 (2010-11-24) * Derrick Camerino added a Gemspec ## 0.1.1 (2009-11-4) * Ruby 1.9 compatible thx to Saadiq Rodgers-King ## 0.1.0 (2008-10-04) * 1 major enhancement: * Initial release diff --git a/lib/base62.rb b/lib/base62.rb index 245736a..5de790f 100644 --- a/lib/base62.rb +++ b/lib/base62.rb @@ -1,31 +1,29 @@ require "base62/version" -require "base62/string" -require "base62/integer" module Base62 PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a class << self def decode(str) out = 0 str.chars.reverse.each_with_index do |char, index| place = PRIMITIVES.size ** index out += PRIMITIVES.index(char) * place end out end def encode(int) raise ArgumentError, "Can't Base62 encode negative number (#{int} given)" if int < 0 return "0" if int == 0 result = '' while int > 0 result.prepend PRIMITIVES[int % PRIMITIVES.size] int /= PRIMITIVES.size end result end end end \ No newline at end of file diff --git a/lib/base62/ext.rb b/lib/base62/ext.rb new file mode 100644 index 0000000..86f3481 --- /dev/null +++ b/lib/base62/ext.rb @@ -0,0 +1,3 @@ +require "base62" +require "base62/ext/string" +require "base62/ext/integer" \ No newline at end of file diff --git a/lib/base62/integer.rb b/lib/base62/ext/integer.rb similarity index 100% rename from lib/base62/integer.rb rename to lib/base62/ext/integer.rb diff --git a/lib/base62/string.rb b/lib/base62/ext/string.rb similarity index 100% rename from lib/base62/string.rb rename to lib/base62/ext/string.rb diff --git a/test/test_helper.rb b/test/test_helper.rb index dac6a2d..460eb0d 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,2 +1,2 @@ -require "base62" +require "base62/ext" require "test/unit" \ No newline at end of file
jtzemp/base62
24329f637dd1e84d50c02474307824265de5db34
No need to create separate variable
diff --git a/lib/base62.rb b/lib/base62.rb index 156c9bd..245736a 100644 --- a/lib/base62.rb +++ b/lib/base62.rb @@ -1,31 +1,31 @@ require "base62/version" require "base62/string" require "base62/integer" module Base62 PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a class << self def decode(str) out = 0 str.chars.reverse.each_with_index do |char, index| place = PRIMITIVES.size ** index out += PRIMITIVES.index(char) * place end out end def encode(int) raise ArgumentError, "Can't Base62 encode negative number (#{int} given)" if int < 0 return "0" if int == 0 - rem = int result = '' - while rem != 0 - result.prepend PRIMITIVES[rem % PRIMITIVES.size] - rem /= PRIMITIVES.size + while int > 0 + result.prepend PRIMITIVES[int % PRIMITIVES.size] + int /= PRIMITIVES.size end + result end end end \ No newline at end of file
jtzemp/base62
6a8040a4e99aa770b88f540a83bede5f96738e80
Use `prepend` to avoid creating new string objects
diff --git a/lib/base62.rb b/lib/base62.rb index d79401a..156c9bd 100644 --- a/lib/base62.rb +++ b/lib/base62.rb @@ -1,31 +1,31 @@ require "base62/version" require "base62/string" require "base62/integer" module Base62 PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a class << self def decode(str) out = 0 str.chars.reverse.each_with_index do |char, index| place = PRIMITIVES.size ** index out += PRIMITIVES.index(char) * place end out end def encode(int) raise ArgumentError, "Can't Base62 encode negative number (#{int} given)" if int < 0 return "0" if int == 0 rem = int result = '' while rem != 0 - result = PRIMITIVES[rem % PRIMITIVES.size].to_s + result + result.prepend PRIMITIVES[rem % PRIMITIVES.size] rem /= PRIMITIVES.size end result end end end \ No newline at end of file
jtzemp/base62
ce19d6045bab87c08615dcf6b91ee156bd7a5c5e
Raise when trying to encode negative numbers
diff --git a/lib/base62.rb b/lib/base62.rb index 7b2ef22..d79401a 100644 --- a/lib/base62.rb +++ b/lib/base62.rb @@ -1,30 +1,31 @@ require "base62/version" require "base62/string" require "base62/integer" module Base62 PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a class << self def decode(str) out = 0 str.chars.reverse.each_with_index do |char, index| place = PRIMITIVES.size ** index out += PRIMITIVES.index(char) * place end out end def encode(int) + raise ArgumentError, "Can't Base62 encode negative number (#{int} given)" if int < 0 return "0" if int == 0 rem = int result = '' while rem != 0 result = PRIMITIVES[rem % PRIMITIVES.size].to_s + result rem /= PRIMITIVES.size end result end end end \ No newline at end of file diff --git a/test/base62_test.rb b/test/base62_test.rb index 934f228..b4bd33f 100644 --- a/test/base62_test.rb +++ b/test/base62_test.rb @@ -1,52 +1,58 @@ require "test_helper" class Base62Test < Test::Unit::TestCase def test_encode { 0 => "0", 1 => "1", 10 => "A", 100 => "1c", 1231 => "Jr", 3982 => "12E", 10927 => "2qF", 50923 => "DFL", 100292 => "Q5c", 202731 => "qjr", 519278 => "2B5S", 902323 => "3mjb", 1003827 => "4D8l", 2129387 => "8vwx", 52338283 => "3XbZr", 298372887 => "KBwPv", 8237468237 => "8zTZmv", 256352386723872 => "1AnE6bpNA" }.each do |int, base62| assert_equal base62, int.base62_encode end end def test_decode { "" => 0, "0" => 0, "1" => 1, "A" => 10, "1c" => 100, "Jr" => 1231, "12E" => 3982, "2qF" => 10927, "DFL" => 50923, "Q5c" => 100292, "qjr" => 202731, "2B5S" => 519278, "3mjb" => 902323, "4D8l" => 1003827, "8vwx" => 2129387, "3XbZr" => 52338283, "KBwPv" => 298372887, "8zTZmv" => 8237468237, "1AnE6bpNA" => 256352386723872 }.each do |base62, int| assert_equal int, base62.base62_decode end end + + def test_negative_numbers + assert_raises ArgumentError do + -1234.base62_encode + end + end end \ No newline at end of file
jtzemp/base62
36527ceb5b0be89696d827f0c896aeb7f3ac7231
Use `chars` instead of `split`
diff --git a/lib/base62.rb b/lib/base62.rb index d1c24ff..7b2ef22 100644 --- a/lib/base62.rb +++ b/lib/base62.rb @@ -1,30 +1,30 @@ require "base62/version" require "base62/string" require "base62/integer" module Base62 PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a class << self def decode(str) out = 0 - str.split(//).reverse.each_with_index do |char, index| + str.chars.reverse.each_with_index do |char, index| place = PRIMITIVES.size ** index out += PRIMITIVES.index(char) * place end out end def encode(int) return "0" if int == 0 rem = int result = '' while rem != 0 result = PRIMITIVES[rem % PRIMITIVES.size].to_s + result rem /= PRIMITIVES.size end result end end end \ No newline at end of file
jtzemp/base62
0357039151207e094959249771641098fd55b96a
Add Travis-CI
diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..adac848 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,7 @@ +language: ruby +rvm: + - 2.1.0 + - 2.0.0 + - 1.9.3 +notifications: + email: false \ No newline at end of file diff --git a/README.md b/README.md index 0ff0f03..7215097 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,39 @@ +[![Build Status](https://secure.travis-ci.org/jtzemp/base62.png)](http://travis-ci.org/jtzemp/base62) + # Base62 Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. ## Installation ```bash $ gem install base62 ``` ## Usage ```ruby require 'base62' 123.base62_encode # => "1z" "funky".base62_decode # => 619367412 ``` ## Contributing 1. Fork the project 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new pull request ## Thanks * [Lasse Bunk](https://github.com/lassebunk) for totally refactoring everything and bringing it into the modern age. * [Saadiq Rodgers-King](http://github.com/saadiq) for making it work with Ruby 1.9. * [Derrick Camerino](https://github.com/robustdj) for adding a Gemspec and prompting me to clean stuff up. Copyright (c) 2008-2014 [JT Zemp](https://github.com/jtzemp), released under the [MIT License](https://github.com/jtzemp/base62/blob/master/LICENSE.txt)
jtzemp/base62
b6248539fddc7c755b14b4ba1f940cfccd2e5e64
Added CHANGELOG.md entry for v 1.0.0 bump.
diff --git a/CHANGELOG.md b/CHANGELOG.md index d162c40..ec3f96b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,18 +1,22 @@ # Base62 changelog +## 1.0.0 (2014-01-16) + +* Lasse Bunk refactored and modernized the whole shebang. + ## 0.1.3 (2010-11-24) * Cleaned out the crap that's not needed like hoe and rake tasks and newgem stuff ## 0.1.2 (2010-11-24) * Derrick Camerino added a Gemspec ## 0.1.1 (2009-11-4) * Ruby 1.9 compatible thx to Saadiq Rodgers-King ## 0.1.0 (2008-10-04) * 1 major enhancement: * Initial release
jtzemp/base62
2559bdd5dc0eb9fd9512872162b8704a8a014ebe
Version bump 0.1.4 -> 1.0.0
diff --git a/lib/base62/version.rb b/lib/base62/version.rb index 87b363a..4007029 100644 --- a/lib/base62/version.rb +++ b/lib/base62/version.rb @@ -1,3 +1,3 @@ module Base62 - VERSION = "0.1.4" + VERSION = "1.0.0" end
jtzemp/base62
081cdd4f65e671d87fab21d65286982b335c9618
Mad props to Lasse Bunk.
diff --git a/LICENSE.txt b/LICENSE.txt index f3d8bde..af81c98 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,22 +1,22 @@ -Copyright (c) 2008-2013 JT Zemp & Thrive Information Solutions +Copyright (c) 2008-2014 JT Zemp MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 1949c67..0ff0f03 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,37 @@ # Base62 Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. ## Installation ```bash $ gem install base62 ``` ## Usage ```ruby require 'base62' 123.base62_encode # => "1z" "funky".base62_decode # => 619367412 ``` ## Contributing 1. Fork the project 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new pull request ## Thanks +* [Lasse Bunk](https://github.com/lassebunk) for totally refactoring everything and bringing it into the modern age. * [Saadiq Rodgers-King](http://github.com/saadiq) for making it work with Ruby 1.9. * [Derrick Camerino](https://github.com/robustdj) for adding a Gemspec and prompting me to clean stuff up. -Copyright (c) 2008-2013 [JT Zemp](https://github.com/jtzemp) & Thrive Information Solutions, released under the [MIT License](https://github.com/jtzemp/base62/blob/master/LICENSE.txt) \ No newline at end of file +Copyright (c) 2008-2014 [JT Zemp](https://github.com/jtzemp), released under the [MIT License](https://github.com/jtzemp/base62/blob/master/LICENSE.txt) diff --git a/base62.gemspec b/base62.gemspec index cdf2055..aaf7db0 100644 --- a/base62.gemspec +++ b/base62.gemspec @@ -1,25 +1,25 @@ lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'base62/version' Gem::Specification.new do |s| s.name = "base62" s.version = Base62::VERSION - s.authors = ["JT Zemp", "Saadiq Rodgers-King", "Derrick Camerino"] - s.email = ["jtzemp@gmail.com"] + s.authors = ["JT Zemp", "Lasse Bunk", "Saadiq Rodgers-King", "Derrick Camerino"] + s.email = ["jtzemp@gmail.com", "lasse@bunk.io"] s.description = %q{Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer.} s.summary = %q{Monkeypatches Integer and String to allow for base62 encoding and decoding.} s.homepage = "https://github.com/jtzemp/base62" s.license = "MIT" s.files = `git ls-files`.split($/) s.test_files = s.files.grep(%r{^test/}) s.require_paths = ["lib"] s.add_development_dependency "bundler", "~> 1.3" s.add_development_dependency "rake" end
jtzemp/base62
23a7c935c5de8174afd02f94a20804bfdddc7242
Fix typo in license link
diff --git a/README.md b/README.md index 8934736..1949c67 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,36 @@ # Base62 Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. ## Installation ```bash $ gem install base62 ``` ## Usage ```ruby require 'base62' 123.base62_encode # => "1z" "funky".base62_decode # => 619367412 ``` ## Contributing 1. Fork the project 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new pull request ## Thanks * [Saadiq Rodgers-King](http://github.com/saadiq) for making it work with Ruby 1.9. * [Derrick Camerino](https://github.com/robustdj) for adding a Gemspec and prompting me to clean stuff up. -Copyright (c) 2008-2013 [JT Zemp](https://github.com/jtzemp) & Thrive Information Solutions, released under the [MIT License](https://github.com/jtzemp/base62/blog/master/LICENSE.txt) \ No newline at end of file +Copyright (c) 2008-2013 [JT Zemp](https://github.com/jtzemp) & Thrive Information Solutions, released under the [MIT License](https://github.com/jtzemp/base62/blob/master/LICENSE.txt) \ No newline at end of file
jtzemp/base62
cb8085ead132cb01fbdc0a4757c08599547dba7a
Fix indentation in gemspec
diff --git a/base62.gemspec b/base62.gemspec index 0a56cd9..cdf2055 100644 --- a/base62.gemspec +++ b/base62.gemspec @@ -1,25 +1,25 @@ lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'base62/version' Gem::Specification.new do |s| s.name = "base62" s.version = Base62::VERSION s.authors = ["JT Zemp", "Saadiq Rodgers-King", "Derrick Camerino"] s.email = ["jtzemp@gmail.com"] s.description = %q{Base62 monkeypatches Integer to add an Integer#base62_encode - instance method to encode an integer in the character set of - 0-9 + A-Z + a-z. It also monkeypatches String to add - String#base62_decode to take the string and turn it back - into a valid integer.} - s.summary = %q{Monkeypatches Integer and String to allow for base62 encoding and decoding} + instance method to encode an integer in the character set of + 0-9 + A-Z + a-z. It also monkeypatches String to add + String#base62_decode to take the string and turn it back + into a valid integer.} + s.summary = %q{Monkeypatches Integer and String to allow for base62 encoding and decoding.} s.homepage = "https://github.com/jtzemp/base62" s.license = "MIT" s.files = `git ls-files`.split($/) s.test_files = s.files.grep(%r{^test/}) s.require_paths = ["lib"] s.add_development_dependency "bundler", "~> 1.3" s.add_development_dependency "rake" end
jtzemp/base62
8efa4924060a34aa945a48bb0925bfd7b89bb775
Simplify and convert text files into markdown
diff --git a/History.txt b/CHANGELOG.md similarity index 66% rename from History.txt rename to CHANGELOG.md index 2640e97..d162c40 100644 --- a/History.txt +++ b/CHANGELOG.md @@ -1,16 +1,18 @@ -== 0.1.3 2010-11-24 +# Base62 changelog + +## 0.1.3 (2010-11-24) * Cleaned out the crap that's not needed like hoe and rake tasks and newgem stuff -== 0.1.2 2010-11-24 +## 0.1.2 (2010-11-24) * Derrick Camerino added a Gemspec -== 0.1.1 2009-11-4 +## 0.1.1 (2009-11-4) * Ruby 1.9 compatible thx to Saadiq Rodgers-King -== 0.1.0 2008-10-04 +## 0.1.0 (2008-10-04) * 1 major enhancement: * Initial release diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..f3d8bde --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2008-2013 JT Zemp & Thrive Information Solutions + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..8934736 --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +# Base62 + +Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. + +## Installation + +```bash +$ gem install base62 +``` + +## Usage + +```ruby +require 'base62' + +123.base62_encode +# => "1z" + +"funky".base62_decode +# => 619367412 +``` + +## Contributing + +1. Fork the project +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Add feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create new pull request + +## Thanks + +* [Saadiq Rodgers-King](http://github.com/saadiq) for making it work with Ruby 1.9. +* [Derrick Camerino](https://github.com/robustdj) for adding a Gemspec and prompting me to clean stuff up. + +Copyright (c) 2008-2013 [JT Zemp](https://github.com/jtzemp) & Thrive Information Solutions, released under the [MIT License](https://github.com/jtzemp/base62/blog/master/LICENSE.txt) \ No newline at end of file diff --git a/README.rdoc b/README.rdoc deleted file mode 100644 index ef9e88e..0000000 --- a/README.rdoc +++ /dev/null @@ -1,47 +0,0 @@ -== DESCRIPTION: - -Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. - -== INSTALL: - -* sudo gem install base62 - -== USAGE: - - require 'base62' - - 123.base62_encode - => "1z" - - "funky".base62_decode - => 619367412 - -== THANKS: - -* Saadiq Rodgers-King (http://github.com/saadiq) for making it work with Ruby 1.9. -* Derrick Camerino (https://github.com/robustdj) for adding a Gemspec and prompting me to clean stuff up. - -== LICENSE: - -(The MIT License) - -Copyright (c) 2008 JT Zemp & Thrive Information Solutions - -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. \ No newline at end of file diff --git a/README.txt b/README.txt deleted file mode 120000 index 257e9c4..0000000 --- a/README.txt +++ /dev/null @@ -1 +0,0 @@ -README.rdoc \ No newline at end of file
jtzemp/base62
6dd6a51d93445f90f22dd50f03931ea663ccbd4c
Separate and simplify encoding and decoding
diff --git a/lib/base62.rb b/lib/base62.rb index 21f3dd2..d1c24ff 100644 --- a/lib/base62.rb +++ b/lib/base62.rb @@ -1,95 +1,30 @@ -require File.dirname(__FILE__) + "/base62/version" +require "base62/version" +require "base62/string" +require "base62/integer" -class String - BASE62_PRIMITIVES = { - "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, - "M" => 22, - "N" => 23, - "O" => 24, - "P" => 25, - "Q" => 26, - "R" => 27, - "S" => 28, - "T" => 29, - "U" => 30, - "V" => 31, - "W" => 32, - "X" => 33, - "Y" => 34, - "Z" => 35, - "a" => 36, - "b" => 37, - "c" => 38, - "d" => 39, - "e" => 40, - "f" => 41 , - "g" => 42 , - "h" => 43 , - "i" => 44 , - "j" => 45 , - "k" => 46 , - "l" => 47 , - "m" => 48 , - "n" => 49 , - "o" => 50, - "p" => 51, - "q" => 52, - "r" => 53, - "s" => 54, - "t" => 55, - "u" => 56, - "v" => 57, - "w" => 58, - "x" => 59, - "y" => 60, - "z" => 61 - } - - def base62_decode - i = 0 - i_out = 0 - self.split(//).reverse.each do |c| - place = BASE62_PRIMITIVES.size ** i - i_out += BASE62_PRIMITIVES[c] * place - i += 1 +module Base62 + PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a + + class << self + def decode(str) + out = 0 + str.split(//).reverse.each_with_index do |char, index| + place = PRIMITIVES.size ** index + out += PRIMITIVES.index(char) * place + end + out end - i_out - end -end + def encode(int) + return "0" if int == 0 -class Integer - BASE62_PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a - - def base62_encode - return "0" if self == 0 - number = self - result = '' - while(number != 0) - result = BASE62_PRIMITIVES[number % BASE62_PRIMITIVES.size ].to_s + result - number /= BASE62_PRIMITIVES.size - end - result + rem = int + result = '' + while rem != 0 + result = PRIMITIVES[rem % PRIMITIVES.size].to_s + result + rem /= PRIMITIVES.size + end + result + end end -end +end \ No newline at end of file diff --git a/lib/base62/integer.rb b/lib/base62/integer.rb new file mode 100644 index 0000000..39ed0b5 --- /dev/null +++ b/lib/base62/integer.rb @@ -0,0 +1,5 @@ +class Integer + def base62_encode + Base62.encode(self) + end +end \ No newline at end of file diff --git a/lib/base62/string.rb b/lib/base62/string.rb new file mode 100644 index 0000000..bed2224 --- /dev/null +++ b/lib/base62/string.rb @@ -0,0 +1,5 @@ +class String + def base62_decode + Base62.decode(self) + end +end \ No newline at end of file
jtzemp/base62
14f32bd07b2de11912187462e32fd6ee8dfa5d43
Simplify version
diff --git a/lib/base62/version.rb b/lib/base62/version.rb index 513c540..87b363a 100644 --- a/lib/base62/version.rb +++ b/lib/base62/version.rb @@ -1,7 +1,3 @@ module Base62 - MAJOR = 0 - MINOR = 1 - TINY = 4 - - VERSION = [MAJOR, MINOR, TINY].join('.') + VERSION = "0.1.4" end
jtzemp/base62
3bb22158f7cf5b6837a557ed144be1437f25cde8
Simplify tests
diff --git a/test/base62_test.rb b/test/base62_test.rb new file mode 100644 index 0000000..934f228 --- /dev/null +++ b/test/base62_test.rb @@ -0,0 +1,52 @@ +require "test_helper" + +class Base62Test < Test::Unit::TestCase + def test_encode + { 0 => "0", + 1 => "1", + 10 => "A", + 100 => "1c", + 1231 => "Jr", + 3982 => "12E", + 10927 => "2qF", + 50923 => "DFL", + 100292 => "Q5c", + 202731 => "qjr", + 519278 => "2B5S", + 902323 => "3mjb", + 1003827 => "4D8l", + 2129387 => "8vwx", + 52338283 => "3XbZr", + 298372887 => "KBwPv", + 8237468237 => "8zTZmv", + 256352386723872 => "1AnE6bpNA" + }.each do |int, base62| + assert_equal base62, int.base62_encode + end + end + + def test_decode + { "" => 0, + "0" => 0, + "1" => 1, + "A" => 10, + "1c" => 100, + "Jr" => 1231, + "12E" => 3982, + "2qF" => 10927, + "DFL" => 50923, + "Q5c" => 100292, + "qjr" => 202731, + "2B5S" => 519278, + "3mjb" => 902323, + "4D8l" => 1003827, + "8vwx" => 2129387, + "3XbZr" => 52338283, + "KBwPv" => 298372887, + "8zTZmv" => 8237468237, + "1AnE6bpNA" => 256352386723872 + }.each do |base62, int| + assert_equal int, base62.base62_decode + end + end +end \ No newline at end of file diff --git a/test/test_base62.rb b/test/test_base62.rb deleted file mode 100644 index d4e2fbe..0000000 --- a/test/test_base62.rb +++ /dev/null @@ -1,17 +0,0 @@ -require File.dirname(__FILE__) + '/test_helper.rb' - -class TestBase62 < Test::Unit::TestCase - - def test_1_to_100000 - (0..100000).each do |i| - assert_equal(i.to_s, i.base62_encode.base62_decode.to_s, i.to_s + "\t" + i.base62_encode.to_s + "\t" + i.base62_encode.base62_decode.to_s) - end - end - - def test_0 - assert_equal(0, "0".base62_decode) - assert_equal("0", 0.base62_encode) - assert_equal(0, "".base62_decode) - end - -end diff --git a/test/test_helper.rb b/test/test_helper.rb index efbfda5..dac6a2d 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,2 +1,2 @@ -require 'test/unit' -require File.dirname(__FILE__) + '/../lib/base62' +require "base62" +require "test/unit" \ No newline at end of file
jtzemp/base62
856ef8cb315aa2e509b36031215164d7e8f726ca
Add a Rakefile so you can `rake test`
diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..97eb7bb --- /dev/null +++ b/Rakefile @@ -0,0 +1,10 @@ +require 'rake/testtask' +require 'bundler/gem_tasks' + +Rake::TestTask.new do |t| + t.libs << 'test' + t.test_files = FileList['test/**/*_test.rb'] + t.verbose = true +end + +task :default => :test \ No newline at end of file
jtzemp/base62
eb5bc1ce385c4a0b538dc8f9249d725271ae4732
Use Bundler for gem development dependencies
diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..1ecddc6 --- /dev/null +++ b/Gemfile @@ -0,0 +1,4 @@ +source 'https://rubygems.org' + +# Specify your gem's dependencies in base62.gemspec +gemspec
jtzemp/base62
49fb564548524805756696cb4651372e7bc9f2d4
Simplify gemspec
diff --git a/base62.gemspec b/base62.gemspec index 503e7a6..0a56cd9 100644 --- a/base62.gemspec +++ b/base62.gemspec @@ -1,27 +1,25 @@ -$LOAD_PATH << File.join(File.dirname(__FILE__), 'lib') -require 'base62' -Gem::Specification.new do |s| - s.name = %q{base62} - s.version = Base62::VERSION - - desc = %q{Base62 monkeypatches Integer to add an Integer#base62_encode - instance method to encode an integer in the character set of - 0-9 + A-Z + a-z. It also monkeypatches String to add - String#base62_decode to take the string and turn it back - into a valid integer.} - s.summary = desc - s.description = desc +lib = File.expand_path('../lib', __FILE__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) +require 'base62/version' - s.files = Dir['[A-Z]*', 'lib/**/*.rb', 'test/*.rb'] - s.require_path = 'lib' - s.test_files = Dir['test/*.rb'] +Gem::Specification.new do |s| + s.name = "base62" + s.version = Base62::VERSION + s.authors = ["JT Zemp", "Saadiq Rodgers-King", "Derrick Camerino"] + s.email = ["jtzemp@gmail.com"] + s.description = %q{Base62 monkeypatches Integer to add an Integer#base62_encode + instance method to encode an integer in the character set of + 0-9 + A-Z + a-z. It also monkeypatches String to add + String#base62_decode to take the string and turn it back + into a valid integer.} + s.summary = %q{Monkeypatches Integer and String to allow for base62 encoding and decoding} + s.homepage = "https://github.com/jtzemp/base62" + s.license = "MIT" - s.authors = ["JT Zemp", "Saadiq Rodgers-King", "Derrick Camerino"] - s.email = %q{jtzemp@gmail.com} - s.homepage = "http://github.com/jtzemp/base62" + s.files = `git ls-files`.split($/) + s.test_files = s.files.grep(%r{^test/}) + s.require_paths = ["lib"] - s.platform = Gem::Platform::RUBY - s.rubygems_version = %q{0.1.4} - s.licenses = ["MIT"] + s.add_development_dependency "bundler", "~> 1.3" + s.add_development_dependency "rake" end -
jtzemp/base62
0ca03807d297adae9c1fb837eb8c647ea461d175
Fixed Issue #1 https://github.com/jtzemp/base62/issues#issue/1: 0.base62_encode returns "0"
diff --git a/README.rdoc b/README.rdoc index 93a1f77..ef9e88e 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,51 +1,47 @@ -= base62 - -* http://geekjacking.com/base62_gem - == DESCRIPTION: Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. == INSTALL: * sudo gem install base62 == USAGE: require 'base62' 123.base62_encode => "1z" "funky".base62_decode => 619367412 == THANKS: * Saadiq Rodgers-King (http://github.com/saadiq) for making it work with Ruby 1.9. * Derrick Camerino (https://github.com/robustdj) for adding a Gemspec and prompting me to clean stuff up. == LICENSE: (The MIT License) Copyright (c) 2008 JT Zemp & Thrive Information Solutions 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. \ No newline at end of file diff --git a/base62.gemspec b/base62.gemspec index d1cf29c..503e7a6 100644 --- a/base62.gemspec +++ b/base62.gemspec @@ -1,27 +1,27 @@ $LOAD_PATH << File.join(File.dirname(__FILE__), 'lib') require 'base62' Gem::Specification.new do |s| s.name = %q{base62} s.version = Base62::VERSION desc = %q{Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer.} s.summary = desc s.description = desc s.files = Dir['[A-Z]*', 'lib/**/*.rb', 'test/*.rb'] s.require_path = 'lib' s.test_files = Dir['test/*.rb'] s.authors = ["JT Zemp", "Saadiq Rodgers-King", "Derrick Camerino"] s.email = %q{jtzemp@gmail.com} s.homepage = "http://github.com/jtzemp/base62" s.platform = Gem::Platform::RUBY - s.rubygems_version = %q{0.1.3} + s.rubygems_version = %q{0.1.4} s.licenses = ["MIT"] end diff --git a/lib/base62.rb b/lib/base62.rb index 985fb49..21f3dd2 100644 --- a/lib/base62.rb +++ b/lib/base62.rb @@ -1,94 +1,95 @@ require File.dirname(__FILE__) + "/base62/version" class String BASE62_PRIMITIVES = { "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, "M" => 22, "N" => 23, "O" => 24, "P" => 25, "Q" => 26, "R" => 27, "S" => 28, "T" => 29, "U" => 30, "V" => 31, "W" => 32, "X" => 33, "Y" => 34, "Z" => 35, "a" => 36, "b" => 37, "c" => 38, "d" => 39, "e" => 40, "f" => 41 , "g" => 42 , "h" => 43 , "i" => 44 , "j" => 45 , "k" => 46 , "l" => 47 , "m" => 48 , "n" => 49 , "o" => 50, "p" => 51, "q" => 52, "r" => 53, "s" => 54, "t" => 55, "u" => 56, "v" => 57, "w" => 58, "x" => 59, "y" => 60, "z" => 61 } def base62_decode i = 0 i_out = 0 self.split(//).reverse.each do |c| place = BASE62_PRIMITIVES.size ** i i_out += BASE62_PRIMITIVES[c] * place i += 1 end i_out end end class Integer BASE62_PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a def base62_encode + return "0" if self == 0 number = self result = '' while(number != 0) result = BASE62_PRIMITIVES[number % BASE62_PRIMITIVES.size ].to_s + result number /= BASE62_PRIMITIVES.size end result end end diff --git a/lib/base62/version.rb b/lib/base62/version.rb index 3291a9a..513c540 100644 --- a/lib/base62/version.rb +++ b/lib/base62/version.rb @@ -1,7 +1,7 @@ module Base62 MAJOR = 0 MINOR = 1 - TINY = 3 + TINY = 4 VERSION = [MAJOR, MINOR, TINY].join('.') end diff --git a/test/test_base62.rb b/test/test_base62.rb index adf9138..d4e2fbe 100644 --- a/test/test_base62.rb +++ b/test/test_base62.rb @@ -1,11 +1,17 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestBase62 < Test::Unit::TestCase def test_1_to_100000 (0..100000).each do |i| assert_equal(i.to_s, i.base62_encode.base62_decode.to_s, i.to_s + "\t" + i.base62_encode.to_s + "\t" + i.base62_encode.base62_decode.to_s) end end + def test_0 + assert_equal(0, "0".base62_decode) + assert_equal("0", 0.base62_encode) + assert_equal(0, "".base62_decode) + end + end
jtzemp/base62
4993c065e621c54373b8dcf09ce7e766d0679c1c
Version bump and Gemspec cleanup/additions as well as added usage instructions to the README
diff --git a/.gitignore b/.gitignore index ccc9fd9..52ed97e 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -*.DS_Store \ No newline at end of file +*.DS_Store +*.gem \ No newline at end of file diff --git a/History.txt b/History.txt index 7b47983..2640e97 100644 --- a/History.txt +++ b/History.txt @@ -1,8 +1,16 @@ +== 0.1.3 2010-11-24 + +* Cleaned out the crap that's not needed like hoe and rake tasks and newgem stuff + +== 0.1.2 2010-11-24 + +* Derrick Camerino added a Gemspec + == 0.1.1 2009-11-4 * Ruby 1.9 compatible thx to Saadiq Rodgers-King == 0.1.0 2008-10-04 * 1 major enhancement: * Initial release diff --git a/README.rdoc b/README.rdoc index d32521b..93a1f77 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,41 +1,51 @@ = base62 * http://geekjacking.com/base62_gem == DESCRIPTION: Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. == INSTALL: * sudo gem install base62 +== USAGE: + + require 'base62' + + 123.base62_encode + => "1z" + + "funky".base62_decode + => 619367412 + == THANKS: * Saadiq Rodgers-King (http://github.com/saadiq) for making it work with Ruby 1.9. -* Derrick Camerino (https://github.com/robustdj) for adding a Gemspec. +* Derrick Camerino (https://github.com/robustdj) for adding a Gemspec and prompting me to clean stuff up. == LICENSE: (The MIT License) Copyright (c) 2008 JT Zemp & Thrive Information Solutions 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. \ No newline at end of file diff --git a/base62.gemspec b/base62.gemspec index eaf5673..d1cf29c 100644 --- a/base62.gemspec +++ b/base62.gemspec @@ -1,28 +1,27 @@ $LOAD_PATH << File.join(File.dirname(__FILE__), 'lib') require 'base62' Gem::Specification.new do |s| s.name = %q{base62} s.version = Base62::VERSION - s.summary = %q{Base62 monkeypatches Integer to add an Integer#base62_encode - instance method to encode an integer in the character set of - 0-9 + A-Z + a-z. It also monkeypatches String to add - String#base62_decode to take the string and turn it back - into a valid integer.} - s.description = %q{Base62 monkeypatches Integer to add an Integer#base62_encode - instance method to encode an integer in the character set of - 0-9 + A-Z + a-z. It also monkeypatches String to add - String#base62_decode to take the string and turn it back - into a valid integer.} + + desc = %q{Base62 monkeypatches Integer to add an Integer#base62_encode + instance method to encode an integer in the character set of + 0-9 + A-Z + a-z. It also monkeypatches String to add + String#base62_decode to take the string and turn it back + into a valid integer.} + s.summary = desc + s.description = desc s.files = Dir['[A-Z]*', 'lib/**/*.rb', 'test/*.rb'] s.require_path = 'lib' s.test_files = Dir['test/*.rb'] s.authors = ["JT Zemp", "Saadiq Rodgers-King", "Derrick Camerino"] - s.email = %q{jtzemp's email} - s.homepage = "http://base62.rubyforge.org/" + s.email = %q{jtzemp@gmail.com} + s.homepage = "http://github.com/jtzemp/base62" s.platform = Gem::Platform::RUBY - s.rubygems_version = %q{0.1.1} + s.rubygems_version = %q{0.1.3} + s.licenses = ["MIT"] end diff --git a/lib/base62/version.rb b/lib/base62/version.rb index a23c333..3291a9a 100644 --- a/lib/base62/version.rb +++ b/lib/base62/version.rb @@ -1,7 +1,7 @@ module Base62 MAJOR = 0 MINOR = 1 - TINY = 1 + TINY = 3 VERSION = [MAJOR, MINOR, TINY].join('.') end
jtzemp/base62
e276743ba475a7080d665aba6708e9f3502aa72c
gotta give myself some credit
diff --git a/base62.gemspec b/base62.gemspec index cac4fa9..eaf5673 100644 --- a/base62.gemspec +++ b/base62.gemspec @@ -1,28 +1,28 @@ $LOAD_PATH << File.join(File.dirname(__FILE__), 'lib') require 'base62' Gem::Specification.new do |s| s.name = %q{base62} s.version = Base62::VERSION s.summary = %q{Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer.} s.description = %q{Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer.} s.files = Dir['[A-Z]*', 'lib/**/*.rb', 'test/*.rb'] s.require_path = 'lib' s.test_files = Dir['test/*.rb'] - s.authors = ["JT Zemp", "Saadiq Rodgers-King"] + s.authors = ["JT Zemp", "Saadiq Rodgers-King", "Derrick Camerino"] s.email = %q{jtzemp's email} s.homepage = "http://base62.rubyforge.org/" s.platform = Gem::Platform::RUBY s.rubygems_version = %q{0.1.1} end
jtzemp/base62
c6e99e6b3889fdb03153b94c7b388b00893f4c88
fixing version constant and modifying gemspec
diff --git a/base62.gemspec b/base62.gemspec index c475c58..cac4fa9 100644 --- a/base62.gemspec +++ b/base62.gemspec @@ -1,28 +1,28 @@ $LOAD_PATH << File.join(File.dirname(__FILE__), 'lib') require 'base62' Gem::Specification.new do |s| s.name = %q{base62} s.version = Base62::VERSION s.summary = %q{Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer.} s.description = %q{Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer.} - s.files = Dir['[A-Z]*', 'lib/**/*.rb', 'spec/**/*.rb', 'features/**/*', 'rails/**/*'] + s.files = Dir['[A-Z]*', 'lib/**/*.rb', 'test/*.rb'] s.require_path = 'lib' s.test_files = Dir['test/*.rb'] s.authors = ["JT Zemp", "Saadiq Rodgers-King"] s.email = %q{jtzemp's email} s.homepage = "http://base62.rubyforge.org/" s.platform = Gem::Platform::RUBY - s.rubygems_version = %q{0.1.0} + s.rubygems_version = %q{0.1.1} end diff --git a/lib/base62.rb b/lib/base62.rb index 2694516..985fb49 100644 --- a/lib/base62.rb +++ b/lib/base62.rb @@ -1,92 +1,94 @@ +require File.dirname(__FILE__) + "/base62/version" + class String BASE62_PRIMITIVES = { "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, "M" => 22, "N" => 23, "O" => 24, "P" => 25, "Q" => 26, "R" => 27, "S" => 28, "T" => 29, "U" => 30, "V" => 31, "W" => 32, "X" => 33, "Y" => 34, "Z" => 35, "a" => 36, "b" => 37, "c" => 38, "d" => 39, "e" => 40, "f" => 41 , "g" => 42 , "h" => 43 , "i" => 44 , "j" => 45 , "k" => 46 , "l" => 47 , "m" => 48 , "n" => 49 , "o" => 50, "p" => 51, "q" => 52, "r" => 53, "s" => 54, "t" => 55, "u" => 56, "v" => 57, "w" => 58, "x" => 59, "y" => 60, "z" => 61 } def base62_decode i = 0 i_out = 0 self.split(//).reverse.each do |c| place = BASE62_PRIMITIVES.size ** i i_out += BASE62_PRIMITIVES[c] * place i += 1 end i_out end end class Integer BASE62_PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a - + def base62_encode number = self result = '' while(number != 0) result = BASE62_PRIMITIVES[number % BASE62_PRIMITIVES.size ].to_s + result number /= BASE62_PRIMITIVES.size end result end end diff --git a/lib/base62/version.rb b/lib/base62/version.rb index db25e96..a23c333 100644 --- a/lib/base62/version.rb +++ b/lib/base62/version.rb @@ -1,10 +1,7 @@ module Base62 - module VERSION #:nodoc: - MAJOR = 0 - MINOR = 1 - TINY = 1 + MAJOR = 0 + MINOR = 1 + TINY = 1 - STRING = [MAJOR, MINOR, TINY].join('.') - self - end + VERSION = [MAJOR, MINOR, TINY].join('.') end
jtzemp/base62
fb1c55b1319bcfa193975faedb6b09b843f07136
adding gemspec file
diff --git a/base62.gemspec b/base62.gemspec new file mode 100644 index 0000000..c475c58 --- /dev/null +++ b/base62.gemspec @@ -0,0 +1,28 @@ +$LOAD_PATH << File.join(File.dirname(__FILE__), 'lib') +require 'base62' +Gem::Specification.new do |s| + s.name = %q{base62} + s.version = Base62::VERSION + s.summary = %q{Base62 monkeypatches Integer to add an Integer#base62_encode + instance method to encode an integer in the character set of + 0-9 + A-Z + a-z. It also monkeypatches String to add + String#base62_decode to take the string and turn it back + into a valid integer.} + s.description = %q{Base62 monkeypatches Integer to add an Integer#base62_encode + instance method to encode an integer in the character set of + 0-9 + A-Z + a-z. It also monkeypatches String to add + String#base62_decode to take the string and turn it back + into a valid integer.} + + s.files = Dir['[A-Z]*', 'lib/**/*.rb', 'spec/**/*.rb', 'features/**/*', 'rails/**/*'] + s.require_path = 'lib' + s.test_files = Dir['test/*.rb'] + + s.authors = ["JT Zemp", "Saadiq Rodgers-King"] + s.email = %q{jtzemp's email} + s.homepage = "http://base62.rubyforge.org/" + + s.platform = Gem::Platform::RUBY + s.rubygems_version = %q{0.1.0} +end +
jtzemp/base62
a36d50623a4ebf943b8069d0b743ee473c5583f1
fix for Ruby 1.9 compatibility
diff --git a/History.txt b/History.txt index 9993927..7b47983 100644 --- a/History.txt +++ b/History.txt @@ -1,4 +1,8 @@ +== 0.1.1 2009-11-4 + +* Ruby 1.9 compatible thx to Saadiq Rodgers-King + == 0.1.0 2008-10-04 * 1 major enhancement: * Initial release diff --git a/README.rdoc b/README.rdoc index 63a5e1a..6c03c03 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,36 +1,40 @@ = base62 * http://geekjacking.com/base62_gem == DESCRIPTION: Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. == INSTALL: * sudo gem install base62 +== THANKS: + +* Saadiq Rodgers-King (http://github.com/saadiq) for making it work with Ruby 1.9 + == LICENSE: (The MIT License) Copyright (c) 2008 JT Zemp & Thrive Information Solutions 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. \ No newline at end of file diff --git a/lib/base62.rb b/lib/base62.rb index b5312f0..2694516 100644 --- a/lib/base62.rb +++ b/lib/base62.rb @@ -1,92 +1,92 @@ class String BASE62_PRIMITIVES = { "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, "M" => 22, "N" => 23, "O" => 24, "P" => 25, "Q" => 26, "R" => 27, "S" => 28, "T" => 29, "U" => 30, "V" => 31, "W" => 32, "X" => 33, "Y" => 34, "Z" => 35, "a" => 36, "b" => 37, "c" => 38, "d" => 39, "e" => 40, "f" => 41 , "g" => 42 , "h" => 43 , "i" => 44 , "j" => 45 , "k" => 46 , "l" => 47 , "m" => 48 , "n" => 49 , "o" => 50, "p" => 51, "q" => 52, "r" => 53, "s" => 54, "t" => 55, "u" => 56, "v" => 57, "w" => 58, "x" => 59, "y" => 60, "z" => 61 } def base62_decode i = 0 i_out = 0 self.split(//).reverse.each do |c| place = BASE62_PRIMITIVES.size ** i i_out += BASE62_PRIMITIVES[c] * place i += 1 end i_out end end class Integer - BASE62_PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').collect + ('a'..'z').collect + BASE62_PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a def base62_encode number = self result = '' while(number != 0) result = BASE62_PRIMITIVES[number % BASE62_PRIMITIVES.size ].to_s + result number /= BASE62_PRIMITIVES.size end result end end diff --git a/lib/base62/version.rb b/lib/base62/version.rb index 0b2a386..db25e96 100644 --- a/lib/base62/version.rb +++ b/lib/base62/version.rb @@ -1,10 +1,10 @@ module Base62 module VERSION #:nodoc: MAJOR = 0 MINOR = 1 - TINY = 0 + TINY = 1 STRING = [MAJOR, MINOR, TINY].join('.') self end end
jtzemp/base62
14b0f9a24a925c8adbb566a17f2620d12c483227
deployed the package to rubyforge and updated the website template.
diff --git a/pkg/base62-0.1.0.gem b/pkg/base62-0.1.0.gem deleted file mode 100644 index 3d769b1..0000000 Binary files a/pkg/base62-0.1.0.gem and /dev/null differ diff --git a/pkg/base62-0.1.0.tgz b/pkg/base62-0.1.0.tgz deleted file mode 100644 index 2bf0ee6..0000000 Binary files a/pkg/base62-0.1.0.tgz and /dev/null differ diff --git a/pkg/base62-0.1.0/History.txt b/pkg/base62-0.1.0/History.txt deleted file mode 100644 index 9993927..0000000 --- a/pkg/base62-0.1.0/History.txt +++ /dev/null @@ -1,4 +0,0 @@ -== 0.1.0 2008-10-04 - -* 1 major enhancement: - * Initial release diff --git a/pkg/base62-0.1.0/Manifest.txt b/pkg/base62-0.1.0/Manifest.txt deleted file mode 100644 index 0e8000a..0000000 --- a/pkg/base62-0.1.0/Manifest.txt +++ /dev/null @@ -1,25 +0,0 @@ -History.txt -Manifest.txt -PostInstall.txt -README.rdoc -README.txt -Rakefile -config/hoe.rb -config/requirements.rb -lib/base62.rb -lib/base62/version.rb -script/console -script/destroy -script/generate -script/txt2html -setup.rb -tasks/deployment.rake -tasks/environment.rake -tasks/website.rake -test/test_base62.rb -test/test_helper.rb -website/index.html -website/index.txt -website/javascripts/rounded_corners_lite.inc.js -website/stylesheets/screen.css -website/template.html.erb diff --git a/pkg/base62-0.1.0/PostInstall.txt b/pkg/base62-0.1.0/PostInstall.txt deleted file mode 100644 index aebe4e8..0000000 --- a/pkg/base62-0.1.0/PostInstall.txt +++ /dev/null @@ -1,3 +0,0 @@ - -For more information on base62, see http://geekjacking.com/base62_gem or http://base62.rubyforge.org - diff --git a/pkg/base62-0.1.0/README.rdoc b/pkg/base62-0.1.0/README.rdoc deleted file mode 100644 index 63a5e1a..0000000 --- a/pkg/base62-0.1.0/README.rdoc +++ /dev/null @@ -1,36 +0,0 @@ -= base62 - -* http://geekjacking.com/base62_gem - -== DESCRIPTION: - -Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. - -== INSTALL: - -* sudo gem install base62 - -== LICENSE: - -(The MIT License) - -Copyright (c) 2008 JT Zemp & Thrive Information Solutions - -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. \ No newline at end of file diff --git a/pkg/base62-0.1.0/README.txt b/pkg/base62-0.1.0/README.txt deleted file mode 100644 index 63a5e1a..0000000 --- a/pkg/base62-0.1.0/README.txt +++ /dev/null @@ -1,36 +0,0 @@ -= base62 - -* http://geekjacking.com/base62_gem - -== DESCRIPTION: - -Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. - -== INSTALL: - -* sudo gem install base62 - -== LICENSE: - -(The MIT License) - -Copyright (c) 2008 JT Zemp & Thrive Information Solutions - -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. \ No newline at end of file diff --git a/pkg/base62-0.1.0/Rakefile b/pkg/base62-0.1.0/Rakefile deleted file mode 100644 index e469154..0000000 --- a/pkg/base62-0.1.0/Rakefile +++ /dev/null @@ -1,4 +0,0 @@ -require 'config/requirements' -require 'config/hoe' # setup Hoe + all gem configuration - -Dir['tasks/**/*.rake'].each { |rake| load rake } \ No newline at end of file diff --git a/pkg/base62-0.1.0/config/hoe.rb b/pkg/base62-0.1.0/config/hoe.rb deleted file mode 100644 index 0b63305..0000000 --- a/pkg/base62-0.1.0/config/hoe.rb +++ /dev/null @@ -1,73 +0,0 @@ -require 'base62/version' - -AUTHOR = 'JT Zemp' # can also be an array of Authors -EMAIL = "jt.zemp@thriveis.com" -DESCRIPTION = "The base62 gem monkeypatches Integer and String. It creates an Integer#base62_encode instance method to encode integers into a string with this set of characters: 0-9 + A-Z + a-z. It also creates a String#base62_decode method to reverse the encoded string back into an integer." -GEM_NAME = 'base62' # what ppl will type to install your gem -RUBYFORGE_PROJECT = 'base62' # The unix name for your project -HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" -DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" -EXTRA_DEPENDENCIES = [ -# ['activesupport', '>= 1.3.1'] -] # An array of rubygem dependencies [name, version] - -@config_file = "~/.rubyforge/user-config.yml" -@config = nil -RUBYFORGE_USERNAME = "unknown" -def rubyforge_username - unless @config - begin - @config = YAML.load(File.read(File.expand_path(@config_file))) - rescue - puts <<-EOS -ERROR: No rubyforge config file found: #{@config_file} -Run 'rubyforge setup' to prepare your env for access to Rubyforge - - See http://newgem.rubyforge.org/rubyforge.html for more details - EOS - exit - end - end - RUBYFORGE_USERNAME.replace @config["username"] -end - - -REV = nil -# UNCOMMENT IF REQUIRED: -# REV = YAML.load(`svn info`)['Revision'] -VERS = Base62::VERSION::STRING + (REV ? ".#{REV}" : "") -RDOC_OPTS = ['--quiet', '--title', 'base62 documentation', - "--opname", "index.html", - "--line-numbers", - "--main", "README", - "--inline-source"] - -class Hoe - def extra_deps - @extra_deps.reject! { |x| Array(x).first == 'hoe' } - @extra_deps - end -end - -# Generate all the Rake tasks -# Run 'rake -T' to see list of generated tasks (from gem root directory) -$hoe = Hoe.new(GEM_NAME, VERS) do |p| - p.developer(AUTHOR, EMAIL) - p.description = DESCRIPTION - p.summary = DESCRIPTION - p.url = HOMEPATH - p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT - p.test_globs = ["test/**/test_*.rb"] - p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. - - # == Optional - p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") - #p.extra_deps = EXTRA_DEPENDENCIES - - #p.spec_extras = {} # A hash of extra values to set in the gemspec. - end - -CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") -PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" -$hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') -$hoe.rsync_args = '-av --delete --ignore-errors' -$hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue "" \ No newline at end of file diff --git a/pkg/base62-0.1.0/config/requirements.rb b/pkg/base62-0.1.0/config/requirements.rb deleted file mode 100644 index 9292b69..0000000 --- a/pkg/base62-0.1.0/config/requirements.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'fileutils' -include FileUtils - -require 'rubygems' -%w[rake hoe newgem rubigen].each do |req_gem| - begin - require req_gem - rescue LoadError - puts "This Rakefile requires the '#{req_gem}' RubyGem." - puts "Installation: gem install #{req_gem} -y" - exit - end -end - -$:.unshift(File.join(File.dirname(__FILE__), %w[.. lib])) diff --git a/pkg/base62-0.1.0/lib/base62.rb b/pkg/base62-0.1.0/lib/base62.rb deleted file mode 100644 index b5312f0..0000000 --- a/pkg/base62-0.1.0/lib/base62.rb +++ /dev/null @@ -1,92 +0,0 @@ -class String - BASE62_PRIMITIVES = { - "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, - "M" => 22, - "N" => 23, - "O" => 24, - "P" => 25, - "Q" => 26, - "R" => 27, - "S" => 28, - "T" => 29, - "U" => 30, - "V" => 31, - "W" => 32, - "X" => 33, - "Y" => 34, - "Z" => 35, - "a" => 36, - "b" => 37, - "c" => 38, - "d" => 39, - "e" => 40, - "f" => 41 , - "g" => 42 , - "h" => 43 , - "i" => 44 , - "j" => 45 , - "k" => 46 , - "l" => 47 , - "m" => 48 , - "n" => 49 , - "o" => 50, - "p" => 51, - "q" => 52, - "r" => 53, - "s" => 54, - "t" => 55, - "u" => 56, - "v" => 57, - "w" => 58, - "x" => 59, - "y" => 60, - "z" => 61 - } - - def base62_decode - i = 0 - i_out = 0 - self.split(//).reverse.each do |c| - place = BASE62_PRIMITIVES.size ** i - i_out += BASE62_PRIMITIVES[c] * place - i += 1 - end - i_out - end -end - - -class Integer - BASE62_PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').collect + ('a'..'z').collect - - def base62_encode - number = self - result = '' - while(number != 0) - result = BASE62_PRIMITIVES[number % BASE62_PRIMITIVES.size ].to_s + result - number /= BASE62_PRIMITIVES.size - end - result - end -end diff --git a/pkg/base62-0.1.0/lib/base62/version.rb b/pkg/base62-0.1.0/lib/base62/version.rb deleted file mode 100644 index 0b2a386..0000000 --- a/pkg/base62-0.1.0/lib/base62/version.rb +++ /dev/null @@ -1,10 +0,0 @@ -module Base62 - module VERSION #:nodoc: - MAJOR = 0 - MINOR = 1 - TINY = 0 - - STRING = [MAJOR, MINOR, TINY].join('.') - self - end -end diff --git a/pkg/base62-0.1.0/script/console b/pkg/base62-0.1.0/script/console deleted file mode 100755 index 0e2f259..0000000 --- a/pkg/base62-0.1.0/script/console +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env ruby -# File: script/console -irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb' - -libs = " -r irb/completion" -# Perhaps use a console_lib to store any extra methods I may want available in the cosole -# libs << " -r #{File.dirname(__FILE__) + '/../lib/console_lib/console_logger.rb'}" -libs << " -r #{File.dirname(__FILE__) + '/../lib/base62.rb'}" -puts "Loading base62 gem" -exec "#{irb} #{libs} --simple-prompt" \ No newline at end of file diff --git a/pkg/base62-0.1.0/script/destroy b/pkg/base62-0.1.0/script/destroy deleted file mode 100755 index e48464d..0000000 --- a/pkg/base62-0.1.0/script/destroy +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env ruby -APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) - -begin - require 'rubigen' -rescue LoadError - require 'rubygems' - require 'rubigen' -end -require 'rubigen/scripts/destroy' - -ARGV.shift if ['--help', '-h'].include?(ARGV[0]) -RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] -RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/pkg/base62-0.1.0/script/generate b/pkg/base62-0.1.0/script/generate deleted file mode 100755 index c27f655..0000000 --- a/pkg/base62-0.1.0/script/generate +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env ruby -APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) - -begin - require 'rubigen' -rescue LoadError - require 'rubygems' - require 'rubigen' -end -require 'rubigen/scripts/generate' - -ARGV.shift if ['--help', '-h'].include?(ARGV[0]) -RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] -RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/pkg/base62-0.1.0/script/txt2html b/pkg/base62-0.1.0/script/txt2html deleted file mode 100755 index d3a4801..0000000 --- a/pkg/base62-0.1.0/script/txt2html +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env ruby - -GEM_NAME = 'base62' # what ppl will type to install your gem -RUBYFORGE_PROJECT = 'base62' - -require 'rubygems' -begin - require 'newgem' - require 'rubyforge' -rescue LoadError - puts "\n\nGenerating the website requires the newgem RubyGem" - puts "Install: gem install newgem\n\n" - exit(1) -end -require 'redcloth' -require 'syntax/convertors/html' -require 'erb' -require File.dirname(__FILE__) + "/../lib/#{GEM_NAME}/version.rb" - -version = Base62::VERSION::STRING -download = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" - -def rubyforge_project_id - RubyForge.new.configure.autoconfig["group_ids"][RUBYFORGE_PROJECT] -end - -class Fixnum - def ordinal - # teens - return 'th' if (10..19).include?(self % 100) - # others - case self % 10 - when 1: return 'st' - when 2: return 'nd' - when 3: return 'rd' - else return 'th' - end - end -end - -class Time - def pretty - return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" - end -end - -def convert_syntax(syntax, source) - return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') -end - -if ARGV.length >= 1 - src, template = ARGV - template ||= File.join(File.dirname(__FILE__), '/../website/template.html.erb') -else - puts("Usage: #{File.split($0).last} source.txt [template.html.erb] > output.html") - exit! -end - -template = ERB.new(File.open(template).read) - -title = nil -body = nil -File.open(src) do |fsrc| - title_text = fsrc.readline - body_text_template = fsrc.read - body_text = ERB.new(body_text_template).result(binding) - syntax_items = [] - body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ - ident = syntax_items.length - element, syntax, source = $1, $2, $3 - syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" - "syntax-temp-#{ident}" - } - title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip - body = RedCloth.new(body_text).to_html - body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } -end -stat = File.stat(src) -created = stat.ctime -modified = stat.mtime - -$stdout << template.result(binding) diff --git a/pkg/base62-0.1.0/setup.rb b/pkg/base62-0.1.0/setup.rb deleted file mode 100644 index 424a5f3..0000000 --- a/pkg/base62-0.1.0/setup.rb +++ /dev/null @@ -1,1585 +0,0 @@ -# -# setup.rb -# -# Copyright (c) 2000-2005 Minero Aoki -# -# This program is free software. -# You can distribute/modify this program under the terms of -# the GNU LGPL, Lesser General Public License version 2.1. -# - -unless Enumerable.method_defined?(:map) # Ruby 1.4.6 - module Enumerable - alias map collect - end -end - -unless File.respond_to?(:read) # Ruby 1.6 - def File.read(fname) - open(fname) {|f| - return f.read - } - end -end - -unless Errno.const_defined?(:ENOTEMPTY) # Windows? - module Errno - class ENOTEMPTY - # We do not raise this exception, implementation is not needed. - end - end -end - -def File.binread(fname) - open(fname, 'rb') {|f| - return f.read - } -end - -# for corrupted Windows' stat(2) -def File.dir?(path) - File.directory?((path[-1,1] == '/') ? path : path + '/') -end - - -class ConfigTable - - include Enumerable - - def initialize(rbconfig) - @rbconfig = rbconfig - @items = [] - @table = {} - # options - @install_prefix = nil - @config_opt = nil - @verbose = true - @no_harm = false - end - - attr_accessor :install_prefix - attr_accessor :config_opt - - attr_writer :verbose - - def verbose? - @verbose - end - - attr_writer :no_harm - - def no_harm? - @no_harm - end - - def [](key) - lookup(key).resolve(self) - end - - def []=(key, val) - lookup(key).set val - end - - def names - @items.map {|i| i.name } - end - - def each(&block) - @items.each(&block) - end - - def key?(name) - @table.key?(name) - end - - def lookup(name) - @table[name] or setup_rb_error "no such config item: #{name}" - end - - def add(item) - @items.push item - @table[item.name] = item - end - - def remove(name) - item = lookup(name) - @items.delete_if {|i| i.name == name } - @table.delete_if {|name, i| i.name == name } - item - end - - def load_script(path, inst = nil) - if File.file?(path) - MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path - end - end - - def savefile - '.config' - end - - def load_savefile - begin - File.foreach(savefile()) do |line| - k, v = *line.split(/=/, 2) - self[k] = v.strip - end - rescue Errno::ENOENT - setup_rb_error $!.message + "\n#{File.basename($0)} config first" - end - end - - def save - @items.each {|i| i.value } - File.open(savefile(), 'w') {|f| - @items.each do |i| - f.printf "%s=%s\n", i.name, i.value if i.value? and i.value - end - } - end - - def load_standard_entries - standard_entries(@rbconfig).each do |ent| - add ent - end - end - - def standard_entries(rbconfig) - c = rbconfig - - rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) - - major = c['MAJOR'].to_i - minor = c['MINOR'].to_i - teeny = c['TEENY'].to_i - version = "#{major}.#{minor}" - - # ruby ver. >= 1.4.4? - newpath_p = ((major >= 2) or - ((major == 1) and - ((minor >= 5) or - ((minor == 4) and (teeny >= 4))))) - - if c['rubylibdir'] - # V > 1.6.3 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = c['rubylibdir'] - librubyverarch = c['archdir'] - siteruby = c['sitedir'] - siterubyver = c['sitelibdir'] - siterubyverarch = c['sitearchdir'] - elsif newpath_p - # 1.4.4 <= V <= 1.6.3 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = "#{c['prefix']}/lib/ruby/#{version}" - librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" - siteruby = c['sitedir'] - siterubyver = "$siteruby/#{version}" - siterubyverarch = "$siterubyver/#{c['arch']}" - else - # V < 1.4.4 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = "#{c['prefix']}/lib/ruby/#{version}" - librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" - siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" - siterubyver = siteruby - siterubyverarch = "$siterubyver/#{c['arch']}" - end - parameterize = lambda {|path| - path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') - } - - if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } - makeprog = arg.sub(/'/, '').split(/=/, 2)[1] - else - makeprog = 'make' - end - - [ - ExecItem.new('installdirs', 'std/site/home', - 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ - {|val, table| - case val - when 'std' - table['rbdir'] = '$librubyver' - table['sodir'] = '$librubyverarch' - when 'site' - table['rbdir'] = '$siterubyver' - table['sodir'] = '$siterubyverarch' - when 'home' - setup_rb_error '$HOME was not set' unless ENV['HOME'] - table['prefix'] = ENV['HOME'] - table['rbdir'] = '$libdir/ruby' - table['sodir'] = '$libdir/ruby' - end - }, - PathItem.new('prefix', 'path', c['prefix'], - 'path prefix of target environment'), - PathItem.new('bindir', 'path', parameterize.call(c['bindir']), - 'the directory for commands'), - PathItem.new('libdir', 'path', parameterize.call(c['libdir']), - 'the directory for libraries'), - PathItem.new('datadir', 'path', parameterize.call(c['datadir']), - 'the directory for shared data'), - PathItem.new('mandir', 'path', parameterize.call(c['mandir']), - 'the directory for man pages'), - PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), - 'the directory for system configuration files'), - PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), - 'the directory for local state data'), - PathItem.new('libruby', 'path', libruby, - 'the directory for ruby libraries'), - PathItem.new('librubyver', 'path', librubyver, - 'the directory for standard ruby libraries'), - PathItem.new('librubyverarch', 'path', librubyverarch, - 'the directory for standard ruby extensions'), - PathItem.new('siteruby', 'path', siteruby, - 'the directory for version-independent aux ruby libraries'), - PathItem.new('siterubyver', 'path', siterubyver, - 'the directory for aux ruby libraries'), - PathItem.new('siterubyverarch', 'path', siterubyverarch, - 'the directory for aux ruby binaries'), - PathItem.new('rbdir', 'path', '$siterubyver', - 'the directory for ruby scripts'), - PathItem.new('sodir', 'path', '$siterubyverarch', - 'the directory for ruby extentions'), - PathItem.new('rubypath', 'path', rubypath, - 'the path to set to #! line'), - ProgramItem.new('rubyprog', 'name', rubypath, - 'the ruby program using for installation'), - ProgramItem.new('makeprog', 'name', makeprog, - 'the make program to compile ruby extentions'), - SelectItem.new('shebang', 'all/ruby/never', 'ruby', - 'shebang line (#!) editing mode'), - BoolItem.new('without-ext', 'yes/no', 'no', - 'does not compile/install ruby extentions') - ] - end - private :standard_entries - - def load_multipackage_entries - multipackage_entries().each do |ent| - add ent - end - end - - def multipackage_entries - [ - PackageSelectionItem.new('with', 'name,name...', '', 'ALL', - 'package names that you want to install'), - PackageSelectionItem.new('without', 'name,name...', '', 'NONE', - 'package names that you do not want to install') - ] - end - private :multipackage_entries - - ALIASES = { - 'std-ruby' => 'librubyver', - 'stdruby' => 'librubyver', - 'rubylibdir' => 'librubyver', - 'archdir' => 'librubyverarch', - 'site-ruby-common' => 'siteruby', # For backward compatibility - 'site-ruby' => 'siterubyver', # For backward compatibility - 'bin-dir' => 'bindir', - 'bin-dir' => 'bindir', - 'rb-dir' => 'rbdir', - 'so-dir' => 'sodir', - 'data-dir' => 'datadir', - 'ruby-path' => 'rubypath', - 'ruby-prog' => 'rubyprog', - 'ruby' => 'rubyprog', - 'make-prog' => 'makeprog', - 'make' => 'makeprog' - } - - def fixup - ALIASES.each do |ali, name| - @table[ali] = @table[name] - end - @items.freeze - @table.freeze - @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ - end - - def parse_opt(opt) - m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" - m.to_a[1,2] - end - - def dllext - @rbconfig['DLEXT'] - end - - def value_config?(name) - lookup(name).value? - end - - class Item - def initialize(name, template, default, desc) - @name = name.freeze - @template = template - @value = default - @default = default - @description = desc - end - - attr_reader :name - attr_reader :description - - attr_accessor :default - alias help_default default - - def help_opt - "--#{@name}=#{@template}" - end - - def value? - true - end - - def value - @value - end - - def resolve(table) - @value.gsub(%r<\$([^/]+)>) { table[$1] } - end - - def set(val) - @value = check(val) - end - - private - - def check(val) - setup_rb_error "config: --#{name} requires argument" unless val - val - end - end - - class BoolItem < Item - def config_type - 'bool' - end - - def help_opt - "--#{@name}" - end - - private - - def check(val) - return 'yes' unless val - case val - when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' - when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' - else - setup_rb_error "config: --#{@name} accepts only yes/no for argument" - end - end - end - - class PathItem < Item - def config_type - 'path' - end - - private - - def check(path) - setup_rb_error "config: --#{@name} requires argument" unless path - path[0,1] == '$' ? path : File.expand_path(path) - end - end - - class ProgramItem < Item - def config_type - 'program' - end - end - - class SelectItem < Item - def initialize(name, selection, default, desc) - super - @ok = selection.split('/') - end - - def config_type - 'select' - end - - private - - def check(val) - unless @ok.include?(val.strip) - setup_rb_error "config: use --#{@name}=#{@template} (#{val})" - end - val.strip - end - end - - class ExecItem < Item - def initialize(name, selection, desc, &block) - super name, selection, nil, desc - @ok = selection.split('/') - @action = block - end - - def config_type - 'exec' - end - - def value? - false - end - - def resolve(table) - setup_rb_error "$#{name()} wrongly used as option value" - end - - undef set - - def evaluate(val, table) - v = val.strip.downcase - unless @ok.include?(v) - setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" - end - @action.call v, table - end - end - - class PackageSelectionItem < Item - def initialize(name, template, default, help_default, desc) - super name, template, default, desc - @help_default = help_default - end - - attr_reader :help_default - - def config_type - 'package' - end - - private - - def check(val) - unless File.dir?("packages/#{val}") - setup_rb_error "config: no such package: #{val}" - end - val - end - end - - class MetaConfigEnvironment - def initialize(config, installer) - @config = config - @installer = installer - end - - def config_names - @config.names - end - - def config?(name) - @config.key?(name) - end - - def bool_config?(name) - @config.lookup(name).config_type == 'bool' - end - - def path_config?(name) - @config.lookup(name).config_type == 'path' - end - - def value_config?(name) - @config.lookup(name).config_type != 'exec' - end - - def add_config(item) - @config.add item - end - - def add_bool_config(name, default, desc) - @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) - end - - def add_path_config(name, default, desc) - @config.add PathItem.new(name, 'path', default, desc) - end - - def set_config_default(name, default) - @config.lookup(name).default = default - end - - def remove_config(name) - @config.remove(name) - end - - # For only multipackage - def packages - raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer - @installer.packages - end - - # For only multipackage - def declare_packages(list) - raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer - @installer.packages = list - end - end - -end # class ConfigTable - - -# This module requires: #verbose?, #no_harm? -module FileOperations - - def mkdir_p(dirname, prefix = nil) - dirname = prefix + File.expand_path(dirname) if prefix - $stderr.puts "mkdir -p #{dirname}" if verbose? - return if no_harm? - - # Does not check '/', it's too abnormal. - dirs = File.expand_path(dirname).split(%r<(?=/)>) - if /\A[a-z]:\z/i =~ dirs[0] - disk = dirs.shift - dirs[0] = disk + dirs[0] - end - dirs.each_index do |idx| - path = dirs[0..idx].join('') - Dir.mkdir path unless File.dir?(path) - end - end - - def rm_f(path) - $stderr.puts "rm -f #{path}" if verbose? - return if no_harm? - force_remove_file path - end - - def rm_rf(path) - $stderr.puts "rm -rf #{path}" if verbose? - return if no_harm? - remove_tree path - end - - def remove_tree(path) - if File.symlink?(path) - remove_file path - elsif File.dir?(path) - remove_tree0 path - else - force_remove_file path - end - end - - def remove_tree0(path) - Dir.foreach(path) do |ent| - next if ent == '.' - next if ent == '..' - entpath = "#{path}/#{ent}" - if File.symlink?(entpath) - remove_file entpath - elsif File.dir?(entpath) - remove_tree0 entpath - else - force_remove_file entpath - end - end - begin - Dir.rmdir path - rescue Errno::ENOTEMPTY - # directory may not be empty - end - end - - def move_file(src, dest) - force_remove_file dest - begin - File.rename src, dest - rescue - File.open(dest, 'wb') {|f| - f.write File.binread(src) - } - File.chmod File.stat(src).mode, dest - File.unlink src - end - end - - def force_remove_file(path) - begin - remove_file path - rescue - end - end - - def remove_file(path) - File.chmod 0777, path - File.unlink path - end - - def install(from, dest, mode, prefix = nil) - $stderr.puts "install #{from} #{dest}" if verbose? - return if no_harm? - - realdest = prefix ? prefix + File.expand_path(dest) : dest - realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) - str = File.binread(from) - if diff?(str, realdest) - verbose_off { - rm_f realdest if File.exist?(realdest) - } - File.open(realdest, 'wb') {|f| - f.write str - } - File.chmod mode, realdest - - File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| - if prefix - f.puts realdest.sub(prefix, '') - else - f.puts realdest - end - } - end - end - - def diff?(new_content, path) - return true unless File.exist?(path) - new_content != File.binread(path) - end - - def command(*args) - $stderr.puts args.join(' ') if verbose? - system(*args) or raise RuntimeError, - "system(#{args.map{|a| a.inspect }.join(' ')}) failed" - end - - def ruby(*args) - command config('rubyprog'), *args - end - - def make(task = nil) - command(*[config('makeprog'), task].compact) - end - - def extdir?(dir) - File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") - end - - def files_of(dir) - Dir.open(dir) {|d| - return d.select {|ent| File.file?("#{dir}/#{ent}") } - } - end - - DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) - - def directories_of(dir) - Dir.open(dir) {|d| - return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT - } - end - -end - - -# This module requires: #srcdir_root, #objdir_root, #relpath -module HookScriptAPI - - def get_config(key) - @config[key] - end - - alias config get_config - - # obsolete: use metaconfig to change configuration - def set_config(key, val) - @config[key] = val - end - - # - # srcdir/objdir (works only in the package directory) - # - - def curr_srcdir - "#{srcdir_root()}/#{relpath()}" - end - - def curr_objdir - "#{objdir_root()}/#{relpath()}" - end - - def srcfile(path) - "#{curr_srcdir()}/#{path}" - end - - def srcexist?(path) - File.exist?(srcfile(path)) - end - - def srcdirectory?(path) - File.dir?(srcfile(path)) - end - - def srcfile?(path) - File.file?(srcfile(path)) - end - - def srcentries(path = '.') - Dir.open("#{curr_srcdir()}/#{path}") {|d| - return d.to_a - %w(. ..) - } - end - - def srcfiles(path = '.') - srcentries(path).select {|fname| - File.file?(File.join(curr_srcdir(), path, fname)) - } - end - - def srcdirectories(path = '.') - srcentries(path).select {|fname| - File.dir?(File.join(curr_srcdir(), path, fname)) - } - end - -end - - -class ToplevelInstaller - - Version = '3.4.1' - Copyright = 'Copyright (c) 2000-2005 Minero Aoki' - - TASKS = [ - [ 'all', 'do config, setup, then install' ], - [ 'config', 'saves your configurations' ], - [ 'show', 'shows current configuration' ], - [ 'setup', 'compiles ruby extentions and others' ], - [ 'install', 'installs files' ], - [ 'test', 'run all tests in test/' ], - [ 'clean', "does `make clean' for each extention" ], - [ 'distclean',"does `make distclean' for each extention" ] - ] - - def ToplevelInstaller.invoke - config = ConfigTable.new(load_rbconfig()) - config.load_standard_entries - config.load_multipackage_entries if multipackage? - config.fixup - klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) - klass.new(File.dirname($0), config).invoke - end - - def ToplevelInstaller.multipackage? - File.dir?(File.dirname($0) + '/packages') - end - - def ToplevelInstaller.load_rbconfig - if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } - ARGV.delete(arg) - load File.expand_path(arg.split(/=/, 2)[1]) - $".push 'rbconfig.rb' - else - require 'rbconfig' - end - ::Config::CONFIG - end - - def initialize(ardir_root, config) - @ardir = File.expand_path(ardir_root) - @config = config - # cache - @valid_task_re = nil - end - - def config(key) - @config[key] - end - - def inspect - "#<#{self.class} #{__id__()}>" - end - - def invoke - run_metaconfigs - case task = parsearg_global() - when nil, 'all' - parsearg_config - init_installers - exec_config - exec_setup - exec_install - else - case task - when 'config', 'test' - ; - when 'clean', 'distclean' - @config.load_savefile if File.exist?(@config.savefile) - else - @config.load_savefile - end - __send__ "parsearg_#{task}" - init_installers - __send__ "exec_#{task}" - end - end - - def run_metaconfigs - @config.load_script "#{@ardir}/metaconfig" - end - - def init_installers - @installer = Installer.new(@config, @ardir, File.expand_path('.')) - end - - # - # Hook Script API bases - # - - def srcdir_root - @ardir - end - - def objdir_root - '.' - end - - def relpath - '.' - end - - # - # Option Parsing - # - - def parsearg_global - while arg = ARGV.shift - case arg - when /\A\w+\z/ - setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) - return arg - when '-q', '--quiet' - @config.verbose = false - when '--verbose' - @config.verbose = true - when '--help' - print_usage $stdout - exit 0 - when '--version' - puts "#{File.basename($0)} version #{Version}" - exit 0 - when '--copyright' - puts Copyright - exit 0 - else - setup_rb_error "unknown global option '#{arg}'" - end - end - nil - end - - def valid_task?(t) - valid_task_re() =~ t - end - - def valid_task_re - @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ - end - - def parsearg_no_options - unless ARGV.empty? - task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) - setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" - end - end - - alias parsearg_show parsearg_no_options - alias parsearg_setup parsearg_no_options - alias parsearg_test parsearg_no_options - alias parsearg_clean parsearg_no_options - alias parsearg_distclean parsearg_no_options - - def parsearg_config - evalopt = [] - set = [] - @config.config_opt = [] - while i = ARGV.shift - if /\A--?\z/ =~ i - @config.config_opt = ARGV.dup - break - end - name, value = *@config.parse_opt(i) - if @config.value_config?(name) - @config[name] = value - else - evalopt.push [name, value] - end - set.push name - end - evalopt.each do |name, value| - @config.lookup(name).evaluate value, @config - end - # Check if configuration is valid - set.each do |n| - @config[n] if @config.value_config?(n) - end - end - - def parsearg_install - @config.no_harm = false - @config.install_prefix = '' - while a = ARGV.shift - case a - when '--no-harm' - @config.no_harm = true - when /\A--prefix=/ - path = a.split(/=/, 2)[1] - path = File.expand_path(path) unless path[0,1] == '/' - @config.install_prefix = path - else - setup_rb_error "install: unknown option #{a}" - end - end - end - - def print_usage(out) - out.puts 'Typical Installation Procedure:' - out.puts " $ ruby #{File.basename $0} config" - out.puts " $ ruby #{File.basename $0} setup" - out.puts " # ruby #{File.basename $0} install (may require root privilege)" - out.puts - out.puts 'Detailed Usage:' - out.puts " ruby #{File.basename $0} <global option>" - out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" - - fmt = " %-24s %s\n" - out.puts - out.puts 'Global options:' - out.printf fmt, '-q,--quiet', 'suppress message outputs' - out.printf fmt, ' --verbose', 'output messages verbosely' - out.printf fmt, ' --help', 'print this message' - out.printf fmt, ' --version', 'print version and quit' - out.printf fmt, ' --copyright', 'print copyright and quit' - out.puts - out.puts 'Tasks:' - TASKS.each do |name, desc| - out.printf fmt, name, desc - end - - fmt = " %-24s %s [%s]\n" - out.puts - out.puts 'Options for CONFIG or ALL:' - @config.each do |item| - out.printf fmt, item.help_opt, item.description, item.help_default - end - out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" - out.puts - out.puts 'Options for INSTALL:' - out.printf fmt, '--no-harm', 'only display what to do if given', 'off' - out.printf fmt, '--prefix=path', 'install path prefix', '' - out.puts - end - - # - # Task Handlers - # - - def exec_config - @installer.exec_config - @config.save # must be final - end - - def exec_setup - @installer.exec_setup - end - - def exec_install - @installer.exec_install - end - - def exec_test - @installer.exec_test - end - - def exec_show - @config.each do |i| - printf "%-20s %s\n", i.name, i.value if i.value? - end - end - - def exec_clean - @installer.exec_clean - end - - def exec_distclean - @installer.exec_distclean - end - -end # class ToplevelInstaller - - -class ToplevelInstallerMulti < ToplevelInstaller - - include FileOperations - - def initialize(ardir_root, config) - super - @packages = directories_of("#{@ardir}/packages") - raise 'no package exists' if @packages.empty? - @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) - end - - def run_metaconfigs - @config.load_script "#{@ardir}/metaconfig", self - @packages.each do |name| - @config.load_script "#{@ardir}/packages/#{name}/metaconfig" - end - end - - attr_reader :packages - - def packages=(list) - raise 'package list is empty' if list.empty? - list.each do |name| - raise "directory packages/#{name} does not exist"\ - unless File.dir?("#{@ardir}/packages/#{name}") - end - @packages = list - end - - def init_installers - @installers = {} - @packages.each do |pack| - @installers[pack] = Installer.new(@config, - "#{@ardir}/packages/#{pack}", - "packages/#{pack}") - end - with = extract_selection(config('with')) - without = extract_selection(config('without')) - @selected = @installers.keys.select {|name| - (with.empty? or with.include?(name)) \ - and not without.include?(name) - } - end - - def extract_selection(list) - a = list.split(/,/) - a.each do |name| - setup_rb_error "no such package: #{name}" unless @installers.key?(name) - end - a - end - - def print_usage(f) - super - f.puts 'Inluded packages:' - f.puts ' ' + @packages.sort.join(' ') - f.puts - end - - # - # Task Handlers - # - - def exec_config - run_hook 'pre-config' - each_selected_installers {|inst| inst.exec_config } - run_hook 'post-config' - @config.save # must be final - end - - def exec_setup - run_hook 'pre-setup' - each_selected_installers {|inst| inst.exec_setup } - run_hook 'post-setup' - end - - def exec_install - run_hook 'pre-install' - each_selected_installers {|inst| inst.exec_install } - run_hook 'post-install' - end - - def exec_test - run_hook 'pre-test' - each_selected_installers {|inst| inst.exec_test } - run_hook 'post-test' - end - - def exec_clean - rm_f @config.savefile - run_hook 'pre-clean' - each_selected_installers {|inst| inst.exec_clean } - run_hook 'post-clean' - end - - def exec_distclean - rm_f @config.savefile - run_hook 'pre-distclean' - each_selected_installers {|inst| inst.exec_distclean } - run_hook 'post-distclean' - end - - # - # lib - # - - def each_selected_installers - Dir.mkdir 'packages' unless File.dir?('packages') - @selected.each do |pack| - $stderr.puts "Processing the package `#{pack}' ..." if verbose? - Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") - Dir.chdir "packages/#{pack}" - yield @installers[pack] - Dir.chdir '../..' - end - end - - def run_hook(id) - @root_installer.run_hook id - end - - # module FileOperations requires this - def verbose? - @config.verbose? - end - - # module FileOperations requires this - def no_harm? - @config.no_harm? - end - -end # class ToplevelInstallerMulti - - -class Installer - - FILETYPES = %w( bin lib ext data conf man ) - - include FileOperations - include HookScriptAPI - - def initialize(config, srcroot, objroot) - @config = config - @srcdir = File.expand_path(srcroot) - @objdir = File.expand_path(objroot) - @currdir = '.' - end - - def inspect - "#<#{self.class} #{File.basename(@srcdir)}>" - end - - def noop(rel) - end - - # - # Hook Script API base methods - # - - def srcdir_root - @srcdir - end - - def objdir_root - @objdir - end - - def relpath - @currdir - end - - # - # Config Access - # - - # module FileOperations requires this - def verbose? - @config.verbose? - end - - # module FileOperations requires this - def no_harm? - @config.no_harm? - end - - def verbose_off - begin - save, @config.verbose = @config.verbose?, false - yield - ensure - @config.verbose = save - end - end - - # - # TASK config - # - - def exec_config - exec_task_traverse 'config' - end - - alias config_dir_bin noop - alias config_dir_lib noop - - def config_dir_ext(rel) - extconf if extdir?(curr_srcdir()) - end - - alias config_dir_data noop - alias config_dir_conf noop - alias config_dir_man noop - - def extconf - ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt - end - - # - # TASK setup - # - - def exec_setup - exec_task_traverse 'setup' - end - - def setup_dir_bin(rel) - files_of(curr_srcdir()).each do |fname| - update_shebang_line "#{curr_srcdir()}/#{fname}" - end - end - - alias setup_dir_lib noop - - def setup_dir_ext(rel) - make if extdir?(curr_srcdir()) - end - - alias setup_dir_data noop - alias setup_dir_conf noop - alias setup_dir_man noop - - def update_shebang_line(path) - return if no_harm? - return if config('shebang') == 'never' - old = Shebang.load(path) - if old - $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 - new = new_shebang(old) - return if new.to_s == old.to_s - else - return unless config('shebang') == 'all' - new = Shebang.new(config('rubypath')) - end - $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? - open_atomic_writer(path) {|output| - File.open(path, 'rb') {|f| - f.gets if old # discard - output.puts new.to_s - output.print f.read - } - } - end - - def new_shebang(old) - if /\Aruby/ =~ File.basename(old.cmd) - Shebang.new(config('rubypath'), old.args) - elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' - Shebang.new(config('rubypath'), old.args[1..-1]) - else - return old unless config('shebang') == 'all' - Shebang.new(config('rubypath')) - end - end - - def open_atomic_writer(path, &block) - tmpfile = File.basename(path) + '.tmp' - begin - File.open(tmpfile, 'wb', &block) - File.rename tmpfile, File.basename(path) - ensure - File.unlink tmpfile if File.exist?(tmpfile) - end - end - - class Shebang - def Shebang.load(path) - line = nil - File.open(path) {|f| - line = f.gets - } - return nil unless /\A#!/ =~ line - parse(line) - end - - def Shebang.parse(line) - cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') - new(cmd, args) - end - - def initialize(cmd, args = []) - @cmd = cmd - @args = args - end - - attr_reader :cmd - attr_reader :args - - def to_s - "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") - end - end - - # - # TASK install - # - - def exec_install - rm_f 'InstalledFiles' - exec_task_traverse 'install' - end - - def install_dir_bin(rel) - install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 - end - - def install_dir_lib(rel) - install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 - end - - def install_dir_ext(rel) - return unless extdir?(curr_srcdir()) - install_files rubyextentions('.'), - "#{config('sodir')}/#{File.dirname(rel)}", - 0555 - end - - def install_dir_data(rel) - install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 - end - - def install_dir_conf(rel) - # FIXME: should not remove current config files - # (rename previous file to .old/.org) - install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 - end - - def install_dir_man(rel) - install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 - end - - def install_files(list, dest, mode) - mkdir_p dest, @config.install_prefix - list.each do |fname| - install fname, dest, mode, @config.install_prefix - end - end - - def libfiles - glob_reject(%w(*.y *.output), targetfiles()) - end - - def rubyextentions(dir) - ents = glob_select("*.#{@config.dllext}", targetfiles()) - if ents.empty? - setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" - end - ents - end - - def targetfiles - mapdir(existfiles() - hookfiles()) - end - - def mapdir(ents) - ents.map {|ent| - if File.exist?(ent) - then ent # objdir - else "#{curr_srcdir()}/#{ent}" # srcdir - end - } - end - - # picked up many entries from cvs-1.11.1/src/ignore.c - JUNK_FILES = %w( - core RCSLOG tags TAGS .make.state - .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb - *~ *.old *.bak *.BAK *.orig *.rej _$* *$ - - *.org *.in .* - ) - - def existfiles - glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) - end - - def hookfiles - %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| - %w( config setup install clean ).map {|t| sprintf(fmt, t) } - }.flatten - end - - def glob_select(pat, ents) - re = globs2re([pat]) - ents.select {|ent| re =~ ent } - end - - def glob_reject(pats, ents) - re = globs2re(pats) - ents.reject {|ent| re =~ ent } - end - - GLOB2REGEX = { - '.' => '\.', - '$' => '\$', - '#' => '\#', - '*' => '.*' - } - - def globs2re(pats) - /\A(?:#{ - pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') - })\z/ - end - - # - # TASK test - # - - TESTDIR = 'test' - - def exec_test - unless File.directory?('test') - $stderr.puts 'no test in this package' if verbose? - return - end - $stderr.puts 'Running tests...' if verbose? - begin - require 'test/unit' - rescue LoadError - setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' - end - runner = Test::Unit::AutoRunner.new(true) - runner.to_run << TESTDIR - runner.run - end - - # - # TASK clean - # - - def exec_clean - exec_task_traverse 'clean' - rm_f @config.savefile - rm_f 'InstalledFiles' - end - - alias clean_dir_bin noop - alias clean_dir_lib noop - alias clean_dir_data noop - alias clean_dir_conf noop - alias clean_dir_man noop - - def clean_dir_ext(rel) - return unless extdir?(curr_srcdir()) - make 'clean' if File.file?('Makefile') - end - - # - # TASK distclean - # - - def exec_distclean - exec_task_traverse 'distclean' - rm_f @config.savefile - rm_f 'InstalledFiles' - end - - alias distclean_dir_bin noop - alias distclean_dir_lib noop - - def distclean_dir_ext(rel) - return unless extdir?(curr_srcdir()) - make 'distclean' if File.file?('Makefile') - end - - alias distclean_dir_data noop - alias distclean_dir_conf noop - alias distclean_dir_man noop - - # - # Traversing - # - - def exec_task_traverse(task) - run_hook "pre-#{task}" - FILETYPES.each do |type| - if type == 'ext' and config('without-ext') == 'yes' - $stderr.puts 'skipping ext/* by user option' if verbose? - next - end - traverse task, type, "#{task}_dir_#{type}" - end - run_hook "post-#{task}" - end - - def traverse(task, rel, mid) - dive_into(rel) { - run_hook "pre-#{task}" - __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') - directories_of(curr_srcdir()).each do |d| - traverse task, "#{rel}/#{d}", mid - end - run_hook "post-#{task}" - } - end - - def dive_into(rel) - return unless File.dir?("#{@srcdir}/#{rel}") - - dir = File.basename(rel) - Dir.mkdir dir unless File.dir?(dir) - prevdir = Dir.pwd - Dir.chdir dir - $stderr.puts '---> ' + rel if verbose? - @currdir = rel - yield - Dir.chdir prevdir - $stderr.puts '<--- ' + rel if verbose? - @currdir = File.dirname(rel) - end - - def run_hook(id) - path = [ "#{curr_srcdir()}/#{id}", - "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } - return unless path - begin - instance_eval File.read(path), path, 1 - rescue - raise if $DEBUG - setup_rb_error "hook #{path} failed:\n" + $!.message - end - end - -end # class Installer - - -class SetupError < StandardError; end - -def setup_rb_error(msg) - raise SetupError, msg -end - -if $0 == __FILE__ - begin - ToplevelInstaller.invoke - rescue SetupError - raise if $DEBUG - $stderr.puts $!.message - $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." - exit 1 - end -end diff --git a/pkg/base62-0.1.0/tasks/deployment.rake b/pkg/base62-0.1.0/tasks/deployment.rake deleted file mode 100644 index 2f43742..0000000 --- a/pkg/base62-0.1.0/tasks/deployment.rake +++ /dev/null @@ -1,34 +0,0 @@ -desc 'Release the website and new gem version' -task :deploy => [:check_version, :website, :release] do - puts "Remember to create SVN tag:" - puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + - "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " - puts "Suggested comment:" - puts "Tagging release #{CHANGES}" -end - -desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' -task :local_deploy => [:website_generate, :install_gem] - -task :check_version do - unless ENV['VERSION'] - puts 'Must pass a VERSION=x.y.z release version' - exit - end - unless ENV['VERSION'] == VERS - puts "Please update your version.rb to match the release version, currently #{VERS}" - exit - end -end - -desc 'Install the package as a gem, without generating documentation(ri/rdoc)' -task :install_gem_no_doc => [:clean, :package] do - sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" -end - -namespace :manifest do - desc 'Recreate Manifest.txt to include ALL files' - task :refresh do - `rake check_manifest | patch -p0 > Manifest.txt` - end -end \ No newline at end of file diff --git a/pkg/base62-0.1.0/tasks/environment.rake b/pkg/base62-0.1.0/tasks/environment.rake deleted file mode 100644 index 691ed3b..0000000 --- a/pkg/base62-0.1.0/tasks/environment.rake +++ /dev/null @@ -1,7 +0,0 @@ -task :ruby_env do - RUBY_APP = if RUBY_PLATFORM =~ /java/ - "jruby" - else - "ruby" - end unless defined? RUBY_APP -end diff --git a/pkg/base62-0.1.0/tasks/website.rake b/pkg/base62-0.1.0/tasks/website.rake deleted file mode 100644 index 93e03fa..0000000 --- a/pkg/base62-0.1.0/tasks/website.rake +++ /dev/null @@ -1,17 +0,0 @@ -desc 'Generate website files' -task :website_generate => :ruby_env do - (Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt| - sh %{ #{RUBY_APP} script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} } - end -end - -desc 'Upload website files to rubyforge' -task :website_upload do - host = "#{rubyforge_username}@rubyforge.org" - remote_dir = "/var/www/gforge-projects/#{PATH}/" - local_dir = 'website' - sh %{rsync -aCv #{local_dir}/ #{host}:#{remote_dir}} -end - -desc 'Generate and upload website files' -task :website => [:website_generate, :website_upload, :publish_docs] diff --git a/pkg/base62-0.1.0/test/test_base62.rb b/pkg/base62-0.1.0/test/test_base62.rb deleted file mode 100644 index adf9138..0000000 --- a/pkg/base62-0.1.0/test/test_base62.rb +++ /dev/null @@ -1,11 +0,0 @@ -require File.dirname(__FILE__) + '/test_helper.rb' - -class TestBase62 < Test::Unit::TestCase - - def test_1_to_100000 - (0..100000).each do |i| - assert_equal(i.to_s, i.base62_encode.base62_decode.to_s, i.to_s + "\t" + i.base62_encode.to_s + "\t" + i.base62_encode.base62_decode.to_s) - end - end - -end diff --git a/pkg/base62-0.1.0/test/test_helper.rb b/pkg/base62-0.1.0/test/test_helper.rb deleted file mode 100644 index efbfda5..0000000 --- a/pkg/base62-0.1.0/test/test_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'test/unit' -require File.dirname(__FILE__) + '/../lib/base62' diff --git a/pkg/base62-0.1.0/website/index.html b/pkg/base62-0.1.0/website/index.html deleted file mode 100644 index c319939..0000000 --- a/pkg/base62-0.1.0/website/index.html +++ /dev/null @@ -1,76 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> -<head> - <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> - <title> - base62 - </title> - <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> -<style> - -</style> - <script type="text/javascript"> - window.onload = function() { - settings = { - tl: { radius: 10 }, - tr: { radius: 10 }, - bl: { radius: 10 }, - br: { radius: 10 }, - antiAlias: true, - autoPad: true, - validTags: ["div"] - } - var versionBox = new curvyCorners(settings, document.getElementById("version")); - versionBox.applyCornersToAll(); - } - </script> -</head> -<body> -<div id="main"> - - <h1>base62</h1> - <div id="version" class="clickable" onclick='document.location = "http://rubyforge.org/projects/base62"; return false'> - <p>Get Version</p> - <a href="http://rubyforge.org/projects/base62" class="numbers">0.1.0</a> - </div> - <h1>&amp;#x2192; &#8216;base62&#8217;</h1> -<h2>What</h2> -<p>The base62 gem monkeypatches Integer and String. It creates an Integer#base62_encode instance method to encode integers into a string with this set of characters: 0-9 + A-Z + a-z. It also creates a String#base62_decode method to reverse the encoded string back into an integer.</p> -<p>I created this gem library to be the basis of a <span class="caps">URL</span> minifying product and service that I&#8217;ll release and host soon.</p> -<h2>Installing</h2> -<p><pre class='syntax'><span class="ident">sudo</span> <span class="ident">gem</span> <span class="ident">install</span> <span class="ident">base62</span></pre></p> -<h2>The basics</h2> -<h2>Developer&#8217;s Site</h2> -<p><a href="http://geekjacking.com/base62_gem">http://geekjacking.com/base62_gem</a></p> -<h2>How to submit patches</h2> -<p>Read the <a href="http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/">8 steps for fixing other people&#8217;s code</a>. It&#8217;s good, but doesn&#8217;t have instructions for GitHub, so come back here after you&#8217;re done and read on.</p> -<p>If you want to submit patches (or check out the code to see how to change from base 10 to base 62) the project code is on GitHub. Here are good instructions for submitting patches through GitHub: http://github.com/guides/fork-a-project-and-submit-your-modifications</p> -<ul> - <li>github: <a href="http://github.com/jtzemp/base62/tree/master">http://github.com/jtzemp/base62/tree/master</a></li> -</ul> -<pre>git clone git://github.com/jtzemp/base62.git</pre> -<h3>Build and test instructions</h3> -<pre>cd base62 -rake test -rake install_gem</pre> -<h2>License</h2> -<p>This code is free to use under the terms of the <span class="caps">MIT</span> license.</p> -<h2>Contact</h2> -<p>Comments are welcome. I&#8217;d love to know if you&#8217;re using it just out of curiosity. Send an email to JT dot Zemp at the domain thriveis.com, or go to http://geekjacking.com/base62_gem and leave a comment there.</p> - <p class="coda"> - Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> - </p> -</div> - -<script type="text/javascript"> -var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); -document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); -</script> -<script type="text/javascript"> -var pageTracker = _gat._getTracker("UA-3918224-4"); -pageTracker._trackPageview(); -</script> -</body> -</html> diff --git a/pkg/base62-0.1.0/website/index.txt b/pkg/base62-0.1.0/website/index.txt deleted file mode 100644 index b1f413f..0000000 --- a/pkg/base62-0.1.0/website/index.txt +++ /dev/null @@ -1,47 +0,0 @@ -h1. base62 - -h1. &#x2192; 'base62' - - -h2. What - -The base62 gem monkeypatches Integer and String. It creates an Integer#base62_encode instance method to encode integers into a string with this set of characters: 0-9 + A-Z + a-z. It also creates a String#base62_decode method to reverse the encoded string back into an integer. - -I created this gem library to be the basis of a URL minifying product and service that I'll release and host soon. - -h2. Installing - -<pre syntax="ruby">sudo gem install base62</pre> - -h2. The basics - - -h2. Developer's Site - -"http://geekjacking.com/base62_gem":http://geekjacking.com/base62_gem - -h2. How to submit patches - -Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/. It's good, but doesn't have instructions for GitHub, so come back here after you're done and read on. - -If you want to submit patches (or check out the code to see how to change from base 10 to base 62) the project code is on GitHub. Here are good instructions for submitting patches through GitHub: http://github.com/guides/fork-a-project-and-submit-your-modifications - -* github: "http://github.com/jtzemp/base62/tree/master":http://github.com/jtzemp/base62/tree/master - -<pre>git clone git://github.com/jtzemp/base62.git</pre> - -h3. Build and test instructions - -<pre>cd base62 -rake test -rake install_gem</pre> - - -h2. License - -This code is free to use under the terms of the MIT license. - -h2. Contact - -Comments are welcome. I'd love to know if you're using it just out of curiosity. Send an email to JT dot Zemp at the domain thriveis.com, or go to http://geekjacking.com/base62_gem and leave a comment there. - diff --git a/pkg/base62-0.1.0/website/javascripts/rounded_corners_lite.inc.js b/pkg/base62-0.1.0/website/javascripts/rounded_corners_lite.inc.js deleted file mode 100644 index afc3ea3..0000000 --- a/pkg/base62-0.1.0/website/javascripts/rounded_corners_lite.inc.js +++ /dev/null @@ -1,285 +0,0 @@ - - /**************************************************************** - * * - * curvyCorners * - * ------------ * - * * - * This script generates rounded corners for your divs. * - * * - * Version 1.2.9 * - * Copyright (c) 2006 Cameron Cooke * - * By: Cameron Cooke and Tim Hutchison. * - * * - * * - * Website: http://www.curvycorners.net * - * Email: info@totalinfinity.com * - * Forum: http://www.curvycorners.net/forum/ * - * * - * * - * This library is free software; you can redistribute * - * it and/or modify it under the terms of the GNU * - * Lesser General Public License as published by the * - * Free Software Foundation; either version 2.1 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 Lesser General Public * - * License for more details. * - * * - * You should have received a copy of the GNU Lesser * - * General Public License along with this library; * - * Inc., 59 Temple Place, Suite 330, Boston, * - * MA 02111-1307 USA * - * * - ****************************************************************/ - -var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1; var isMoz = document.implementation && document.implementation.createDocument; var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false; function curvyCorners() -{ if(typeof(arguments[0]) != "object") throw newCurvyError("First parameter of curvyCorners() must be an object."); if(typeof(arguments[1]) != "object" && typeof(arguments[1]) != "string") throw newCurvyError("Second parameter of curvyCorners() must be an object or a class name."); if(typeof(arguments[1]) == "string") -{ var startIndex = 0; var boxCol = getElementsByClass(arguments[1]);} -else -{ var startIndex = 1; var boxCol = arguments;} -var curvyCornersCol = new Array(); if(arguments[0].validTags) -var validElements = arguments[0].validTags; else -var validElements = ["div"]; for(var i = startIndex, j = boxCol.length; i < j; i++) -{ var currentTag = boxCol[i].tagName.toLowerCase(); if(inArray(validElements, currentTag) !== false) -{ curvyCornersCol[curvyCornersCol.length] = new curvyObject(arguments[0], boxCol[i]);} -} -this.objects = curvyCornersCol; this.applyCornersToAll = function() -{ for(var x = 0, k = this.objects.length; x < k; x++) -{ this.objects[x].applyCorners();} -} -} -function curvyObject() -{ this.box = arguments[1]; this.settings = arguments[0]; this.topContainer = null; this.bottomContainer = null; this.masterCorners = new Array(); this.contentDIV = null; var boxHeight = get_style(this.box, "height", "height"); var boxWidth = get_style(this.box, "width", "width"); var borderWidth = get_style(this.box, "borderTopWidth", "border-top-width"); var borderColour = get_style(this.box, "borderTopColor", "border-top-color"); var boxColour = get_style(this.box, "backgroundColor", "background-color"); var backgroundImage = get_style(this.box, "backgroundImage", "background-image"); var boxPosition = get_style(this.box, "position", "position"); var boxPadding = get_style(this.box, "paddingTop", "padding-top"); this.boxHeight = parseInt(((boxHeight != "" && boxHeight != "auto" && boxHeight.indexOf("%") == -1)? boxHeight.substring(0, boxHeight.indexOf("px")) : this.box.scrollHeight)); this.boxWidth = parseInt(((boxWidth != "" && boxWidth != "auto" && boxWidth.indexOf("%") == -1)? boxWidth.substring(0, boxWidth.indexOf("px")) : this.box.scrollWidth)); this.borderWidth = parseInt(((borderWidth != "" && borderWidth.indexOf("px") !== -1)? borderWidth.slice(0, borderWidth.indexOf("px")) : 0)); this.boxColour = format_colour(boxColour); this.boxPadding = parseInt(((boxPadding != "" && boxPadding.indexOf("px") !== -1)? boxPadding.slice(0, boxPadding.indexOf("px")) : 0)); this.borderColour = format_colour(borderColour); this.borderString = this.borderWidth + "px" + " solid " + this.borderColour; this.backgroundImage = ((backgroundImage != "none")? backgroundImage : ""); this.boxContent = this.box.innerHTML; if(boxPosition != "absolute") this.box.style.position = "relative"; this.box.style.padding = "0px"; if(isIE && boxWidth == "auto" && boxHeight == "auto") this.box.style.width = "100%"; if(this.settings.autoPad == true && this.boxPadding > 0) -this.box.innerHTML = ""; this.applyCorners = function() -{ for(var t = 0; t < 2; t++) -{ switch(t) -{ case 0: -if(this.settings.tl || this.settings.tr) -{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0); newMainContainer.style.height = topMaxRadius + "px"; newMainContainer.style.top = 0 - topMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.topContainer = this.box.appendChild(newMainContainer);} -break; case 1: -if(this.settings.bl || this.settings.br) -{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0); newMainContainer.style.height = botMaxRadius + "px"; newMainContainer.style.bottom = 0 - botMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.bottomContainer = this.box.appendChild(newMainContainer);} -break;} -} -if(this.topContainer) this.box.style.borderTopWidth = "0px"; if(this.bottomContainer) this.box.style.borderBottomWidth = "0px"; var corners = ["tr", "tl", "br", "bl"]; for(var i in corners) -{ if(i > -1 < 4) -{ var cc = corners[i]; if(!this.settings[cc]) -{ if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null)) -{ var newCorner = document.createElement("DIV"); newCorner.style.position = "relative"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; if(this.backgroundImage == "") -newCorner.style.backgroundColor = this.boxColour; else -newCorner.style.backgroundImage = this.backgroundImage; switch(cc) -{ case "tl": -newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.tr.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.left = -this.borderWidth + "px"; break; case "tr": -newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.tl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; newCorner.style.left = this.borderWidth + "px"; break; case "bl": -newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.br.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = -this.borderWidth + "px"; newCorner.style.backgroundPosition = "-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break; case "br": -newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.bl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = this.borderWidth + "px" -newCorner.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break;} -} -} -else -{ if(this.masterCorners[this.settings[cc].radius]) -{ var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);} -else -{ var newCorner = document.createElement("DIV"); newCorner.style.height = this.settings[cc].radius + "px"; newCorner.style.width = this.settings[cc].radius + "px"; newCorner.style.position = "absolute"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth); for(var intx = 0, j = this.settings[cc].radius; intx < j; intx++) -{ if((intx +1) >= borderRadius) -var y1 = -1; else -var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1); if(borderRadius != j) -{ if((intx) >= borderRadius) -var y2 = -1; else -var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2))); if((intx+1) >= j) -var y3 = -1; else -var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);} -if((intx) >= j) -var y4 = -1; else -var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2))); if(y1 > -1) this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius); if(borderRadius != j) -{ for(var inty = (y1 + 1); inty < y2; inty++) -{ if(this.settings.antiAlias) -{ if(this.backgroundImage != "") -{ var borderFract = (pixelFraction(intx, inty, borderRadius) * 100); if(borderFract < 30) -{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);} -else -{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);} -} -else -{ var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius)); this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);} -} -} -if(this.settings.antiAlias) -{ if(y3 >= y2) -{ if (y2 == -1) y2 = 0; this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);} -} -else -{ if(y3 >= y1) -{ this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);} -} -var outsideColour = this.borderColour;} -else -{ var outsideColour = this.boxColour; var y3 = y1;} -if(this.settings.antiAlias) -{ for(var inty = (y3 + 1); inty < y4; inty++) -{ this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);} -} -} -this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);} -if(cc != "br") -{ for(var t = 0, k = newCorner.childNodes.length; t < k; t++) -{ var pixelBar = newCorner.childNodes[t]; var pixelBarTop = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px"))); var pixelBarLeft = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px"))); var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px"))); if(cc == "tl" || cc == "bl"){ pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px";} -if(cc == "tr" || cc == "tl"){ pixelBar.style.top = this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px";} -switch(cc) -{ case "tr": -pixelBar.style.backgroundPosition = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "tl": -pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "bl": -pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px"; break;} -} -} -} -if(newCorner) -{ switch(cc) -{ case "tl": -if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "tr": -if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "bl": -if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break; case "br": -if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break;} -} -} -} -var radiusDiff = new Array(); radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius) -radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius); for(z in radiusDiff) -{ if(z == "t" || z == "b") -{ if(radiusDiff[z]) -{ var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius)? z +"l" : z +"r"); var newFiller = document.createElement("DIV"); newFiller.style.height = radiusDiff[z] + "px"; newFiller.style.width = this.settings[smallerCornerType].radius+ "px" -newFiller.style.position = "absolute"; newFiller.style.fontSize = "1px"; newFiller.style.overflow = "hidden"; newFiller.style.backgroundColor = this.boxColour; switch(smallerCornerType) -{ case "tl": -newFiller.style.bottom = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.topContainer.appendChild(newFiller); break; case "tr": -newFiller.style.bottom = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.topContainer.appendChild(newFiller); break; case "bl": -newFiller.style.top = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.bottomContainer.appendChild(newFiller); break; case "br": -newFiller.style.top = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.bottomContainer.appendChild(newFiller); break;} -} -var newFillerBar = document.createElement("DIV"); newFillerBar.style.position = "relative"; newFillerBar.style.fontSize = "1px"; newFillerBar.style.overflow = "hidden"; newFillerBar.style.backgroundColor = this.boxColour; newFillerBar.style.backgroundImage = this.backgroundImage; switch(z) -{ case "t": -if(this.topContainer) -{ if(this.settings.tl.radius && this.settings.tr.radius) -{ newFillerBar.style.height = topMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.tl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.tr.radius - this.borderWidth + "px"; newFillerBar.style.borderTop = this.borderString; if(this.backgroundImage != "") -newFillerBar.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; this.topContainer.appendChild(newFillerBar);} -this.box.style.backgroundPosition = "0px -" + (topMaxRadius - this.borderWidth) + "px";} -break; case "b": -if(this.bottomContainer) -{ if(this.settings.bl.radius && this.settings.br.radius) -{ newFillerBar.style.height = botMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.bl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.br.radius - this.borderWidth + "px"; newFillerBar.style.borderBottom = this.borderString; if(this.backgroundImage != "") -newFillerBar.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (topMaxRadius + this.borderWidth)) + "px"; this.bottomContainer.appendChild(newFillerBar);} -} -break;} -} -} -if(this.settings.autoPad == true && this.boxPadding > 0) -{ var contentContainer = document.createElement("DIV"); contentContainer.style.position = "relative"; contentContainer.innerHTML = this.boxContent; contentContainer.className = "autoPadDiv"; var topPadding = Math.abs(topMaxRadius - this.boxPadding); var botPadding = Math.abs(botMaxRadius - this.boxPadding); if(topMaxRadius < this.boxPadding) -contentContainer.style.paddingTop = topPadding + "px"; if(botMaxRadius < this.boxPadding) -contentContainer.style.paddingBottom = botMaxRadius + "px"; contentContainer.style.paddingLeft = this.boxPadding + "px"; contentContainer.style.paddingRight = this.boxPadding + "px"; this.contentDIV = this.box.appendChild(contentContainer);} -} -this.drawPixel = function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius) -{ var pixel = document.createElement("DIV"); pixel.style.height = height + "px"; pixel.style.width = "1px"; pixel.style.position = "absolute"; pixel.style.fontSize = "1px"; pixel.style.overflow = "hidden"; var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius); if(image == -1 && this.backgroundImage != "") -{ pixel.style.backgroundImage = this.backgroundImage; pixel.style.backgroundPosition = "-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px";} -else -{ pixel.style.backgroundColor = colour;} -if (transAmount != 100) -setOpacity(pixel, transAmount); pixel.style.top = inty + "px"; pixel.style.left = intx + "px"; newCorner.appendChild(pixel);} -} -function insertAfter(parent, node, referenceNode) -{ parent.insertBefore(node, referenceNode.nextSibling);} -function BlendColour(Col1, Col2, Col1Fraction) -{ var red1 = parseInt(Col1.substr(1,2),16); var green1 = parseInt(Col1.substr(3,2),16); var blue1 = parseInt(Col1.substr(5,2),16); var red2 = parseInt(Col2.substr(1,2),16); var green2 = parseInt(Col2.substr(3,2),16); var blue2 = parseInt(Col2.substr(5,2),16); if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1; var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction))); if(endRed > 255) endRed = 255; if(endRed < 0) endRed = 0; var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction))); if(endGreen > 255) endGreen = 255; if(endGreen < 0) endGreen = 0; var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction))); if(endBlue > 255) endBlue = 255; if(endBlue < 0) endBlue = 0; return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);} -function IntToHex(strNum) -{ base = strNum / 16; rem = strNum % 16; base = base - (rem / 16); baseS = MakeHex(base); remS = MakeHex(rem); return baseS + '' + remS;} -function MakeHex(x) -{ if((x >= 0) && (x <= 9)) -{ return x;} -else -{ switch(x) -{ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F";} -} -} -function pixelFraction(x, y, r) -{ var pixelfraction = 0; var xvalues = new Array(1); var yvalues = new Array(1); var point = 0; var whatsides = ""; var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2))); if ((intersect >= y) && (intersect < (y+1))) -{ whatsides = "Left"; xvalues[point] = 0; yvalues[point] = intersect - y; point = point + 1;} -var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2))); if ((intersect >= x) && (intersect < (x+1))) -{ whatsides = whatsides + "Top"; xvalues[point] = intersect - x; yvalues[point] = 1; point = point + 1;} -var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2))); if ((intersect >= y) && (intersect < (y+1))) -{ whatsides = whatsides + "Right"; xvalues[point] = 1; yvalues[point] = intersect - y; point = point + 1;} -var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2))); if ((intersect >= x) && (intersect < (x+1))) -{ whatsides = whatsides + "Bottom"; xvalues[point] = intersect - x; yvalues[point] = 0;} -switch (whatsides) -{ case "LeftRight": -pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2); break; case "TopRight": -pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2); break; case "TopBottom": -pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2); break; case "LeftBottom": -pixelfraction = (yvalues[0]*xvalues[1])/2; break; default: -pixelfraction = 1;} -return pixelfraction;} -function rgb2Hex(rgbColour) -{ try{ var rgbArray = rgb2Array(rgbColour); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);} -catch(e){ alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");} -return hexColour;} -function rgb2Array(rgbColour) -{ var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")")); var rgbArray = rgbValues.split(", "); return rgbArray;} -function setOpacity(obj, opacity) -{ opacity = (opacity == 100)?99.999:opacity; if(isSafari && obj.tagName != "IFRAME") -{ var rgbArray = rgb2Array(obj.style.backgroundColor); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";} -else if(typeof(obj.style.opacity) != "undefined") -{ obj.style.opacity = opacity/100;} -else if(typeof(obj.style.MozOpacity) != "undefined") -{ obj.style.MozOpacity = opacity/100;} -else if(typeof(obj.style.filter) != "undefined") -{ obj.style.filter = "alpha(opacity:" + opacity + ")";} -else if(typeof(obj.style.KHTMLOpacity) != "undefined") -{ obj.style.KHTMLOpacity = opacity/100;} -} -function inArray(array, value) -{ for(var i = 0; i < array.length; i++){ if (array[i] === value) return i;} -return false;} -function inArrayKey(array, value) -{ for(key in array){ if(key === value) return true;} -return false;} -function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true;} -else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r;} -else { elm['on' + evType] = fn;} -} -function removeEvent(obj, evType, fn, useCapture){ if (obj.removeEventListener){ obj.removeEventListener(evType, fn, useCapture); return true;} else if (obj.detachEvent){ var r = obj.detachEvent("on"+evType, fn); return r;} else { alert("Handler could not be removed");} -} -function format_colour(colour) -{ var returnColour = "#ffffff"; if(colour != "" && colour != "transparent") -{ if(colour.substr(0, 3) == "rgb") -{ returnColour = rgb2Hex(colour);} -else if(colour.length == 4) -{ returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);} -else -{ returnColour = colour;} -} -return returnColour;} -function get_style(obj, property, propertyNS) -{ try -{ if(obj.currentStyle) -{ var returnVal = eval("obj.currentStyle." + property);} -else -{ if(isSafari && obj.style.display == "none") -{ obj.style.display = ""; var wasHidden = true;} -var returnVal = document.defaultView.getComputedStyle(obj, '').getPropertyValue(propertyNS); if(isSafari && wasHidden) -{ obj.style.display = "none";} -} -} -catch(e) -{ } -return returnVal;} -function getElementsByClass(searchClass, node, tag) -{ var classElements = new Array(); if(node == null) -node = document; if(tag == null) -tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)"); for (i = 0, j = 0; i < elsLen; i++) -{ if(pattern.test(els[i].className)) -{ classElements[j] = els[i]; j++;} -} -return classElements;} -function newCurvyError(errorMessage) -{ return new Error("curvyCorners Error:\n" + errorMessage) -} diff --git a/pkg/base62-0.1.0/website/stylesheets/screen.css b/pkg/base62-0.1.0/website/stylesheets/screen.css deleted file mode 100644 index 2c84cd0..0000000 --- a/pkg/base62-0.1.0/website/stylesheets/screen.css +++ /dev/null @@ -1,138 +0,0 @@ -body { - background-color: #E1D1F1; - font-family: "Georgia", sans-serif; - font-size: 16px; - line-height: 1.6em; - padding: 1.6em 0 0 0; - color: #333; -} -h1, h2, h3, h4, h5, h6 { - color: #444; -} -h1 { - font-family: sans-serif; - font-weight: normal; - font-size: 4em; - line-height: 0.8em; - letter-spacing: -0.1ex; - margin: 5px; -} -li { - padding: 0; - margin: 0; - list-style-type: square; -} -a { - color: #5E5AFF; - background-color: #DAC; - font-weight: normal; - text-decoration: underline; -} -blockquote { - font-size: 90%; - font-style: italic; - border-left: 1px solid #111; - padding-left: 1em; -} -.caps { - font-size: 80%; -} - -#main { - width: 45em; - padding: 0; - margin: 0 auto; -} -.coda { - text-align: right; - color: #77f; - font-size: smaller; -} - -table { - font-size: 90%; - line-height: 1.4em; - color: #ff8; - background-color: #111; - padding: 2px 10px 2px 10px; - border-style: dashed; -} - -th { - color: #fff; -} - -td { - padding: 2px 10px 2px 10px; -} - -.success { - color: #0CC52B; -} - -.failed { - color: #E90A1B; -} - -.unknown { - color: #995000; -} -pre, code { - font-family: monospace; - font-size: 90%; - line-height: 1.4em; - color: #ff8; - background-color: #111; - padding: 2px 10px 2px 10px; -} -.comment { color: #aaa; font-style: italic; } -.keyword { color: #eff; font-weight: bold; } -.punct { color: #eee; font-weight: bold; } -.symbol { color: #0bb; } -.string { color: #6b4; } -.ident { color: #ff8; } -.constant { color: #66f; } -.regex { color: #ec6; } -.number { color: #F99; } -.expr { color: #227; } - -#version { - float: right; - text-align: right; - font-family: sans-serif; - font-weight: normal; - background-color: #B3ABFF; - color: #141331; - padding: 15px 20px 10px 20px; - margin: 0 auto; - margin-top: 15px; - border: 3px solid #141331; -} - -#version .numbers { - display: block; - font-size: 4em; - line-height: 0.8em; - letter-spacing: -0.1ex; - margin-bottom: 15px; -} - -#version p { - text-decoration: none; - color: #141331; - background-color: #B3ABFF; - margin: 0; - padding: 0; -} - -#version a { - text-decoration: none; - color: #141331; - background-color: #B3ABFF; -} - -.clickable { - cursor: pointer; - cursor: hand; -} - diff --git a/pkg/base62-0.1.0/website/template.html.erb b/pkg/base62-0.1.0/website/template.html.erb deleted file mode 100644 index e851735..0000000 --- a/pkg/base62-0.1.0/website/template.html.erb +++ /dev/null @@ -1,48 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> -<head> - <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> - <title> - <%= title %> - </title> - <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> -<style> - -</style> - <script type="text/javascript"> - window.onload = function() { - settings = { - tl: { radius: 10 }, - tr: { radius: 10 }, - bl: { radius: 10 }, - br: { radius: 10 }, - antiAlias: true, - autoPad: true, - validTags: ["div"] - } - var versionBox = new curvyCorners(settings, document.getElementById("version")); - versionBox.applyCornersToAll(); - } - </script> -</head> -<body> -<div id="main"> - - <h1><%= title %></h1> - <div id="version" class="clickable" onclick='document.location = "<%= download %>"; return false'> - <p>Get Version</p> - <a href="<%= download %>" class="numbers"><%= version %></a> - </div> - <%= body %> - <p class="coda"> - <a href="FIXME email">FIXME full name</a>, <%= modified.pretty %><br> - Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> - </p> -</div> - -<!-- insert site tracking codes here, like Google Urchin --> - -</body> -</html> diff --git a/website/index.html b/website/index.html index c319939..c4d6751 100644 --- a/website/index.html +++ b/website/index.html @@ -1,76 +1,79 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> base62 </title> <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> <style> </style> <script type="text/javascript"> window.onload = function() { settings = { tl: { radius: 10 }, tr: { radius: 10 }, bl: { radius: 10 }, br: { radius: 10 }, antiAlias: true, autoPad: true, validTags: ["div"] } var versionBox = new curvyCorners(settings, document.getElementById("version")); versionBox.applyCornersToAll(); } </script> </head> <body> <div id="main"> <h1>base62</h1> <div id="version" class="clickable" onclick='document.location = "http://rubyforge.org/projects/base62"; return false'> <p>Get Version</p> <a href="http://rubyforge.org/projects/base62" class="numbers">0.1.0</a> </div> - <h1>&amp;#x2192; &#8216;base62&#8217;</h1> -<h2>What</h2> + <h2>What</h2> <p>The base62 gem monkeypatches Integer and String. It creates an Integer#base62_encode instance method to encode integers into a string with this set of characters: 0-9 + A-Z + a-z. It also creates a String#base62_decode method to reverse the encoded string back into an integer.</p> <p>I created this gem library to be the basis of a <span class="caps">URL</span> minifying product and service that I&#8217;ll release and host soon.</p> <h2>Installing</h2> <p><pre class='syntax'><span class="ident">sudo</span> <span class="ident">gem</span> <span class="ident">install</span> <span class="ident">base62</span></pre></p> <h2>The basics</h2> +<p><pre class='syntax'><span class="ident">puts</span> <span class="number">123456789</span><span class="punct">.</span><span class="ident">base62_encode</span> <span class="comment"># =&gt; &quot;8M0kX&quot;</span> +<span class="ident">puts</span> <span class="punct">&quot;</span><span class="string">8M0kX</span><span class="punct">&quot;.</span><span class="ident">base62_decode</span> <span class="comment"># =&gt; 123456789</span></pre></p> <h2>Developer&#8217;s Site</h2> <p><a href="http://geekjacking.com/base62_gem">http://geekjacking.com/base62_gem</a></p> <h2>How to submit patches</h2> <p>Read the <a href="http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/">8 steps for fixing other people&#8217;s code</a>. It&#8217;s good, but doesn&#8217;t have instructions for GitHub, so come back here after you&#8217;re done and read on.</p> -<p>If you want to submit patches (or check out the code to see how to change from base 10 to base 62) the project code is on GitHub. Here are good instructions for submitting patches through GitHub: http://github.com/guides/fork-a-project-and-submit-your-modifications</p> +<p>If you want to submit patches (or check out the code to see how to change from base 10 to base 62) the project code is on GitHub. Here are good instructions for submitting patches through GitHub: <a href="http://github.com/guides/fork-a-project-and-submit-your-modifications">http://github.com/guides/fork-a-project-and-submit-your-modifications</a></p> <ul> <li>github: <a href="http://github.com/jtzemp/base62/tree/master">http://github.com/jtzemp/base62/tree/master</a></li> </ul> <pre>git clone git://github.com/jtzemp/base62.git</pre> <h3>Build and test instructions</h3> <pre>cd base62 rake test rake install_gem</pre> <h2>License</h2> <p>This code is free to use under the terms of the <span class="caps">MIT</span> license.</p> <h2>Contact</h2> -<p>Comments are welcome. I&#8217;d love to know if you&#8217;re using it just out of curiosity. Send an email to JT dot Zemp at the domain thriveis.com, or go to http://geekjacking.com/base62_gem and leave a comment there.</p> +<p>Comments are welcome. I&#8217;d love to know if you&#8217;re using it just out of curiosity. Send an email to JT dot Zemp at the domain thriveis.com, or go to <a href="http://geekjacking.com/base62_gem">http://geekjacking.com/base62_gem</a> and leave a comment there.</p> <p class="coda"> + <a href="http://geekjacking.com/about/">JT Zemp</a> (<a href="http://www.twitter.com/jtzemp">JT Zemp on Twitter</a>), 6th October 2008<br> Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> </p> </div> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-3918224-4"); pageTracker._trackPageview(); </script> + </body> </html> diff --git a/website/index.txt b/website/index.txt index b1f413f..cf4b75a 100644 --- a/website/index.txt +++ b/website/index.txt @@ -1,47 +1,46 @@ h1. base62 -h1. &#x2192; 'base62' - - h2. What The base62 gem monkeypatches Integer and String. It creates an Integer#base62_encode instance method to encode integers into a string with this set of characters: 0-9 + A-Z + a-z. It also creates a String#base62_decode method to reverse the encoded string back into an integer. I created this gem library to be the basis of a URL minifying product and service that I'll release and host soon. h2. Installing <pre syntax="ruby">sudo gem install base62</pre> h2. The basics +<pre syntax="ruby">puts 123456789.base62_encode # => "8M0kX" +puts "8M0kX".base62_decode # => 123456789</pre> h2. Developer's Site "http://geekjacking.com/base62_gem":http://geekjacking.com/base62_gem h2. How to submit patches Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/. It's good, but doesn't have instructions for GitHub, so come back here after you're done and read on. -If you want to submit patches (or check out the code to see how to change from base 10 to base 62) the project code is on GitHub. Here are good instructions for submitting patches through GitHub: http://github.com/guides/fork-a-project-and-submit-your-modifications +If you want to submit patches (or check out the code to see how to change from base 10 to base 62) the project code is on GitHub. Here are good instructions for submitting patches through GitHub: "http://github.com/guides/fork-a-project-and-submit-your-modifications":http://github.com/guides/fork-a-project-and-submit-your-modifications * github: "http://github.com/jtzemp/base62/tree/master":http://github.com/jtzemp/base62/tree/master <pre>git clone git://github.com/jtzemp/base62.git</pre> h3. Build and test instructions <pre>cd base62 rake test rake install_gem</pre> h2. License This code is free to use under the terms of the MIT license. h2. Contact -Comments are welcome. I'd love to know if you're using it just out of curiosity. Send an email to JT dot Zemp at the domain thriveis.com, or go to http://geekjacking.com/base62_gem and leave a comment there. +Comments are welcome. I'd love to know if you're using it just out of curiosity. Send an email to JT dot Zemp at the domain thriveis.com, or go to "http://geekjacking.com/base62_gem":http://geekjacking.com/base62_gem and leave a comment there. diff --git a/website/template.html.erb b/website/template.html.erb index e851735..0b4899c 100644 --- a/website/template.html.erb +++ b/website/template.html.erb @@ -1,48 +1,55 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> <%= title %> </title> <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> <style> </style> <script type="text/javascript"> window.onload = function() { settings = { tl: { radius: 10 }, tr: { radius: 10 }, bl: { radius: 10 }, br: { radius: 10 }, antiAlias: true, autoPad: true, validTags: ["div"] } var versionBox = new curvyCorners(settings, document.getElementById("version")); versionBox.applyCornersToAll(); } </script> </head> <body> <div id="main"> <h1><%= title %></h1> <div id="version" class="clickable" onclick='document.location = "<%= download %>"; return false'> <p>Get Version</p> <a href="<%= download %>" class="numbers"><%= version %></a> </div> <%= body %> <p class="coda"> - <a href="FIXME email">FIXME full name</a>, <%= modified.pretty %><br> + <a href="http://geekjacking.com/about/">JT Zemp</a> (<a href="http://www.twitter.com/jtzemp">JT Zemp on Twitter</a>), <%= modified.pretty %><br> Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> </p> </div> -<!-- insert site tracking codes here, like Google Urchin --> +<script type="text/javascript"> +var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); +document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); +</script> +<script type="text/javascript"> +var pageTracker = _gat._getTracker("UA-3918224-4"); +pageTracker._trackPageview(); +</script> </body> </html>
jtzemp/base62
cfb35dba9f9c29edc198e1c747c1e08976c93059
created the gem package.
diff --git a/pkg/base62-0.1.0.gem b/pkg/base62-0.1.0.gem new file mode 100644 index 0000000..f232a9a Binary files /dev/null and b/pkg/base62-0.1.0.gem differ diff --git a/pkg/base62-0.1.0.tgz b/pkg/base62-0.1.0.tgz new file mode 100644 index 0000000..d276b5e Binary files /dev/null and b/pkg/base62-0.1.0.tgz differ diff --git a/pkg/base62-0.1.0/History.txt b/pkg/base62-0.1.0/History.txt new file mode 100644 index 0000000..9993927 --- /dev/null +++ b/pkg/base62-0.1.0/History.txt @@ -0,0 +1,4 @@ +== 0.1.0 2008-10-04 + +* 1 major enhancement: + * Initial release diff --git a/pkg/base62-0.1.0/Manifest.txt b/pkg/base62-0.1.0/Manifest.txt new file mode 100644 index 0000000..0e8000a --- /dev/null +++ b/pkg/base62-0.1.0/Manifest.txt @@ -0,0 +1,25 @@ +History.txt +Manifest.txt +PostInstall.txt +README.rdoc +README.txt +Rakefile +config/hoe.rb +config/requirements.rb +lib/base62.rb +lib/base62/version.rb +script/console +script/destroy +script/generate +script/txt2html +setup.rb +tasks/deployment.rake +tasks/environment.rake +tasks/website.rake +test/test_base62.rb +test/test_helper.rb +website/index.html +website/index.txt +website/javascripts/rounded_corners_lite.inc.js +website/stylesheets/screen.css +website/template.html.erb diff --git a/pkg/base62-0.1.0/PostInstall.txt b/pkg/base62-0.1.0/PostInstall.txt new file mode 100644 index 0000000..aebe4e8 --- /dev/null +++ b/pkg/base62-0.1.0/PostInstall.txt @@ -0,0 +1,3 @@ + +For more information on base62, see http://geekjacking.com/base62_gem or http://base62.rubyforge.org + diff --git a/pkg/base62-0.1.0/README.rdoc b/pkg/base62-0.1.0/README.rdoc new file mode 100644 index 0000000..63a5e1a --- /dev/null +++ b/pkg/base62-0.1.0/README.rdoc @@ -0,0 +1,36 @@ += base62 + +* http://geekjacking.com/base62_gem + +== DESCRIPTION: + +Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. + +== INSTALL: + +* sudo gem install base62 + +== LICENSE: + +(The MIT License) + +Copyright (c) 2008 JT Zemp & Thrive Information Solutions + +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. \ No newline at end of file diff --git a/pkg/base62-0.1.0/README.txt b/pkg/base62-0.1.0/README.txt new file mode 100644 index 0000000..63a5e1a --- /dev/null +++ b/pkg/base62-0.1.0/README.txt @@ -0,0 +1,36 @@ += base62 + +* http://geekjacking.com/base62_gem + +== DESCRIPTION: + +Base62 monkeypatches Integer to add an Integer#base62_encode instance method to encode an integer in the character set of 0-9 + A-Z + a-z. It also monkeypatches String to add String#base62_decode to take the string and turn it back into a valid integer. + +== INSTALL: + +* sudo gem install base62 + +== LICENSE: + +(The MIT License) + +Copyright (c) 2008 JT Zemp & Thrive Information Solutions + +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. \ No newline at end of file diff --git a/pkg/base62-0.1.0/Rakefile b/pkg/base62-0.1.0/Rakefile new file mode 100644 index 0000000..e469154 --- /dev/null +++ b/pkg/base62-0.1.0/Rakefile @@ -0,0 +1,4 @@ +require 'config/requirements' +require 'config/hoe' # setup Hoe + all gem configuration + +Dir['tasks/**/*.rake'].each { |rake| load rake } \ No newline at end of file diff --git a/pkg/base62-0.1.0/config/hoe.rb b/pkg/base62-0.1.0/config/hoe.rb new file mode 100644 index 0000000..6ec6d1b --- /dev/null +++ b/pkg/base62-0.1.0/config/hoe.rb @@ -0,0 +1,73 @@ +require 'base62/version' + +AUTHOR = 'FIXME full name' # can also be an array of Authors +EMAIL = "FIXME email" +DESCRIPTION = "description of gem" +GEM_NAME = 'base62' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'base62' # The unix name for your project +HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" +DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" +EXTRA_DEPENDENCIES = [ +# ['activesupport', '>= 1.3.1'] +] # An array of rubygem dependencies [name, version] + +@config_file = "~/.rubyforge/user-config.yml" +@config = nil +RUBYFORGE_USERNAME = "unknown" +def rubyforge_username + unless @config + begin + @config = YAML.load(File.read(File.expand_path(@config_file))) + rescue + puts <<-EOS +ERROR: No rubyforge config file found: #{@config_file} +Run 'rubyforge setup' to prepare your env for access to Rubyforge + - See http://newgem.rubyforge.org/rubyforge.html for more details + EOS + exit + end + end + RUBYFORGE_USERNAME.replace @config["username"] +end + + +REV = nil +# UNCOMMENT IF REQUIRED: +# REV = YAML.load(`svn info`)['Revision'] +VERS = Base62::VERSION::STRING + (REV ? ".#{REV}" : "") +RDOC_OPTS = ['--quiet', '--title', 'base62 documentation', + "--opname", "index.html", + "--line-numbers", + "--main", "README", + "--inline-source"] + +class Hoe + def extra_deps + @extra_deps.reject! { |x| Array(x).first == 'hoe' } + @extra_deps + end +end + +# Generate all the Rake tasks +# Run 'rake -T' to see list of generated tasks (from gem root directory) +$hoe = Hoe.new(GEM_NAME, VERS) do |p| + p.developer(AUTHOR, EMAIL) + p.description = DESCRIPTION + p.summary = DESCRIPTION + p.url = HOMEPATH + p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT + p.test_globs = ["test/**/test_*.rb"] + p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. + + # == Optional + p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") + #p.extra_deps = EXTRA_DEPENDENCIES + + #p.spec_extras = {} # A hash of extra values to set in the gemspec. + end + +CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") +PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" +$hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') +$hoe.rsync_args = '-av --delete --ignore-errors' +$hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue "" \ No newline at end of file diff --git a/pkg/base62-0.1.0/config/requirements.rb b/pkg/base62-0.1.0/config/requirements.rb new file mode 100644 index 0000000..9292b69 --- /dev/null +++ b/pkg/base62-0.1.0/config/requirements.rb @@ -0,0 +1,15 @@ +require 'fileutils' +include FileUtils + +require 'rubygems' +%w[rake hoe newgem rubigen].each do |req_gem| + begin + require req_gem + rescue LoadError + puts "This Rakefile requires the '#{req_gem}' RubyGem." + puts "Installation: gem install #{req_gem} -y" + exit + end +end + +$:.unshift(File.join(File.dirname(__FILE__), %w[.. lib])) diff --git a/pkg/base62-0.1.0/lib/base62.rb b/pkg/base62-0.1.0/lib/base62.rb new file mode 100644 index 0000000..b5312f0 --- /dev/null +++ b/pkg/base62-0.1.0/lib/base62.rb @@ -0,0 +1,92 @@ +class String + BASE62_PRIMITIVES = { + "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, + "M" => 22, + "N" => 23, + "O" => 24, + "P" => 25, + "Q" => 26, + "R" => 27, + "S" => 28, + "T" => 29, + "U" => 30, + "V" => 31, + "W" => 32, + "X" => 33, + "Y" => 34, + "Z" => 35, + "a" => 36, + "b" => 37, + "c" => 38, + "d" => 39, + "e" => 40, + "f" => 41 , + "g" => 42 , + "h" => 43 , + "i" => 44 , + "j" => 45 , + "k" => 46 , + "l" => 47 , + "m" => 48 , + "n" => 49 , + "o" => 50, + "p" => 51, + "q" => 52, + "r" => 53, + "s" => 54, + "t" => 55, + "u" => 56, + "v" => 57, + "w" => 58, + "x" => 59, + "y" => 60, + "z" => 61 + } + + def base62_decode + i = 0 + i_out = 0 + self.split(//).reverse.each do |c| + place = BASE62_PRIMITIVES.size ** i + i_out += BASE62_PRIMITIVES[c] * place + i += 1 + end + i_out + end +end + + +class Integer + BASE62_PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').collect + ('a'..'z').collect + + def base62_encode + number = self + result = '' + while(number != 0) + result = BASE62_PRIMITIVES[number % BASE62_PRIMITIVES.size ].to_s + result + number /= BASE62_PRIMITIVES.size + end + result + end +end diff --git a/pkg/base62-0.1.0/lib/base62/version.rb b/pkg/base62-0.1.0/lib/base62/version.rb new file mode 100644 index 0000000..0b2a386 --- /dev/null +++ b/pkg/base62-0.1.0/lib/base62/version.rb @@ -0,0 +1,10 @@ +module Base62 + module VERSION #:nodoc: + MAJOR = 0 + MINOR = 1 + TINY = 0 + + STRING = [MAJOR, MINOR, TINY].join('.') + self + end +end diff --git a/pkg/base62-0.1.0/script/console b/pkg/base62-0.1.0/script/console new file mode 100755 index 0000000..0e2f259 --- /dev/null +++ b/pkg/base62-0.1.0/script/console @@ -0,0 +1,10 @@ +#!/usr/bin/env ruby +# File: script/console +irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb' + +libs = " -r irb/completion" +# Perhaps use a console_lib to store any extra methods I may want available in the cosole +# libs << " -r #{File.dirname(__FILE__) + '/../lib/console_lib/console_logger.rb'}" +libs << " -r #{File.dirname(__FILE__) + '/../lib/base62.rb'}" +puts "Loading base62 gem" +exec "#{irb} #{libs} --simple-prompt" \ No newline at end of file diff --git a/pkg/base62-0.1.0/script/destroy b/pkg/base62-0.1.0/script/destroy new file mode 100755 index 0000000..e48464d --- /dev/null +++ b/pkg/base62-0.1.0/script/destroy @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/destroy' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/pkg/base62-0.1.0/script/generate b/pkg/base62-0.1.0/script/generate new file mode 100755 index 0000000..c27f655 --- /dev/null +++ b/pkg/base62-0.1.0/script/generate @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/generate' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/pkg/base62-0.1.0/script/txt2html b/pkg/base62-0.1.0/script/txt2html new file mode 100755 index 0000000..d3a4801 --- /dev/null +++ b/pkg/base62-0.1.0/script/txt2html @@ -0,0 +1,82 @@ +#!/usr/bin/env ruby + +GEM_NAME = 'base62' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'base62' + +require 'rubygems' +begin + require 'newgem' + require 'rubyforge' +rescue LoadError + puts "\n\nGenerating the website requires the newgem RubyGem" + puts "Install: gem install newgem\n\n" + exit(1) +end +require 'redcloth' +require 'syntax/convertors/html' +require 'erb' +require File.dirname(__FILE__) + "/../lib/#{GEM_NAME}/version.rb" + +version = Base62::VERSION::STRING +download = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" + +def rubyforge_project_id + RubyForge.new.configure.autoconfig["group_ids"][RUBYFORGE_PROJECT] +end + +class Fixnum + def ordinal + # teens + return 'th' if (10..19).include?(self % 100) + # others + case self % 10 + when 1: return 'st' + when 2: return 'nd' + when 3: return 'rd' + else return 'th' + end + end +end + +class Time + def pretty + return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" + end +end + +def convert_syntax(syntax, source) + return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') +end + +if ARGV.length >= 1 + src, template = ARGV + template ||= File.join(File.dirname(__FILE__), '/../website/template.html.erb') +else + puts("Usage: #{File.split($0).last} source.txt [template.html.erb] > output.html") + exit! +end + +template = ERB.new(File.open(template).read) + +title = nil +body = nil +File.open(src) do |fsrc| + title_text = fsrc.readline + body_text_template = fsrc.read + body_text = ERB.new(body_text_template).result(binding) + syntax_items = [] + body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ + ident = syntax_items.length + element, syntax, source = $1, $2, $3 + syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" + "syntax-temp-#{ident}" + } + title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip + body = RedCloth.new(body_text).to_html + body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } +end +stat = File.stat(src) +created = stat.ctime +modified = stat.mtime + +$stdout << template.result(binding) diff --git a/pkg/base62-0.1.0/setup.rb b/pkg/base62-0.1.0/setup.rb new file mode 100644 index 0000000..424a5f3 --- /dev/null +++ b/pkg/base62-0.1.0/setup.rb @@ -0,0 +1,1585 @@ +# +# setup.rb +# +# Copyright (c) 2000-2005 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the terms of +# the GNU LGPL, Lesser General Public License version 2.1. +# + +unless Enumerable.method_defined?(:map) # Ruby 1.4.6 + module Enumerable + alias map collect + end +end + +unless File.respond_to?(:read) # Ruby 1.6 + def File.read(fname) + open(fname) {|f| + return f.read + } + end +end + +unless Errno.const_defined?(:ENOTEMPTY) # Windows? + module Errno + class ENOTEMPTY + # We do not raise this exception, implementation is not needed. + end + end +end + +def File.binread(fname) + open(fname, 'rb') {|f| + return f.read + } +end + +# for corrupted Windows' stat(2) +def File.dir?(path) + File.directory?((path[-1,1] == '/') ? path : path + '/') +end + + +class ConfigTable + + include Enumerable + + def initialize(rbconfig) + @rbconfig = rbconfig + @items = [] + @table = {} + # options + @install_prefix = nil + @config_opt = nil + @verbose = true + @no_harm = false + end + + attr_accessor :install_prefix + attr_accessor :config_opt + + attr_writer :verbose + + def verbose? + @verbose + end + + attr_writer :no_harm + + def no_harm? + @no_harm + end + + def [](key) + lookup(key).resolve(self) + end + + def []=(key, val) + lookup(key).set val + end + + def names + @items.map {|i| i.name } + end + + def each(&block) + @items.each(&block) + end + + def key?(name) + @table.key?(name) + end + + def lookup(name) + @table[name] or setup_rb_error "no such config item: #{name}" + end + + def add(item) + @items.push item + @table[item.name] = item + end + + def remove(name) + item = lookup(name) + @items.delete_if {|i| i.name == name } + @table.delete_if {|name, i| i.name == name } + item + end + + def load_script(path, inst = nil) + if File.file?(path) + MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path + end + end + + def savefile + '.config' + end + + def load_savefile + begin + File.foreach(savefile()) do |line| + k, v = *line.split(/=/, 2) + self[k] = v.strip + end + rescue Errno::ENOENT + setup_rb_error $!.message + "\n#{File.basename($0)} config first" + end + end + + def save + @items.each {|i| i.value } + File.open(savefile(), 'w') {|f| + @items.each do |i| + f.printf "%s=%s\n", i.name, i.value if i.value? and i.value + end + } + end + + def load_standard_entries + standard_entries(@rbconfig).each do |ent| + add ent + end + end + + def standard_entries(rbconfig) + c = rbconfig + + rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) + + major = c['MAJOR'].to_i + minor = c['MINOR'].to_i + teeny = c['TEENY'].to_i + version = "#{major}.#{minor}" + + # ruby ver. >= 1.4.4? + newpath_p = ((major >= 2) or + ((major == 1) and + ((minor >= 5) or + ((minor == 4) and (teeny >= 4))))) + + if c['rubylibdir'] + # V > 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = c['rubylibdir'] + librubyverarch = c['archdir'] + siteruby = c['sitedir'] + siterubyver = c['sitelibdir'] + siterubyverarch = c['sitearchdir'] + elsif newpath_p + # 1.4.4 <= V <= 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = c['sitedir'] + siterubyver = "$siteruby/#{version}" + siterubyverarch = "$siterubyver/#{c['arch']}" + else + # V < 1.4.4 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" + siterubyver = siteruby + siterubyverarch = "$siterubyver/#{c['arch']}" + end + parameterize = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') + } + + if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] + else + makeprog = 'make' + end + + [ + ExecItem.new('installdirs', 'std/site/home', + 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ + {|val, table| + case val + when 'std' + table['rbdir'] = '$librubyver' + table['sodir'] = '$librubyverarch' + when 'site' + table['rbdir'] = '$siterubyver' + table['sodir'] = '$siterubyverarch' + when 'home' + setup_rb_error '$HOME was not set' unless ENV['HOME'] + table['prefix'] = ENV['HOME'] + table['rbdir'] = '$libdir/ruby' + table['sodir'] = '$libdir/ruby' + end + }, + PathItem.new('prefix', 'path', c['prefix'], + 'path prefix of target environment'), + PathItem.new('bindir', 'path', parameterize.call(c['bindir']), + 'the directory for commands'), + PathItem.new('libdir', 'path', parameterize.call(c['libdir']), + 'the directory for libraries'), + PathItem.new('datadir', 'path', parameterize.call(c['datadir']), + 'the directory for shared data'), + PathItem.new('mandir', 'path', parameterize.call(c['mandir']), + 'the directory for man pages'), + PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), + 'the directory for system configuration files'), + PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), + 'the directory for local state data'), + PathItem.new('libruby', 'path', libruby, + 'the directory for ruby libraries'), + PathItem.new('librubyver', 'path', librubyver, + 'the directory for standard ruby libraries'), + PathItem.new('librubyverarch', 'path', librubyverarch, + 'the directory for standard ruby extensions'), + PathItem.new('siteruby', 'path', siteruby, + 'the directory for version-independent aux ruby libraries'), + PathItem.new('siterubyver', 'path', siterubyver, + 'the directory for aux ruby libraries'), + PathItem.new('siterubyverarch', 'path', siterubyverarch, + 'the directory for aux ruby binaries'), + PathItem.new('rbdir', 'path', '$siterubyver', + 'the directory for ruby scripts'), + PathItem.new('sodir', 'path', '$siterubyverarch', + 'the directory for ruby extentions'), + PathItem.new('rubypath', 'path', rubypath, + 'the path to set to #! line'), + ProgramItem.new('rubyprog', 'name', rubypath, + 'the ruby program using for installation'), + ProgramItem.new('makeprog', 'name', makeprog, + 'the make program to compile ruby extentions'), + SelectItem.new('shebang', 'all/ruby/never', 'ruby', + 'shebang line (#!) editing mode'), + BoolItem.new('without-ext', 'yes/no', 'no', + 'does not compile/install ruby extentions') + ] + end + private :standard_entries + + def load_multipackage_entries + multipackage_entries().each do |ent| + add ent + end + end + + def multipackage_entries + [ + PackageSelectionItem.new('with', 'name,name...', '', 'ALL', + 'package names that you want to install'), + PackageSelectionItem.new('without', 'name,name...', '', 'NONE', + 'package names that you do not want to install') + ] + end + private :multipackage_entries + + ALIASES = { + 'std-ruby' => 'librubyver', + 'stdruby' => 'librubyver', + 'rubylibdir' => 'librubyver', + 'archdir' => 'librubyverarch', + 'site-ruby-common' => 'siteruby', # For backward compatibility + 'site-ruby' => 'siterubyver', # For backward compatibility + 'bin-dir' => 'bindir', + 'bin-dir' => 'bindir', + 'rb-dir' => 'rbdir', + 'so-dir' => 'sodir', + 'data-dir' => 'datadir', + 'ruby-path' => 'rubypath', + 'ruby-prog' => 'rubyprog', + 'ruby' => 'rubyprog', + 'make-prog' => 'makeprog', + 'make' => 'makeprog' + } + + def fixup + ALIASES.each do |ali, name| + @table[ali] = @table[name] + end + @items.freeze + @table.freeze + @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ + end + + def parse_opt(opt) + m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" + m.to_a[1,2] + end + + def dllext + @rbconfig['DLEXT'] + end + + def value_config?(name) + lookup(name).value? + end + + class Item + def initialize(name, template, default, desc) + @name = name.freeze + @template = template + @value = default + @default = default + @description = desc + end + + attr_reader :name + attr_reader :description + + attr_accessor :default + alias help_default default + + def help_opt + "--#{@name}=#{@template}" + end + + def value? + true + end + + def value + @value + end + + def resolve(table) + @value.gsub(%r<\$([^/]+)>) { table[$1] } + end + + def set(val) + @value = check(val) + end + + private + + def check(val) + setup_rb_error "config: --#{name} requires argument" unless val + val + end + end + + class BoolItem < Item + def config_type + 'bool' + end + + def help_opt + "--#{@name}" + end + + private + + def check(val) + return 'yes' unless val + case val + when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' + when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' + else + setup_rb_error "config: --#{@name} accepts only yes/no for argument" + end + end + end + + class PathItem < Item + def config_type + 'path' + end + + private + + def check(path) + setup_rb_error "config: --#{@name} requires argument" unless path + path[0,1] == '$' ? path : File.expand_path(path) + end + end + + class ProgramItem < Item + def config_type + 'program' + end + end + + class SelectItem < Item + def initialize(name, selection, default, desc) + super + @ok = selection.split('/') + end + + def config_type + 'select' + end + + private + + def check(val) + unless @ok.include?(val.strip) + setup_rb_error "config: use --#{@name}=#{@template} (#{val})" + end + val.strip + end + end + + class ExecItem < Item + def initialize(name, selection, desc, &block) + super name, selection, nil, desc + @ok = selection.split('/') + @action = block + end + + def config_type + 'exec' + end + + def value? + false + end + + def resolve(table) + setup_rb_error "$#{name()} wrongly used as option value" + end + + undef set + + def evaluate(val, table) + v = val.strip.downcase + unless @ok.include?(v) + setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" + end + @action.call v, table + end + end + + class PackageSelectionItem < Item + def initialize(name, template, default, help_default, desc) + super name, template, default, desc + @help_default = help_default + end + + attr_reader :help_default + + def config_type + 'package' + end + + private + + def check(val) + unless File.dir?("packages/#{val}") + setup_rb_error "config: no such package: #{val}" + end + val + end + end + + class MetaConfigEnvironment + def initialize(config, installer) + @config = config + @installer = installer + end + + def config_names + @config.names + end + + def config?(name) + @config.key?(name) + end + + def bool_config?(name) + @config.lookup(name).config_type == 'bool' + end + + def path_config?(name) + @config.lookup(name).config_type == 'path' + end + + def value_config?(name) + @config.lookup(name).config_type != 'exec' + end + + def add_config(item) + @config.add item + end + + def add_bool_config(name, default, desc) + @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) + end + + def add_path_config(name, default, desc) + @config.add PathItem.new(name, 'path', default, desc) + end + + def set_config_default(name, default) + @config.lookup(name).default = default + end + + def remove_config(name) + @config.remove(name) + end + + # For only multipackage + def packages + raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer + @installer.packages + end + + # For only multipackage + def declare_packages(list) + raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer + @installer.packages = list + end + end + +end # class ConfigTable + + +# This module requires: #verbose?, #no_harm? +module FileOperations + + def mkdir_p(dirname, prefix = nil) + dirname = prefix + File.expand_path(dirname) if prefix + $stderr.puts "mkdir -p #{dirname}" if verbose? + return if no_harm? + + # Does not check '/', it's too abnormal. + dirs = File.expand_path(dirname).split(%r<(?=/)>) + if /\A[a-z]:\z/i =~ dirs[0] + disk = dirs.shift + dirs[0] = disk + dirs[0] + end + dirs.each_index do |idx| + path = dirs[0..idx].join('') + Dir.mkdir path unless File.dir?(path) + end + end + + def rm_f(path) + $stderr.puts "rm -f #{path}" if verbose? + return if no_harm? + force_remove_file path + end + + def rm_rf(path) + $stderr.puts "rm -rf #{path}" if verbose? + return if no_harm? + remove_tree path + end + + def remove_tree(path) + if File.symlink?(path) + remove_file path + elsif File.dir?(path) + remove_tree0 path + else + force_remove_file path + end + end + + def remove_tree0(path) + Dir.foreach(path) do |ent| + next if ent == '.' + next if ent == '..' + entpath = "#{path}/#{ent}" + if File.symlink?(entpath) + remove_file entpath + elsif File.dir?(entpath) + remove_tree0 entpath + else + force_remove_file entpath + end + end + begin + Dir.rmdir path + rescue Errno::ENOTEMPTY + # directory may not be empty + end + end + + def move_file(src, dest) + force_remove_file dest + begin + File.rename src, dest + rescue + File.open(dest, 'wb') {|f| + f.write File.binread(src) + } + File.chmod File.stat(src).mode, dest + File.unlink src + end + end + + def force_remove_file(path) + begin + remove_file path + rescue + end + end + + def remove_file(path) + File.chmod 0777, path + File.unlink path + end + + def install(from, dest, mode, prefix = nil) + $stderr.puts "install #{from} #{dest}" if verbose? + return if no_harm? + + realdest = prefix ? prefix + File.expand_path(dest) : dest + realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) + str = File.binread(from) + if diff?(str, realdest) + verbose_off { + rm_f realdest if File.exist?(realdest) + } + File.open(realdest, 'wb') {|f| + f.write str + } + File.chmod mode, realdest + + File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| + if prefix + f.puts realdest.sub(prefix, '') + else + f.puts realdest + end + } + end + end + + def diff?(new_content, path) + return true unless File.exist?(path) + new_content != File.binread(path) + end + + def command(*args) + $stderr.puts args.join(' ') if verbose? + system(*args) or raise RuntimeError, + "system(#{args.map{|a| a.inspect }.join(' ')}) failed" + end + + def ruby(*args) + command config('rubyprog'), *args + end + + def make(task = nil) + command(*[config('makeprog'), task].compact) + end + + def extdir?(dir) + File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") + end + + def files_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.file?("#{dir}/#{ent}") } + } + end + + DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) + + def directories_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT + } + end + +end + + +# This module requires: #srcdir_root, #objdir_root, #relpath +module HookScriptAPI + + def get_config(key) + @config[key] + end + + alias config get_config + + # obsolete: use metaconfig to change configuration + def set_config(key, val) + @config[key] = val + end + + # + # srcdir/objdir (works only in the package directory) + # + + def curr_srcdir + "#{srcdir_root()}/#{relpath()}" + end + + def curr_objdir + "#{objdir_root()}/#{relpath()}" + end + + def srcfile(path) + "#{curr_srcdir()}/#{path}" + end + + def srcexist?(path) + File.exist?(srcfile(path)) + end + + def srcdirectory?(path) + File.dir?(srcfile(path)) + end + + def srcfile?(path) + File.file?(srcfile(path)) + end + + def srcentries(path = '.') + Dir.open("#{curr_srcdir()}/#{path}") {|d| + return d.to_a - %w(. ..) + } + end + + def srcfiles(path = '.') + srcentries(path).select {|fname| + File.file?(File.join(curr_srcdir(), path, fname)) + } + end + + def srcdirectories(path = '.') + srcentries(path).select {|fname| + File.dir?(File.join(curr_srcdir(), path, fname)) + } + end + +end + + +class ToplevelInstaller + + Version = '3.4.1' + Copyright = 'Copyright (c) 2000-2005 Minero Aoki' + + TASKS = [ + [ 'all', 'do config, setup, then install' ], + [ 'config', 'saves your configurations' ], + [ 'show', 'shows current configuration' ], + [ 'setup', 'compiles ruby extentions and others' ], + [ 'install', 'installs files' ], + [ 'test', 'run all tests in test/' ], + [ 'clean', "does `make clean' for each extention" ], + [ 'distclean',"does `make distclean' for each extention" ] + ] + + def ToplevelInstaller.invoke + config = ConfigTable.new(load_rbconfig()) + config.load_standard_entries + config.load_multipackage_entries if multipackage? + config.fixup + klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) + klass.new(File.dirname($0), config).invoke + end + + def ToplevelInstaller.multipackage? + File.dir?(File.dirname($0) + '/packages') + end + + def ToplevelInstaller.load_rbconfig + if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } + ARGV.delete(arg) + load File.expand_path(arg.split(/=/, 2)[1]) + $".push 'rbconfig.rb' + else + require 'rbconfig' + end + ::Config::CONFIG + end + + def initialize(ardir_root, config) + @ardir = File.expand_path(ardir_root) + @config = config + # cache + @valid_task_re = nil + end + + def config(key) + @config[key] + end + + def inspect + "#<#{self.class} #{__id__()}>" + end + + def invoke + run_metaconfigs + case task = parsearg_global() + when nil, 'all' + parsearg_config + init_installers + exec_config + exec_setup + exec_install + else + case task + when 'config', 'test' + ; + when 'clean', 'distclean' + @config.load_savefile if File.exist?(@config.savefile) + else + @config.load_savefile + end + __send__ "parsearg_#{task}" + init_installers + __send__ "exec_#{task}" + end + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig" + end + + def init_installers + @installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + # + # Hook Script API bases + # + + def srcdir_root + @ardir + end + + def objdir_root + '.' + end + + def relpath + '.' + end + + # + # Option Parsing + # + + def parsearg_global + while arg = ARGV.shift + case arg + when /\A\w+\z/ + setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) + return arg + when '-q', '--quiet' + @config.verbose = false + when '--verbose' + @config.verbose = true + when '--help' + print_usage $stdout + exit 0 + when '--version' + puts "#{File.basename($0)} version #{Version}" + exit 0 + when '--copyright' + puts Copyright + exit 0 + else + setup_rb_error "unknown global option '#{arg}'" + end + end + nil + end + + def valid_task?(t) + valid_task_re() =~ t + end + + def valid_task_re + @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ + end + + def parsearg_no_options + unless ARGV.empty? + task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) + setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" + end + end + + alias parsearg_show parsearg_no_options + alias parsearg_setup parsearg_no_options + alias parsearg_test parsearg_no_options + alias parsearg_clean parsearg_no_options + alias parsearg_distclean parsearg_no_options + + def parsearg_config + evalopt = [] + set = [] + @config.config_opt = [] + while i = ARGV.shift + if /\A--?\z/ =~ i + @config.config_opt = ARGV.dup + break + end + name, value = *@config.parse_opt(i) + if @config.value_config?(name) + @config[name] = value + else + evalopt.push [name, value] + end + set.push name + end + evalopt.each do |name, value| + @config.lookup(name).evaluate value, @config + end + # Check if configuration is valid + set.each do |n| + @config[n] if @config.value_config?(n) + end + end + + def parsearg_install + @config.no_harm = false + @config.install_prefix = '' + while a = ARGV.shift + case a + when '--no-harm' + @config.no_harm = true + when /\A--prefix=/ + path = a.split(/=/, 2)[1] + path = File.expand_path(path) unless path[0,1] == '/' + @config.install_prefix = path + else + setup_rb_error "install: unknown option #{a}" + end + end + end + + def print_usage(out) + out.puts 'Typical Installation Procedure:' + out.puts " $ ruby #{File.basename $0} config" + out.puts " $ ruby #{File.basename $0} setup" + out.puts " # ruby #{File.basename $0} install (may require root privilege)" + out.puts + out.puts 'Detailed Usage:' + out.puts " ruby #{File.basename $0} <global option>" + out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" + + fmt = " %-24s %s\n" + out.puts + out.puts 'Global options:' + out.printf fmt, '-q,--quiet', 'suppress message outputs' + out.printf fmt, ' --verbose', 'output messages verbosely' + out.printf fmt, ' --help', 'print this message' + out.printf fmt, ' --version', 'print version and quit' + out.printf fmt, ' --copyright', 'print copyright and quit' + out.puts + out.puts 'Tasks:' + TASKS.each do |name, desc| + out.printf fmt, name, desc + end + + fmt = " %-24s %s [%s]\n" + out.puts + out.puts 'Options for CONFIG or ALL:' + @config.each do |item| + out.printf fmt, item.help_opt, item.description, item.help_default + end + out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" + out.puts + out.puts 'Options for INSTALL:' + out.printf fmt, '--no-harm', 'only display what to do if given', 'off' + out.printf fmt, '--prefix=path', 'install path prefix', '' + out.puts + end + + # + # Task Handlers + # + + def exec_config + @installer.exec_config + @config.save # must be final + end + + def exec_setup + @installer.exec_setup + end + + def exec_install + @installer.exec_install + end + + def exec_test + @installer.exec_test + end + + def exec_show + @config.each do |i| + printf "%-20s %s\n", i.name, i.value if i.value? + end + end + + def exec_clean + @installer.exec_clean + end + + def exec_distclean + @installer.exec_distclean + end + +end # class ToplevelInstaller + + +class ToplevelInstallerMulti < ToplevelInstaller + + include FileOperations + + def initialize(ardir_root, config) + super + @packages = directories_of("#{@ardir}/packages") + raise 'no package exists' if @packages.empty? + @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig", self + @packages.each do |name| + @config.load_script "#{@ardir}/packages/#{name}/metaconfig" + end + end + + attr_reader :packages + + def packages=(list) + raise 'package list is empty' if list.empty? + list.each do |name| + raise "directory packages/#{name} does not exist"\ + unless File.dir?("#{@ardir}/packages/#{name}") + end + @packages = list + end + + def init_installers + @installers = {} + @packages.each do |pack| + @installers[pack] = Installer.new(@config, + "#{@ardir}/packages/#{pack}", + "packages/#{pack}") + end + with = extract_selection(config('with')) + without = extract_selection(config('without')) + @selected = @installers.keys.select {|name| + (with.empty? or with.include?(name)) \ + and not without.include?(name) + } + end + + def extract_selection(list) + a = list.split(/,/) + a.each do |name| + setup_rb_error "no such package: #{name}" unless @installers.key?(name) + end + a + end + + def print_usage(f) + super + f.puts 'Inluded packages:' + f.puts ' ' + @packages.sort.join(' ') + f.puts + end + + # + # Task Handlers + # + + def exec_config + run_hook 'pre-config' + each_selected_installers {|inst| inst.exec_config } + run_hook 'post-config' + @config.save # must be final + end + + def exec_setup + run_hook 'pre-setup' + each_selected_installers {|inst| inst.exec_setup } + run_hook 'post-setup' + end + + def exec_install + run_hook 'pre-install' + each_selected_installers {|inst| inst.exec_install } + run_hook 'post-install' + end + + def exec_test + run_hook 'pre-test' + each_selected_installers {|inst| inst.exec_test } + run_hook 'post-test' + end + + def exec_clean + rm_f @config.savefile + run_hook 'pre-clean' + each_selected_installers {|inst| inst.exec_clean } + run_hook 'post-clean' + end + + def exec_distclean + rm_f @config.savefile + run_hook 'pre-distclean' + each_selected_installers {|inst| inst.exec_distclean } + run_hook 'post-distclean' + end + + # + # lib + # + + def each_selected_installers + Dir.mkdir 'packages' unless File.dir?('packages') + @selected.each do |pack| + $stderr.puts "Processing the package `#{pack}' ..." if verbose? + Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") + Dir.chdir "packages/#{pack}" + yield @installers[pack] + Dir.chdir '../..' + end + end + + def run_hook(id) + @root_installer.run_hook id + end + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + +end # class ToplevelInstallerMulti + + +class Installer + + FILETYPES = %w( bin lib ext data conf man ) + + include FileOperations + include HookScriptAPI + + def initialize(config, srcroot, objroot) + @config = config + @srcdir = File.expand_path(srcroot) + @objdir = File.expand_path(objroot) + @currdir = '.' + end + + def inspect + "#<#{self.class} #{File.basename(@srcdir)}>" + end + + def noop(rel) + end + + # + # Hook Script API base methods + # + + def srcdir_root + @srcdir + end + + def objdir_root + @objdir + end + + def relpath + @currdir + end + + # + # Config Access + # + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + + def verbose_off + begin + save, @config.verbose = @config.verbose?, false + yield + ensure + @config.verbose = save + end + end + + # + # TASK config + # + + def exec_config + exec_task_traverse 'config' + end + + alias config_dir_bin noop + alias config_dir_lib noop + + def config_dir_ext(rel) + extconf if extdir?(curr_srcdir()) + end + + alias config_dir_data noop + alias config_dir_conf noop + alias config_dir_man noop + + def extconf + ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt + end + + # + # TASK setup + # + + def exec_setup + exec_task_traverse 'setup' + end + + def setup_dir_bin(rel) + files_of(curr_srcdir()).each do |fname| + update_shebang_line "#{curr_srcdir()}/#{fname}" + end + end + + alias setup_dir_lib noop + + def setup_dir_ext(rel) + make if extdir?(curr_srcdir()) + end + + alias setup_dir_data noop + alias setup_dir_conf noop + alias setup_dir_man noop + + def update_shebang_line(path) + return if no_harm? + return if config('shebang') == 'never' + old = Shebang.load(path) + if old + $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 + new = new_shebang(old) + return if new.to_s == old.to_s + else + return unless config('shebang') == 'all' + new = Shebang.new(config('rubypath')) + end + $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? + open_atomic_writer(path) {|output| + File.open(path, 'rb') {|f| + f.gets if old # discard + output.puts new.to_s + output.print f.read + } + } + end + + def new_shebang(old) + if /\Aruby/ =~ File.basename(old.cmd) + Shebang.new(config('rubypath'), old.args) + elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' + Shebang.new(config('rubypath'), old.args[1..-1]) + else + return old unless config('shebang') == 'all' + Shebang.new(config('rubypath')) + end + end + + def open_atomic_writer(path, &block) + tmpfile = File.basename(path) + '.tmp' + begin + File.open(tmpfile, 'wb', &block) + File.rename tmpfile, File.basename(path) + ensure + File.unlink tmpfile if File.exist?(tmpfile) + end + end + + class Shebang + def Shebang.load(path) + line = nil + File.open(path) {|f| + line = f.gets + } + return nil unless /\A#!/ =~ line + parse(line) + end + + def Shebang.parse(line) + cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') + new(cmd, args) + end + + def initialize(cmd, args = []) + @cmd = cmd + @args = args + end + + attr_reader :cmd + attr_reader :args + + def to_s + "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") + end + end + + # + # TASK install + # + + def exec_install + rm_f 'InstalledFiles' + exec_task_traverse 'install' + end + + def install_dir_bin(rel) + install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 + end + + def install_dir_lib(rel) + install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 + end + + def install_dir_ext(rel) + return unless extdir?(curr_srcdir()) + install_files rubyextentions('.'), + "#{config('sodir')}/#{File.dirname(rel)}", + 0555 + end + + def install_dir_data(rel) + install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 + end + + def install_dir_conf(rel) + # FIXME: should not remove current config files + # (rename previous file to .old/.org) + install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 + end + + def install_dir_man(rel) + install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 + end + + def install_files(list, dest, mode) + mkdir_p dest, @config.install_prefix + list.each do |fname| + install fname, dest, mode, @config.install_prefix + end + end + + def libfiles + glob_reject(%w(*.y *.output), targetfiles()) + end + + def rubyextentions(dir) + ents = glob_select("*.#{@config.dllext}", targetfiles()) + if ents.empty? + setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" + end + ents + end + + def targetfiles + mapdir(existfiles() - hookfiles()) + end + + def mapdir(ents) + ents.map {|ent| + if File.exist?(ent) + then ent # objdir + else "#{curr_srcdir()}/#{ent}" # srcdir + end + } + end + + # picked up many entries from cvs-1.11.1/src/ignore.c + JUNK_FILES = %w( + core RCSLOG tags TAGS .make.state + .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb + *~ *.old *.bak *.BAK *.orig *.rej _$* *$ + + *.org *.in .* + ) + + def existfiles + glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) + end + + def hookfiles + %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| + %w( config setup install clean ).map {|t| sprintf(fmt, t) } + }.flatten + end + + def glob_select(pat, ents) + re = globs2re([pat]) + ents.select {|ent| re =~ ent } + end + + def glob_reject(pats, ents) + re = globs2re(pats) + ents.reject {|ent| re =~ ent } + end + + GLOB2REGEX = { + '.' => '\.', + '$' => '\$', + '#' => '\#', + '*' => '.*' + } + + def globs2re(pats) + /\A(?:#{ + pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') + })\z/ + end + + # + # TASK test + # + + TESTDIR = 'test' + + def exec_test + unless File.directory?('test') + $stderr.puts 'no test in this package' if verbose? + return + end + $stderr.puts 'Running tests...' if verbose? + begin + require 'test/unit' + rescue LoadError + setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' + end + runner = Test::Unit::AutoRunner.new(true) + runner.to_run << TESTDIR + runner.run + end + + # + # TASK clean + # + + def exec_clean + exec_task_traverse 'clean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias clean_dir_bin noop + alias clean_dir_lib noop + alias clean_dir_data noop + alias clean_dir_conf noop + alias clean_dir_man noop + + def clean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'clean' if File.file?('Makefile') + end + + # + # TASK distclean + # + + def exec_distclean + exec_task_traverse 'distclean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias distclean_dir_bin noop + alias distclean_dir_lib noop + + def distclean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'distclean' if File.file?('Makefile') + end + + alias distclean_dir_data noop + alias distclean_dir_conf noop + alias distclean_dir_man noop + + # + # Traversing + # + + def exec_task_traverse(task) + run_hook "pre-#{task}" + FILETYPES.each do |type| + if type == 'ext' and config('without-ext') == 'yes' + $stderr.puts 'skipping ext/* by user option' if verbose? + next + end + traverse task, type, "#{task}_dir_#{type}" + end + run_hook "post-#{task}" + end + + def traverse(task, rel, mid) + dive_into(rel) { + run_hook "pre-#{task}" + __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') + directories_of(curr_srcdir()).each do |d| + traverse task, "#{rel}/#{d}", mid + end + run_hook "post-#{task}" + } + end + + def dive_into(rel) + return unless File.dir?("#{@srcdir}/#{rel}") + + dir = File.basename(rel) + Dir.mkdir dir unless File.dir?(dir) + prevdir = Dir.pwd + Dir.chdir dir + $stderr.puts '---> ' + rel if verbose? + @currdir = rel + yield + Dir.chdir prevdir + $stderr.puts '<--- ' + rel if verbose? + @currdir = File.dirname(rel) + end + + def run_hook(id) + path = [ "#{curr_srcdir()}/#{id}", + "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } + return unless path + begin + instance_eval File.read(path), path, 1 + rescue + raise if $DEBUG + setup_rb_error "hook #{path} failed:\n" + $!.message + end + end + +end # class Installer + + +class SetupError < StandardError; end + +def setup_rb_error(msg) + raise SetupError, msg +end + +if $0 == __FILE__ + begin + ToplevelInstaller.invoke + rescue SetupError + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end diff --git a/pkg/base62-0.1.0/tasks/deployment.rake b/pkg/base62-0.1.0/tasks/deployment.rake new file mode 100644 index 0000000..2f43742 --- /dev/null +++ b/pkg/base62-0.1.0/tasks/deployment.rake @@ -0,0 +1,34 @@ +desc 'Release the website and new gem version' +task :deploy => [:check_version, :website, :release] do + puts "Remember to create SVN tag:" + puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " + puts "Suggested comment:" + puts "Tagging release #{CHANGES}" +end + +desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' +task :local_deploy => [:website_generate, :install_gem] + +task :check_version do + unless ENV['VERSION'] + puts 'Must pass a VERSION=x.y.z release version' + exit + end + unless ENV['VERSION'] == VERS + puts "Please update your version.rb to match the release version, currently #{VERS}" + exit + end +end + +desc 'Install the package as a gem, without generating documentation(ri/rdoc)' +task :install_gem_no_doc => [:clean, :package] do + sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" +end + +namespace :manifest do + desc 'Recreate Manifest.txt to include ALL files' + task :refresh do + `rake check_manifest | patch -p0 > Manifest.txt` + end +end \ No newline at end of file diff --git a/pkg/base62-0.1.0/tasks/environment.rake b/pkg/base62-0.1.0/tasks/environment.rake new file mode 100644 index 0000000..691ed3b --- /dev/null +++ b/pkg/base62-0.1.0/tasks/environment.rake @@ -0,0 +1,7 @@ +task :ruby_env do + RUBY_APP = if RUBY_PLATFORM =~ /java/ + "jruby" + else + "ruby" + end unless defined? RUBY_APP +end diff --git a/pkg/base62-0.1.0/tasks/website.rake b/pkg/base62-0.1.0/tasks/website.rake new file mode 100644 index 0000000..93e03fa --- /dev/null +++ b/pkg/base62-0.1.0/tasks/website.rake @@ -0,0 +1,17 @@ +desc 'Generate website files' +task :website_generate => :ruby_env do + (Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt| + sh %{ #{RUBY_APP} script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} } + end +end + +desc 'Upload website files to rubyforge' +task :website_upload do + host = "#{rubyforge_username}@rubyforge.org" + remote_dir = "/var/www/gforge-projects/#{PATH}/" + local_dir = 'website' + sh %{rsync -aCv #{local_dir}/ #{host}:#{remote_dir}} +end + +desc 'Generate and upload website files' +task :website => [:website_generate, :website_upload, :publish_docs] diff --git a/pkg/base62-0.1.0/test/test_base62.rb b/pkg/base62-0.1.0/test/test_base62.rb new file mode 100644 index 0000000..adf9138 --- /dev/null +++ b/pkg/base62-0.1.0/test/test_base62.rb @@ -0,0 +1,11 @@ +require File.dirname(__FILE__) + '/test_helper.rb' + +class TestBase62 < Test::Unit::TestCase + + def test_1_to_100000 + (0..100000).each do |i| + assert_equal(i.to_s, i.base62_encode.base62_decode.to_s, i.to_s + "\t" + i.base62_encode.to_s + "\t" + i.base62_encode.base62_decode.to_s) + end + end + +end diff --git a/pkg/base62-0.1.0/test/test_helper.rb b/pkg/base62-0.1.0/test/test_helper.rb new file mode 100644 index 0000000..efbfda5 --- /dev/null +++ b/pkg/base62-0.1.0/test/test_helper.rb @@ -0,0 +1,2 @@ +require 'test/unit' +require File.dirname(__FILE__) + '/../lib/base62' diff --git a/pkg/base62-0.1.0/website/index.html b/pkg/base62-0.1.0/website/index.html new file mode 100644 index 0000000..9246dcf --- /dev/null +++ b/pkg/base62-0.1.0/website/index.html @@ -0,0 +1,10 @@ +<html> + <head> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>base62 ruby gem</title> + + </head> + <body id="body"> + <p>This gem monkeypatches Integer and String to encode integers into a base62 0-9 + A-Z + a-z string format and decode strings in this format back into integers.</p> + </body> +</html> \ No newline at end of file diff --git a/pkg/base62-0.1.0/website/index.txt b/pkg/base62-0.1.0/website/index.txt new file mode 100644 index 0000000..a997068 --- /dev/null +++ b/pkg/base62-0.1.0/website/index.txt @@ -0,0 +1,47 @@ +h1. base62 + +h1. &#x2192; 'base62' + + +h2. What + +The base62 gem monkeypatches Integer and String. It creates an Integer#base62_encode instance method to encode integers into a string with this set of characters: 0-9 + A-Z + a-z. It also creates a String#base62_decode method to reverse the encoded string back into an integer. + +I created this gem library to be the basis of a URL minifying product and service that I'll release and host soon. + +h2. Installing + +<pre syntax="ruby">sudo gem install base62</pre> + +h2. The basics + + +h2. Developer's Site + +"http://geekjacking.com/base62_gem":http://geekjacking.com/base62_gem + +h2. How to submit patches + +Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/. It's good, but doesn't have instructions for GitHub, so come back here after you're done and read on. + +If you want to submit patches, the project code is on GitHub. Here are good instructions for submitting patches through GitHub: http://github.com/guides/fork-a-project-and-submit-your-modifications + +* github: "http://github.com/jtzemp/base62/tree/master":http://github.com/jtzemp/base62/tree/master + +<pre>git clone git://github.com/jtzemp/base62.git</pre> + +h3. Build and test instructions + +<pre>cd base62 +rake test +rake install_gem</pre> + + +h2. License + +This code is free to use under the terms of the MIT license. + +h2. Contact + +Comments are welcome. Send an email to "JT Zemp":mailto:jt.zemp@thriveis.com, or go to http://geekjacking.com/base62_gem and leave a comment there. + diff --git a/pkg/base62-0.1.0/website/javascripts/rounded_corners_lite.inc.js b/pkg/base62-0.1.0/website/javascripts/rounded_corners_lite.inc.js new file mode 100644 index 0000000..afc3ea3 --- /dev/null +++ b/pkg/base62-0.1.0/website/javascripts/rounded_corners_lite.inc.js @@ -0,0 +1,285 @@ + + /**************************************************************** + * * + * curvyCorners * + * ------------ * + * * + * This script generates rounded corners for your divs. * + * * + * Version 1.2.9 * + * Copyright (c) 2006 Cameron Cooke * + * By: Cameron Cooke and Tim Hutchison. * + * * + * * + * Website: http://www.curvycorners.net * + * Email: info@totalinfinity.com * + * Forum: http://www.curvycorners.net/forum/ * + * * + * * + * This library is free software; you can redistribute * + * it and/or modify it under the terms of the GNU * + * Lesser General Public License as published by the * + * Free Software Foundation; either version 2.1 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 Lesser General Public * + * License for more details. * + * * + * You should have received a copy of the GNU Lesser * + * General Public License along with this library; * + * Inc., 59 Temple Place, Suite 330, Boston, * + * MA 02111-1307 USA * + * * + ****************************************************************/ + +var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1; var isMoz = document.implementation && document.implementation.createDocument; var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false; function curvyCorners() +{ if(typeof(arguments[0]) != "object") throw newCurvyError("First parameter of curvyCorners() must be an object."); if(typeof(arguments[1]) != "object" && typeof(arguments[1]) != "string") throw newCurvyError("Second parameter of curvyCorners() must be an object or a class name."); if(typeof(arguments[1]) == "string") +{ var startIndex = 0; var boxCol = getElementsByClass(arguments[1]);} +else +{ var startIndex = 1; var boxCol = arguments;} +var curvyCornersCol = new Array(); if(arguments[0].validTags) +var validElements = arguments[0].validTags; else +var validElements = ["div"]; for(var i = startIndex, j = boxCol.length; i < j; i++) +{ var currentTag = boxCol[i].tagName.toLowerCase(); if(inArray(validElements, currentTag) !== false) +{ curvyCornersCol[curvyCornersCol.length] = new curvyObject(arguments[0], boxCol[i]);} +} +this.objects = curvyCornersCol; this.applyCornersToAll = function() +{ for(var x = 0, k = this.objects.length; x < k; x++) +{ this.objects[x].applyCorners();} +} +} +function curvyObject() +{ this.box = arguments[1]; this.settings = arguments[0]; this.topContainer = null; this.bottomContainer = null; this.masterCorners = new Array(); this.contentDIV = null; var boxHeight = get_style(this.box, "height", "height"); var boxWidth = get_style(this.box, "width", "width"); var borderWidth = get_style(this.box, "borderTopWidth", "border-top-width"); var borderColour = get_style(this.box, "borderTopColor", "border-top-color"); var boxColour = get_style(this.box, "backgroundColor", "background-color"); var backgroundImage = get_style(this.box, "backgroundImage", "background-image"); var boxPosition = get_style(this.box, "position", "position"); var boxPadding = get_style(this.box, "paddingTop", "padding-top"); this.boxHeight = parseInt(((boxHeight != "" && boxHeight != "auto" && boxHeight.indexOf("%") == -1)? boxHeight.substring(0, boxHeight.indexOf("px")) : this.box.scrollHeight)); this.boxWidth = parseInt(((boxWidth != "" && boxWidth != "auto" && boxWidth.indexOf("%") == -1)? boxWidth.substring(0, boxWidth.indexOf("px")) : this.box.scrollWidth)); this.borderWidth = parseInt(((borderWidth != "" && borderWidth.indexOf("px") !== -1)? borderWidth.slice(0, borderWidth.indexOf("px")) : 0)); this.boxColour = format_colour(boxColour); this.boxPadding = parseInt(((boxPadding != "" && boxPadding.indexOf("px") !== -1)? boxPadding.slice(0, boxPadding.indexOf("px")) : 0)); this.borderColour = format_colour(borderColour); this.borderString = this.borderWidth + "px" + " solid " + this.borderColour; this.backgroundImage = ((backgroundImage != "none")? backgroundImage : ""); this.boxContent = this.box.innerHTML; if(boxPosition != "absolute") this.box.style.position = "relative"; this.box.style.padding = "0px"; if(isIE && boxWidth == "auto" && boxHeight == "auto") this.box.style.width = "100%"; if(this.settings.autoPad == true && this.boxPadding > 0) +this.box.innerHTML = ""; this.applyCorners = function() +{ for(var t = 0; t < 2; t++) +{ switch(t) +{ case 0: +if(this.settings.tl || this.settings.tr) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0); newMainContainer.style.height = topMaxRadius + "px"; newMainContainer.style.top = 0 - topMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.topContainer = this.box.appendChild(newMainContainer);} +break; case 1: +if(this.settings.bl || this.settings.br) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0); newMainContainer.style.height = botMaxRadius + "px"; newMainContainer.style.bottom = 0 - botMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.bottomContainer = this.box.appendChild(newMainContainer);} +break;} +} +if(this.topContainer) this.box.style.borderTopWidth = "0px"; if(this.bottomContainer) this.box.style.borderBottomWidth = "0px"; var corners = ["tr", "tl", "br", "bl"]; for(var i in corners) +{ if(i > -1 < 4) +{ var cc = corners[i]; if(!this.settings[cc]) +{ if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null)) +{ var newCorner = document.createElement("DIV"); newCorner.style.position = "relative"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; if(this.backgroundImage == "") +newCorner.style.backgroundColor = this.boxColour; else +newCorner.style.backgroundImage = this.backgroundImage; switch(cc) +{ case "tl": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.tr.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.left = -this.borderWidth + "px"; break; case "tr": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.tl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; newCorner.style.left = this.borderWidth + "px"; break; case "bl": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.br.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = -this.borderWidth + "px"; newCorner.style.backgroundPosition = "-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break; case "br": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.bl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = this.borderWidth + "px" +newCorner.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break;} +} +} +else +{ if(this.masterCorners[this.settings[cc].radius]) +{ var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);} +else +{ var newCorner = document.createElement("DIV"); newCorner.style.height = this.settings[cc].radius + "px"; newCorner.style.width = this.settings[cc].radius + "px"; newCorner.style.position = "absolute"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth); for(var intx = 0, j = this.settings[cc].radius; intx < j; intx++) +{ if((intx +1) >= borderRadius) +var y1 = -1; else +var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1); if(borderRadius != j) +{ if((intx) >= borderRadius) +var y2 = -1; else +var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2))); if((intx+1) >= j) +var y3 = -1; else +var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);} +if((intx) >= j) +var y4 = -1; else +var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2))); if(y1 > -1) this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius); if(borderRadius != j) +{ for(var inty = (y1 + 1); inty < y2; inty++) +{ if(this.settings.antiAlias) +{ if(this.backgroundImage != "") +{ var borderFract = (pixelFraction(intx, inty, borderRadius) * 100); if(borderFract < 30) +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);} +else +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);} +} +else +{ var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius)); this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);} +} +} +if(this.settings.antiAlias) +{ if(y3 >= y2) +{ if (y2 == -1) y2 = 0; this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);} +} +else +{ if(y3 >= y1) +{ this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);} +} +var outsideColour = this.borderColour;} +else +{ var outsideColour = this.boxColour; var y3 = y1;} +if(this.settings.antiAlias) +{ for(var inty = (y3 + 1); inty < y4; inty++) +{ this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);} +} +} +this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);} +if(cc != "br") +{ for(var t = 0, k = newCorner.childNodes.length; t < k; t++) +{ var pixelBar = newCorner.childNodes[t]; var pixelBarTop = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px"))); var pixelBarLeft = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px"))); var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px"))); if(cc == "tl" || cc == "bl"){ pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px";} +if(cc == "tr" || cc == "tl"){ pixelBar.style.top = this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px";} +switch(cc) +{ case "tr": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "tl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "bl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px"; break;} +} +} +} +if(newCorner) +{ switch(cc) +{ case "tl": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "tr": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "bl": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break; case "br": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break;} +} +} +} +var radiusDiff = new Array(); radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius) +radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius); for(z in radiusDiff) +{ if(z == "t" || z == "b") +{ if(radiusDiff[z]) +{ var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius)? z +"l" : z +"r"); var newFiller = document.createElement("DIV"); newFiller.style.height = radiusDiff[z] + "px"; newFiller.style.width = this.settings[smallerCornerType].radius+ "px" +newFiller.style.position = "absolute"; newFiller.style.fontSize = "1px"; newFiller.style.overflow = "hidden"; newFiller.style.backgroundColor = this.boxColour; switch(smallerCornerType) +{ case "tl": +newFiller.style.bottom = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.topContainer.appendChild(newFiller); break; case "tr": +newFiller.style.bottom = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.topContainer.appendChild(newFiller); break; case "bl": +newFiller.style.top = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.bottomContainer.appendChild(newFiller); break; case "br": +newFiller.style.top = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.bottomContainer.appendChild(newFiller); break;} +} +var newFillerBar = document.createElement("DIV"); newFillerBar.style.position = "relative"; newFillerBar.style.fontSize = "1px"; newFillerBar.style.overflow = "hidden"; newFillerBar.style.backgroundColor = this.boxColour; newFillerBar.style.backgroundImage = this.backgroundImage; switch(z) +{ case "t": +if(this.topContainer) +{ if(this.settings.tl.radius && this.settings.tr.radius) +{ newFillerBar.style.height = topMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.tl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.tr.radius - this.borderWidth + "px"; newFillerBar.style.borderTop = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; this.topContainer.appendChild(newFillerBar);} +this.box.style.backgroundPosition = "0px -" + (topMaxRadius - this.borderWidth) + "px";} +break; case "b": +if(this.bottomContainer) +{ if(this.settings.bl.radius && this.settings.br.radius) +{ newFillerBar.style.height = botMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.bl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.br.radius - this.borderWidth + "px"; newFillerBar.style.borderBottom = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (topMaxRadius + this.borderWidth)) + "px"; this.bottomContainer.appendChild(newFillerBar);} +} +break;} +} +} +if(this.settings.autoPad == true && this.boxPadding > 0) +{ var contentContainer = document.createElement("DIV"); contentContainer.style.position = "relative"; contentContainer.innerHTML = this.boxContent; contentContainer.className = "autoPadDiv"; var topPadding = Math.abs(topMaxRadius - this.boxPadding); var botPadding = Math.abs(botMaxRadius - this.boxPadding); if(topMaxRadius < this.boxPadding) +contentContainer.style.paddingTop = topPadding + "px"; if(botMaxRadius < this.boxPadding) +contentContainer.style.paddingBottom = botMaxRadius + "px"; contentContainer.style.paddingLeft = this.boxPadding + "px"; contentContainer.style.paddingRight = this.boxPadding + "px"; this.contentDIV = this.box.appendChild(contentContainer);} +} +this.drawPixel = function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius) +{ var pixel = document.createElement("DIV"); pixel.style.height = height + "px"; pixel.style.width = "1px"; pixel.style.position = "absolute"; pixel.style.fontSize = "1px"; pixel.style.overflow = "hidden"; var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius); if(image == -1 && this.backgroundImage != "") +{ pixel.style.backgroundImage = this.backgroundImage; pixel.style.backgroundPosition = "-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px";} +else +{ pixel.style.backgroundColor = colour;} +if (transAmount != 100) +setOpacity(pixel, transAmount); pixel.style.top = inty + "px"; pixel.style.left = intx + "px"; newCorner.appendChild(pixel);} +} +function insertAfter(parent, node, referenceNode) +{ parent.insertBefore(node, referenceNode.nextSibling);} +function BlendColour(Col1, Col2, Col1Fraction) +{ var red1 = parseInt(Col1.substr(1,2),16); var green1 = parseInt(Col1.substr(3,2),16); var blue1 = parseInt(Col1.substr(5,2),16); var red2 = parseInt(Col2.substr(1,2),16); var green2 = parseInt(Col2.substr(3,2),16); var blue2 = parseInt(Col2.substr(5,2),16); if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1; var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction))); if(endRed > 255) endRed = 255; if(endRed < 0) endRed = 0; var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction))); if(endGreen > 255) endGreen = 255; if(endGreen < 0) endGreen = 0; var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction))); if(endBlue > 255) endBlue = 255; if(endBlue < 0) endBlue = 0; return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);} +function IntToHex(strNum) +{ base = strNum / 16; rem = strNum % 16; base = base - (rem / 16); baseS = MakeHex(base); remS = MakeHex(rem); return baseS + '' + remS;} +function MakeHex(x) +{ if((x >= 0) && (x <= 9)) +{ return x;} +else +{ switch(x) +{ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F";} +} +} +function pixelFraction(x, y, r) +{ var pixelfraction = 0; var xvalues = new Array(1); var yvalues = new Array(1); var point = 0; var whatsides = ""; var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = "Left"; xvalues[point] = 0; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Top"; xvalues[point] = intersect - x; yvalues[point] = 1; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = whatsides + "Right"; xvalues[point] = 1; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Bottom"; xvalues[point] = intersect - x; yvalues[point] = 0;} +switch (whatsides) +{ case "LeftRight": +pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2); break; case "TopRight": +pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2); break; case "TopBottom": +pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2); break; case "LeftBottom": +pixelfraction = (yvalues[0]*xvalues[1])/2; break; default: +pixelfraction = 1;} +return pixelfraction;} +function rgb2Hex(rgbColour) +{ try{ var rgbArray = rgb2Array(rgbColour); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);} +catch(e){ alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");} +return hexColour;} +function rgb2Array(rgbColour) +{ var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")")); var rgbArray = rgbValues.split(", "); return rgbArray;} +function setOpacity(obj, opacity) +{ opacity = (opacity == 100)?99.999:opacity; if(isSafari && obj.tagName != "IFRAME") +{ var rgbArray = rgb2Array(obj.style.backgroundColor); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";} +else if(typeof(obj.style.opacity) != "undefined") +{ obj.style.opacity = opacity/100;} +else if(typeof(obj.style.MozOpacity) != "undefined") +{ obj.style.MozOpacity = opacity/100;} +else if(typeof(obj.style.filter) != "undefined") +{ obj.style.filter = "alpha(opacity:" + opacity + ")";} +else if(typeof(obj.style.KHTMLOpacity) != "undefined") +{ obj.style.KHTMLOpacity = opacity/100;} +} +function inArray(array, value) +{ for(var i = 0; i < array.length; i++){ if (array[i] === value) return i;} +return false;} +function inArrayKey(array, value) +{ for(key in array){ if(key === value) return true;} +return false;} +function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true;} +else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r;} +else { elm['on' + evType] = fn;} +} +function removeEvent(obj, evType, fn, useCapture){ if (obj.removeEventListener){ obj.removeEventListener(evType, fn, useCapture); return true;} else if (obj.detachEvent){ var r = obj.detachEvent("on"+evType, fn); return r;} else { alert("Handler could not be removed");} +} +function format_colour(colour) +{ var returnColour = "#ffffff"; if(colour != "" && colour != "transparent") +{ if(colour.substr(0, 3) == "rgb") +{ returnColour = rgb2Hex(colour);} +else if(colour.length == 4) +{ returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);} +else +{ returnColour = colour;} +} +return returnColour;} +function get_style(obj, property, propertyNS) +{ try +{ if(obj.currentStyle) +{ var returnVal = eval("obj.currentStyle." + property);} +else +{ if(isSafari && obj.style.display == "none") +{ obj.style.display = ""; var wasHidden = true;} +var returnVal = document.defaultView.getComputedStyle(obj, '').getPropertyValue(propertyNS); if(isSafari && wasHidden) +{ obj.style.display = "none";} +} +} +catch(e) +{ } +return returnVal;} +function getElementsByClass(searchClass, node, tag) +{ var classElements = new Array(); if(node == null) +node = document; if(tag == null) +tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)"); for (i = 0, j = 0; i < elsLen; i++) +{ if(pattern.test(els[i].className)) +{ classElements[j] = els[i]; j++;} +} +return classElements;} +function newCurvyError(errorMessage) +{ return new Error("curvyCorners Error:\n" + errorMessage) +} diff --git a/pkg/base62-0.1.0/website/stylesheets/screen.css b/pkg/base62-0.1.0/website/stylesheets/screen.css new file mode 100644 index 0000000..2c84cd0 --- /dev/null +++ b/pkg/base62-0.1.0/website/stylesheets/screen.css @@ -0,0 +1,138 @@ +body { + background-color: #E1D1F1; + font-family: "Georgia", sans-serif; + font-size: 16px; + line-height: 1.6em; + padding: 1.6em 0 0 0; + color: #333; +} +h1, h2, h3, h4, h5, h6 { + color: #444; +} +h1 { + font-family: sans-serif; + font-weight: normal; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin: 5px; +} +li { + padding: 0; + margin: 0; + list-style-type: square; +} +a { + color: #5E5AFF; + background-color: #DAC; + font-weight: normal; + text-decoration: underline; +} +blockquote { + font-size: 90%; + font-style: italic; + border-left: 1px solid #111; + padding-left: 1em; +} +.caps { + font-size: 80%; +} + +#main { + width: 45em; + padding: 0; + margin: 0 auto; +} +.coda { + text-align: right; + color: #77f; + font-size: smaller; +} + +table { + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; + border-style: dashed; +} + +th { + color: #fff; +} + +td { + padding: 2px 10px 2px 10px; +} + +.success { + color: #0CC52B; +} + +.failed { + color: #E90A1B; +} + +.unknown { + color: #995000; +} +pre, code { + font-family: monospace; + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; +} +.comment { color: #aaa; font-style: italic; } +.keyword { color: #eff; font-weight: bold; } +.punct { color: #eee; font-weight: bold; } +.symbol { color: #0bb; } +.string { color: #6b4; } +.ident { color: #ff8; } +.constant { color: #66f; } +.regex { color: #ec6; } +.number { color: #F99; } +.expr { color: #227; } + +#version { + float: right; + text-align: right; + font-family: sans-serif; + font-weight: normal; + background-color: #B3ABFF; + color: #141331; + padding: 15px 20px 10px 20px; + margin: 0 auto; + margin-top: 15px; + border: 3px solid #141331; +} + +#version .numbers { + display: block; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin-bottom: 15px; +} + +#version p { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; + margin: 0; + padding: 0; +} + +#version a { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; +} + +.clickable { + cursor: pointer; + cursor: hand; +} + diff --git a/pkg/base62-0.1.0/website/template.html.erb b/pkg/base62-0.1.0/website/template.html.erb new file mode 100644 index 0000000..e851735 --- /dev/null +++ b/pkg/base62-0.1.0/website/template.html.erb @@ -0,0 +1,48 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title> + <%= title %> + </title> + <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> +<style> + +</style> + <script type="text/javascript"> + window.onload = function() { + settings = { + tl: { radius: 10 }, + tr: { radius: 10 }, + bl: { radius: 10 }, + br: { radius: 10 }, + antiAlias: true, + autoPad: true, + validTags: ["div"] + } + var versionBox = new curvyCorners(settings, document.getElementById("version")); + versionBox.applyCornersToAll(); + } + </script> +</head> +<body> +<div id="main"> + + <h1><%= title %></h1> + <div id="version" class="clickable" onclick='document.location = "<%= download %>"; return false'> + <p>Get Version</p> + <a href="<%= download %>" class="numbers"><%= version %></a> + </div> + <%= body %> + <p class="coda"> + <a href="FIXME email">FIXME full name</a>, <%= modified.pretty %><br> + Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> + </p> +</div> + +<!-- insert site tracking codes here, like Google Urchin --> + +</body> +</html>
jtzemp/base62
6ebe04fe9f3221b0b40f6ecdb4ce4426b190276d
added gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ccc9fd9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.DS_Store \ No newline at end of file
jtzemp/base62
958c6691e3cd88a3ca101aa8892b77c74d135bd3
initial import
diff --git a/History.txt b/History.txt new file mode 100644 index 0000000..9993927 --- /dev/null +++ b/History.txt @@ -0,0 +1,4 @@ +== 0.1.0 2008-10-04 + +* 1 major enhancement: + * Initial release diff --git a/Manifest.txt b/Manifest.txt new file mode 100644 index 0000000..858c11f --- /dev/null +++ b/Manifest.txt @@ -0,0 +1,24 @@ +History.txt +Manifest.txt +PostInstall.txt +README.rdoc +Rakefile +config/hoe.rb +config/requirements.rb +lib/base62.rb +lib/base62/version.rb +script/console +script/destroy +script/generate +script/txt2html +setup.rb +tasks/deployment.rake +tasks/environment.rake +tasks/website.rake +test/test_base62.rb +test/test_helper.rb +website/index.html +website/index.txt +website/javascripts/rounded_corners_lite.inc.js +website/stylesheets/screen.css +website/template.html.erb diff --git a/PostInstall.txt b/PostInstall.txt new file mode 100644 index 0000000..24a599a --- /dev/null +++ b/PostInstall.txt @@ -0,0 +1,7 @@ + +For more information on base62, see http://base62.rubyforge.org + +NOTE: Change this information in PostInstall.txt +You can also delete it if you don't want it. + + diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..f95e035 --- /dev/null +++ b/README.rdoc @@ -0,0 +1,48 @@ += base62 + +* FIX (url) + +== DESCRIPTION: + +FIX (describe your package) + +== FEATURES/PROBLEMS: + +* FIX (list of features or problems) + +== SYNOPSIS: + + FIX (code sample of usage) + +== REQUIREMENTS: + +* FIX (list of requirements) + +== INSTALL: + +* FIX (sudo gem install, anything else) + +== LICENSE: + +(The MIT License) + +Copyright (c) 2008 FIXME full name + +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. \ No newline at end of file diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..e469154 --- /dev/null +++ b/Rakefile @@ -0,0 +1,4 @@ +require 'config/requirements' +require 'config/hoe' # setup Hoe + all gem configuration + +Dir['tasks/**/*.rake'].each { |rake| load rake } \ No newline at end of file diff --git a/config/hoe.rb b/config/hoe.rb new file mode 100644 index 0000000..6ec6d1b --- /dev/null +++ b/config/hoe.rb @@ -0,0 +1,73 @@ +require 'base62/version' + +AUTHOR = 'FIXME full name' # can also be an array of Authors +EMAIL = "FIXME email" +DESCRIPTION = "description of gem" +GEM_NAME = 'base62' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'base62' # The unix name for your project +HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" +DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" +EXTRA_DEPENDENCIES = [ +# ['activesupport', '>= 1.3.1'] +] # An array of rubygem dependencies [name, version] + +@config_file = "~/.rubyforge/user-config.yml" +@config = nil +RUBYFORGE_USERNAME = "unknown" +def rubyforge_username + unless @config + begin + @config = YAML.load(File.read(File.expand_path(@config_file))) + rescue + puts <<-EOS +ERROR: No rubyforge config file found: #{@config_file} +Run 'rubyforge setup' to prepare your env for access to Rubyforge + - See http://newgem.rubyforge.org/rubyforge.html for more details + EOS + exit + end + end + RUBYFORGE_USERNAME.replace @config["username"] +end + + +REV = nil +# UNCOMMENT IF REQUIRED: +# REV = YAML.load(`svn info`)['Revision'] +VERS = Base62::VERSION::STRING + (REV ? ".#{REV}" : "") +RDOC_OPTS = ['--quiet', '--title', 'base62 documentation', + "--opname", "index.html", + "--line-numbers", + "--main", "README", + "--inline-source"] + +class Hoe + def extra_deps + @extra_deps.reject! { |x| Array(x).first == 'hoe' } + @extra_deps + end +end + +# Generate all the Rake tasks +# Run 'rake -T' to see list of generated tasks (from gem root directory) +$hoe = Hoe.new(GEM_NAME, VERS) do |p| + p.developer(AUTHOR, EMAIL) + p.description = DESCRIPTION + p.summary = DESCRIPTION + p.url = HOMEPATH + p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT + p.test_globs = ["test/**/test_*.rb"] + p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. + + # == Optional + p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") + #p.extra_deps = EXTRA_DEPENDENCIES + + #p.spec_extras = {} # A hash of extra values to set in the gemspec. + end + +CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") +PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" +$hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') +$hoe.rsync_args = '-av --delete --ignore-errors' +$hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue "" \ No newline at end of file diff --git a/config/requirements.rb b/config/requirements.rb new file mode 100644 index 0000000..9292b69 --- /dev/null +++ b/config/requirements.rb @@ -0,0 +1,15 @@ +require 'fileutils' +include FileUtils + +require 'rubygems' +%w[rake hoe newgem rubigen].each do |req_gem| + begin + require req_gem + rescue LoadError + puts "This Rakefile requires the '#{req_gem}' RubyGem." + puts "Installation: gem install #{req_gem} -y" + exit + end +end + +$:.unshift(File.join(File.dirname(__FILE__), %w[.. lib])) diff --git a/lib/base62.rb b/lib/base62.rb new file mode 100644 index 0000000..2f0f753 --- /dev/null +++ b/lib/base62.rb @@ -0,0 +1,101 @@ +$:.unshift(File.dirname(__FILE__)) unless + $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) + +module Base62 + +end + +#!/usr/bin/env ruby + +class String + BASE62_PRIMITIVES = { + "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, + "M" => 22, + "N" => 23, + "O" => 24, + "P" => 25, + "Q" => 26, + "R" => 27, + "S" => 28, + "T" => 29, + "U" => 30, + "V" => 31, + "W" => 32, + "X" => 33, + "Y" => 34, + "Z" => 35, + "a" => 36, + "b" => 37, + "c" => 38, + "d" => 39, + "e" => 40, + "f" => 41 , + "g" => 42 , + "h" => 43 , + "i" => 44 , + "j" => 45 , + "k" => 46 , + "l" => 47 , + "m" => 48 , + "n" => 49 , + "o" => 50, + "p" => 51, + "q" => 52, + "r" => 53, + "s" => 54, + "t" => 55, + "u" => 56, + "v" => 57, + "w" => 58, + "x" => 59, + "y" => 60, + "z" => 61 + } + + def base62_decode + i = 0 + i_out = 0 + self.split(//).reverse.each do |c| + place = BASE62_PRIMITIVES.size ** i + i_out += BASE62_PRIMITIVES[c] * place + i += 1 + end + i_out + end +end + + +class Integer + BASE62_PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').collect + ('a'..'z').collect + + def base62_encode + number = self + result = '' + while(number != 0) + result = BASE62_PRIMITIVES[number % BASE62_PRIMITIVES.size ].to_s + result + number /= BASE62_PRIMITIVES.size + end + result + end +end diff --git a/lib/base62/version.rb b/lib/base62/version.rb new file mode 100644 index 0000000..0b2a386 --- /dev/null +++ b/lib/base62/version.rb @@ -0,0 +1,10 @@ +module Base62 + module VERSION #:nodoc: + MAJOR = 0 + MINOR = 1 + TINY = 0 + + STRING = [MAJOR, MINOR, TINY].join('.') + self + end +end diff --git a/script/console b/script/console new file mode 100755 index 0000000..0e2f259 --- /dev/null +++ b/script/console @@ -0,0 +1,10 @@ +#!/usr/bin/env ruby +# File: script/console +irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb' + +libs = " -r irb/completion" +# Perhaps use a console_lib to store any extra methods I may want available in the cosole +# libs << " -r #{File.dirname(__FILE__) + '/../lib/console_lib/console_logger.rb'}" +libs << " -r #{File.dirname(__FILE__) + '/../lib/base62.rb'}" +puts "Loading base62 gem" +exec "#{irb} #{libs} --simple-prompt" \ No newline at end of file diff --git a/script/destroy b/script/destroy new file mode 100755 index 0000000..e48464d --- /dev/null +++ b/script/destroy @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/destroy' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/script/generate b/script/generate new file mode 100755 index 0000000..c27f655 --- /dev/null +++ b/script/generate @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/generate' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/script/txt2html b/script/txt2html new file mode 100755 index 0000000..d3a4801 --- /dev/null +++ b/script/txt2html @@ -0,0 +1,82 @@ +#!/usr/bin/env ruby + +GEM_NAME = 'base62' # what ppl will type to install your gem +RUBYFORGE_PROJECT = 'base62' + +require 'rubygems' +begin + require 'newgem' + require 'rubyforge' +rescue LoadError + puts "\n\nGenerating the website requires the newgem RubyGem" + puts "Install: gem install newgem\n\n" + exit(1) +end +require 'redcloth' +require 'syntax/convertors/html' +require 'erb' +require File.dirname(__FILE__) + "/../lib/#{GEM_NAME}/version.rb" + +version = Base62::VERSION::STRING +download = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" + +def rubyforge_project_id + RubyForge.new.configure.autoconfig["group_ids"][RUBYFORGE_PROJECT] +end + +class Fixnum + def ordinal + # teens + return 'th' if (10..19).include?(self % 100) + # others + case self % 10 + when 1: return 'st' + when 2: return 'nd' + when 3: return 'rd' + else return 'th' + end + end +end + +class Time + def pretty + return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}" + end +end + +def convert_syntax(syntax, source) + return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'') +end + +if ARGV.length >= 1 + src, template = ARGV + template ||= File.join(File.dirname(__FILE__), '/../website/template.html.erb') +else + puts("Usage: #{File.split($0).last} source.txt [template.html.erb] > output.html") + exit! +end + +template = ERB.new(File.open(template).read) + +title = nil +body = nil +File.open(src) do |fsrc| + title_text = fsrc.readline + body_text_template = fsrc.read + body_text = ERB.new(body_text_template).result(binding) + syntax_items = [] + body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){ + ident = syntax_items.length + element, syntax, source = $1, $2, $3 + syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>" + "syntax-temp-#{ident}" + } + title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip + body = RedCloth.new(body_text).to_html + body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] } +end +stat = File.stat(src) +created = stat.ctime +modified = stat.mtime + +$stdout << template.result(binding) diff --git a/setup.rb b/setup.rb new file mode 100644 index 0000000..424a5f3 --- /dev/null +++ b/setup.rb @@ -0,0 +1,1585 @@ +# +# setup.rb +# +# Copyright (c) 2000-2005 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the terms of +# the GNU LGPL, Lesser General Public License version 2.1. +# + +unless Enumerable.method_defined?(:map) # Ruby 1.4.6 + module Enumerable + alias map collect + end +end + +unless File.respond_to?(:read) # Ruby 1.6 + def File.read(fname) + open(fname) {|f| + return f.read + } + end +end + +unless Errno.const_defined?(:ENOTEMPTY) # Windows? + module Errno + class ENOTEMPTY + # We do not raise this exception, implementation is not needed. + end + end +end + +def File.binread(fname) + open(fname, 'rb') {|f| + return f.read + } +end + +# for corrupted Windows' stat(2) +def File.dir?(path) + File.directory?((path[-1,1] == '/') ? path : path + '/') +end + + +class ConfigTable + + include Enumerable + + def initialize(rbconfig) + @rbconfig = rbconfig + @items = [] + @table = {} + # options + @install_prefix = nil + @config_opt = nil + @verbose = true + @no_harm = false + end + + attr_accessor :install_prefix + attr_accessor :config_opt + + attr_writer :verbose + + def verbose? + @verbose + end + + attr_writer :no_harm + + def no_harm? + @no_harm + end + + def [](key) + lookup(key).resolve(self) + end + + def []=(key, val) + lookup(key).set val + end + + def names + @items.map {|i| i.name } + end + + def each(&block) + @items.each(&block) + end + + def key?(name) + @table.key?(name) + end + + def lookup(name) + @table[name] or setup_rb_error "no such config item: #{name}" + end + + def add(item) + @items.push item + @table[item.name] = item + end + + def remove(name) + item = lookup(name) + @items.delete_if {|i| i.name == name } + @table.delete_if {|name, i| i.name == name } + item + end + + def load_script(path, inst = nil) + if File.file?(path) + MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path + end + end + + def savefile + '.config' + end + + def load_savefile + begin + File.foreach(savefile()) do |line| + k, v = *line.split(/=/, 2) + self[k] = v.strip + end + rescue Errno::ENOENT + setup_rb_error $!.message + "\n#{File.basename($0)} config first" + end + end + + def save + @items.each {|i| i.value } + File.open(savefile(), 'w') {|f| + @items.each do |i| + f.printf "%s=%s\n", i.name, i.value if i.value? and i.value + end + } + end + + def load_standard_entries + standard_entries(@rbconfig).each do |ent| + add ent + end + end + + def standard_entries(rbconfig) + c = rbconfig + + rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) + + major = c['MAJOR'].to_i + minor = c['MINOR'].to_i + teeny = c['TEENY'].to_i + version = "#{major}.#{minor}" + + # ruby ver. >= 1.4.4? + newpath_p = ((major >= 2) or + ((major == 1) and + ((minor >= 5) or + ((minor == 4) and (teeny >= 4))))) + + if c['rubylibdir'] + # V > 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = c['rubylibdir'] + librubyverarch = c['archdir'] + siteruby = c['sitedir'] + siterubyver = c['sitelibdir'] + siterubyverarch = c['sitearchdir'] + elsif newpath_p + # 1.4.4 <= V <= 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = c['sitedir'] + siterubyver = "$siteruby/#{version}" + siterubyverarch = "$siterubyver/#{c['arch']}" + else + # V < 1.4.4 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" + siterubyver = siteruby + siterubyverarch = "$siterubyver/#{c['arch']}" + end + parameterize = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') + } + + if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] + else + makeprog = 'make' + end + + [ + ExecItem.new('installdirs', 'std/site/home', + 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ + {|val, table| + case val + when 'std' + table['rbdir'] = '$librubyver' + table['sodir'] = '$librubyverarch' + when 'site' + table['rbdir'] = '$siterubyver' + table['sodir'] = '$siterubyverarch' + when 'home' + setup_rb_error '$HOME was not set' unless ENV['HOME'] + table['prefix'] = ENV['HOME'] + table['rbdir'] = '$libdir/ruby' + table['sodir'] = '$libdir/ruby' + end + }, + PathItem.new('prefix', 'path', c['prefix'], + 'path prefix of target environment'), + PathItem.new('bindir', 'path', parameterize.call(c['bindir']), + 'the directory for commands'), + PathItem.new('libdir', 'path', parameterize.call(c['libdir']), + 'the directory for libraries'), + PathItem.new('datadir', 'path', parameterize.call(c['datadir']), + 'the directory for shared data'), + PathItem.new('mandir', 'path', parameterize.call(c['mandir']), + 'the directory for man pages'), + PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), + 'the directory for system configuration files'), + PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), + 'the directory for local state data'), + PathItem.new('libruby', 'path', libruby, + 'the directory for ruby libraries'), + PathItem.new('librubyver', 'path', librubyver, + 'the directory for standard ruby libraries'), + PathItem.new('librubyverarch', 'path', librubyverarch, + 'the directory for standard ruby extensions'), + PathItem.new('siteruby', 'path', siteruby, + 'the directory for version-independent aux ruby libraries'), + PathItem.new('siterubyver', 'path', siterubyver, + 'the directory for aux ruby libraries'), + PathItem.new('siterubyverarch', 'path', siterubyverarch, + 'the directory for aux ruby binaries'), + PathItem.new('rbdir', 'path', '$siterubyver', + 'the directory for ruby scripts'), + PathItem.new('sodir', 'path', '$siterubyverarch', + 'the directory for ruby extentions'), + PathItem.new('rubypath', 'path', rubypath, + 'the path to set to #! line'), + ProgramItem.new('rubyprog', 'name', rubypath, + 'the ruby program using for installation'), + ProgramItem.new('makeprog', 'name', makeprog, + 'the make program to compile ruby extentions'), + SelectItem.new('shebang', 'all/ruby/never', 'ruby', + 'shebang line (#!) editing mode'), + BoolItem.new('without-ext', 'yes/no', 'no', + 'does not compile/install ruby extentions') + ] + end + private :standard_entries + + def load_multipackage_entries + multipackage_entries().each do |ent| + add ent + end + end + + def multipackage_entries + [ + PackageSelectionItem.new('with', 'name,name...', '', 'ALL', + 'package names that you want to install'), + PackageSelectionItem.new('without', 'name,name...', '', 'NONE', + 'package names that you do not want to install') + ] + end + private :multipackage_entries + + ALIASES = { + 'std-ruby' => 'librubyver', + 'stdruby' => 'librubyver', + 'rubylibdir' => 'librubyver', + 'archdir' => 'librubyverarch', + 'site-ruby-common' => 'siteruby', # For backward compatibility + 'site-ruby' => 'siterubyver', # For backward compatibility + 'bin-dir' => 'bindir', + 'bin-dir' => 'bindir', + 'rb-dir' => 'rbdir', + 'so-dir' => 'sodir', + 'data-dir' => 'datadir', + 'ruby-path' => 'rubypath', + 'ruby-prog' => 'rubyprog', + 'ruby' => 'rubyprog', + 'make-prog' => 'makeprog', + 'make' => 'makeprog' + } + + def fixup + ALIASES.each do |ali, name| + @table[ali] = @table[name] + end + @items.freeze + @table.freeze + @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ + end + + def parse_opt(opt) + m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" + m.to_a[1,2] + end + + def dllext + @rbconfig['DLEXT'] + end + + def value_config?(name) + lookup(name).value? + end + + class Item + def initialize(name, template, default, desc) + @name = name.freeze + @template = template + @value = default + @default = default + @description = desc + end + + attr_reader :name + attr_reader :description + + attr_accessor :default + alias help_default default + + def help_opt + "--#{@name}=#{@template}" + end + + def value? + true + end + + def value + @value + end + + def resolve(table) + @value.gsub(%r<\$([^/]+)>) { table[$1] } + end + + def set(val) + @value = check(val) + end + + private + + def check(val) + setup_rb_error "config: --#{name} requires argument" unless val + val + end + end + + class BoolItem < Item + def config_type + 'bool' + end + + def help_opt + "--#{@name}" + end + + private + + def check(val) + return 'yes' unless val + case val + when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' + when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' + else + setup_rb_error "config: --#{@name} accepts only yes/no for argument" + end + end + end + + class PathItem < Item + def config_type + 'path' + end + + private + + def check(path) + setup_rb_error "config: --#{@name} requires argument" unless path + path[0,1] == '$' ? path : File.expand_path(path) + end + end + + class ProgramItem < Item + def config_type + 'program' + end + end + + class SelectItem < Item + def initialize(name, selection, default, desc) + super + @ok = selection.split('/') + end + + def config_type + 'select' + end + + private + + def check(val) + unless @ok.include?(val.strip) + setup_rb_error "config: use --#{@name}=#{@template} (#{val})" + end + val.strip + end + end + + class ExecItem < Item + def initialize(name, selection, desc, &block) + super name, selection, nil, desc + @ok = selection.split('/') + @action = block + end + + def config_type + 'exec' + end + + def value? + false + end + + def resolve(table) + setup_rb_error "$#{name()} wrongly used as option value" + end + + undef set + + def evaluate(val, table) + v = val.strip.downcase + unless @ok.include?(v) + setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" + end + @action.call v, table + end + end + + class PackageSelectionItem < Item + def initialize(name, template, default, help_default, desc) + super name, template, default, desc + @help_default = help_default + end + + attr_reader :help_default + + def config_type + 'package' + end + + private + + def check(val) + unless File.dir?("packages/#{val}") + setup_rb_error "config: no such package: #{val}" + end + val + end + end + + class MetaConfigEnvironment + def initialize(config, installer) + @config = config + @installer = installer + end + + def config_names + @config.names + end + + def config?(name) + @config.key?(name) + end + + def bool_config?(name) + @config.lookup(name).config_type == 'bool' + end + + def path_config?(name) + @config.lookup(name).config_type == 'path' + end + + def value_config?(name) + @config.lookup(name).config_type != 'exec' + end + + def add_config(item) + @config.add item + end + + def add_bool_config(name, default, desc) + @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) + end + + def add_path_config(name, default, desc) + @config.add PathItem.new(name, 'path', default, desc) + end + + def set_config_default(name, default) + @config.lookup(name).default = default + end + + def remove_config(name) + @config.remove(name) + end + + # For only multipackage + def packages + raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer + @installer.packages + end + + # For only multipackage + def declare_packages(list) + raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer + @installer.packages = list + end + end + +end # class ConfigTable + + +# This module requires: #verbose?, #no_harm? +module FileOperations + + def mkdir_p(dirname, prefix = nil) + dirname = prefix + File.expand_path(dirname) if prefix + $stderr.puts "mkdir -p #{dirname}" if verbose? + return if no_harm? + + # Does not check '/', it's too abnormal. + dirs = File.expand_path(dirname).split(%r<(?=/)>) + if /\A[a-z]:\z/i =~ dirs[0] + disk = dirs.shift + dirs[0] = disk + dirs[0] + end + dirs.each_index do |idx| + path = dirs[0..idx].join('') + Dir.mkdir path unless File.dir?(path) + end + end + + def rm_f(path) + $stderr.puts "rm -f #{path}" if verbose? + return if no_harm? + force_remove_file path + end + + def rm_rf(path) + $stderr.puts "rm -rf #{path}" if verbose? + return if no_harm? + remove_tree path + end + + def remove_tree(path) + if File.symlink?(path) + remove_file path + elsif File.dir?(path) + remove_tree0 path + else + force_remove_file path + end + end + + def remove_tree0(path) + Dir.foreach(path) do |ent| + next if ent == '.' + next if ent == '..' + entpath = "#{path}/#{ent}" + if File.symlink?(entpath) + remove_file entpath + elsif File.dir?(entpath) + remove_tree0 entpath + else + force_remove_file entpath + end + end + begin + Dir.rmdir path + rescue Errno::ENOTEMPTY + # directory may not be empty + end + end + + def move_file(src, dest) + force_remove_file dest + begin + File.rename src, dest + rescue + File.open(dest, 'wb') {|f| + f.write File.binread(src) + } + File.chmod File.stat(src).mode, dest + File.unlink src + end + end + + def force_remove_file(path) + begin + remove_file path + rescue + end + end + + def remove_file(path) + File.chmod 0777, path + File.unlink path + end + + def install(from, dest, mode, prefix = nil) + $stderr.puts "install #{from} #{dest}" if verbose? + return if no_harm? + + realdest = prefix ? prefix + File.expand_path(dest) : dest + realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) + str = File.binread(from) + if diff?(str, realdest) + verbose_off { + rm_f realdest if File.exist?(realdest) + } + File.open(realdest, 'wb') {|f| + f.write str + } + File.chmod mode, realdest + + File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| + if prefix + f.puts realdest.sub(prefix, '') + else + f.puts realdest + end + } + end + end + + def diff?(new_content, path) + return true unless File.exist?(path) + new_content != File.binread(path) + end + + def command(*args) + $stderr.puts args.join(' ') if verbose? + system(*args) or raise RuntimeError, + "system(#{args.map{|a| a.inspect }.join(' ')}) failed" + end + + def ruby(*args) + command config('rubyprog'), *args + end + + def make(task = nil) + command(*[config('makeprog'), task].compact) + end + + def extdir?(dir) + File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") + end + + def files_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.file?("#{dir}/#{ent}") } + } + end + + DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) + + def directories_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT + } + end + +end + + +# This module requires: #srcdir_root, #objdir_root, #relpath +module HookScriptAPI + + def get_config(key) + @config[key] + end + + alias config get_config + + # obsolete: use metaconfig to change configuration + def set_config(key, val) + @config[key] = val + end + + # + # srcdir/objdir (works only in the package directory) + # + + def curr_srcdir + "#{srcdir_root()}/#{relpath()}" + end + + def curr_objdir + "#{objdir_root()}/#{relpath()}" + end + + def srcfile(path) + "#{curr_srcdir()}/#{path}" + end + + def srcexist?(path) + File.exist?(srcfile(path)) + end + + def srcdirectory?(path) + File.dir?(srcfile(path)) + end + + def srcfile?(path) + File.file?(srcfile(path)) + end + + def srcentries(path = '.') + Dir.open("#{curr_srcdir()}/#{path}") {|d| + return d.to_a - %w(. ..) + } + end + + def srcfiles(path = '.') + srcentries(path).select {|fname| + File.file?(File.join(curr_srcdir(), path, fname)) + } + end + + def srcdirectories(path = '.') + srcentries(path).select {|fname| + File.dir?(File.join(curr_srcdir(), path, fname)) + } + end + +end + + +class ToplevelInstaller + + Version = '3.4.1' + Copyright = 'Copyright (c) 2000-2005 Minero Aoki' + + TASKS = [ + [ 'all', 'do config, setup, then install' ], + [ 'config', 'saves your configurations' ], + [ 'show', 'shows current configuration' ], + [ 'setup', 'compiles ruby extentions and others' ], + [ 'install', 'installs files' ], + [ 'test', 'run all tests in test/' ], + [ 'clean', "does `make clean' for each extention" ], + [ 'distclean',"does `make distclean' for each extention" ] + ] + + def ToplevelInstaller.invoke + config = ConfigTable.new(load_rbconfig()) + config.load_standard_entries + config.load_multipackage_entries if multipackage? + config.fixup + klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) + klass.new(File.dirname($0), config).invoke + end + + def ToplevelInstaller.multipackage? + File.dir?(File.dirname($0) + '/packages') + end + + def ToplevelInstaller.load_rbconfig + if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } + ARGV.delete(arg) + load File.expand_path(arg.split(/=/, 2)[1]) + $".push 'rbconfig.rb' + else + require 'rbconfig' + end + ::Config::CONFIG + end + + def initialize(ardir_root, config) + @ardir = File.expand_path(ardir_root) + @config = config + # cache + @valid_task_re = nil + end + + def config(key) + @config[key] + end + + def inspect + "#<#{self.class} #{__id__()}>" + end + + def invoke + run_metaconfigs + case task = parsearg_global() + when nil, 'all' + parsearg_config + init_installers + exec_config + exec_setup + exec_install + else + case task + when 'config', 'test' + ; + when 'clean', 'distclean' + @config.load_savefile if File.exist?(@config.savefile) + else + @config.load_savefile + end + __send__ "parsearg_#{task}" + init_installers + __send__ "exec_#{task}" + end + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig" + end + + def init_installers + @installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + # + # Hook Script API bases + # + + def srcdir_root + @ardir + end + + def objdir_root + '.' + end + + def relpath + '.' + end + + # + # Option Parsing + # + + def parsearg_global + while arg = ARGV.shift + case arg + when /\A\w+\z/ + setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) + return arg + when '-q', '--quiet' + @config.verbose = false + when '--verbose' + @config.verbose = true + when '--help' + print_usage $stdout + exit 0 + when '--version' + puts "#{File.basename($0)} version #{Version}" + exit 0 + when '--copyright' + puts Copyright + exit 0 + else + setup_rb_error "unknown global option '#{arg}'" + end + end + nil + end + + def valid_task?(t) + valid_task_re() =~ t + end + + def valid_task_re + @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ + end + + def parsearg_no_options + unless ARGV.empty? + task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) + setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" + end + end + + alias parsearg_show parsearg_no_options + alias parsearg_setup parsearg_no_options + alias parsearg_test parsearg_no_options + alias parsearg_clean parsearg_no_options + alias parsearg_distclean parsearg_no_options + + def parsearg_config + evalopt = [] + set = [] + @config.config_opt = [] + while i = ARGV.shift + if /\A--?\z/ =~ i + @config.config_opt = ARGV.dup + break + end + name, value = *@config.parse_opt(i) + if @config.value_config?(name) + @config[name] = value + else + evalopt.push [name, value] + end + set.push name + end + evalopt.each do |name, value| + @config.lookup(name).evaluate value, @config + end + # Check if configuration is valid + set.each do |n| + @config[n] if @config.value_config?(n) + end + end + + def parsearg_install + @config.no_harm = false + @config.install_prefix = '' + while a = ARGV.shift + case a + when '--no-harm' + @config.no_harm = true + when /\A--prefix=/ + path = a.split(/=/, 2)[1] + path = File.expand_path(path) unless path[0,1] == '/' + @config.install_prefix = path + else + setup_rb_error "install: unknown option #{a}" + end + end + end + + def print_usage(out) + out.puts 'Typical Installation Procedure:' + out.puts " $ ruby #{File.basename $0} config" + out.puts " $ ruby #{File.basename $0} setup" + out.puts " # ruby #{File.basename $0} install (may require root privilege)" + out.puts + out.puts 'Detailed Usage:' + out.puts " ruby #{File.basename $0} <global option>" + out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" + + fmt = " %-24s %s\n" + out.puts + out.puts 'Global options:' + out.printf fmt, '-q,--quiet', 'suppress message outputs' + out.printf fmt, ' --verbose', 'output messages verbosely' + out.printf fmt, ' --help', 'print this message' + out.printf fmt, ' --version', 'print version and quit' + out.printf fmt, ' --copyright', 'print copyright and quit' + out.puts + out.puts 'Tasks:' + TASKS.each do |name, desc| + out.printf fmt, name, desc + end + + fmt = " %-24s %s [%s]\n" + out.puts + out.puts 'Options for CONFIG or ALL:' + @config.each do |item| + out.printf fmt, item.help_opt, item.description, item.help_default + end + out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" + out.puts + out.puts 'Options for INSTALL:' + out.printf fmt, '--no-harm', 'only display what to do if given', 'off' + out.printf fmt, '--prefix=path', 'install path prefix', '' + out.puts + end + + # + # Task Handlers + # + + def exec_config + @installer.exec_config + @config.save # must be final + end + + def exec_setup + @installer.exec_setup + end + + def exec_install + @installer.exec_install + end + + def exec_test + @installer.exec_test + end + + def exec_show + @config.each do |i| + printf "%-20s %s\n", i.name, i.value if i.value? + end + end + + def exec_clean + @installer.exec_clean + end + + def exec_distclean + @installer.exec_distclean + end + +end # class ToplevelInstaller + + +class ToplevelInstallerMulti < ToplevelInstaller + + include FileOperations + + def initialize(ardir_root, config) + super + @packages = directories_of("#{@ardir}/packages") + raise 'no package exists' if @packages.empty? + @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig", self + @packages.each do |name| + @config.load_script "#{@ardir}/packages/#{name}/metaconfig" + end + end + + attr_reader :packages + + def packages=(list) + raise 'package list is empty' if list.empty? + list.each do |name| + raise "directory packages/#{name} does not exist"\ + unless File.dir?("#{@ardir}/packages/#{name}") + end + @packages = list + end + + def init_installers + @installers = {} + @packages.each do |pack| + @installers[pack] = Installer.new(@config, + "#{@ardir}/packages/#{pack}", + "packages/#{pack}") + end + with = extract_selection(config('with')) + without = extract_selection(config('without')) + @selected = @installers.keys.select {|name| + (with.empty? or with.include?(name)) \ + and not without.include?(name) + } + end + + def extract_selection(list) + a = list.split(/,/) + a.each do |name| + setup_rb_error "no such package: #{name}" unless @installers.key?(name) + end + a + end + + def print_usage(f) + super + f.puts 'Inluded packages:' + f.puts ' ' + @packages.sort.join(' ') + f.puts + end + + # + # Task Handlers + # + + def exec_config + run_hook 'pre-config' + each_selected_installers {|inst| inst.exec_config } + run_hook 'post-config' + @config.save # must be final + end + + def exec_setup + run_hook 'pre-setup' + each_selected_installers {|inst| inst.exec_setup } + run_hook 'post-setup' + end + + def exec_install + run_hook 'pre-install' + each_selected_installers {|inst| inst.exec_install } + run_hook 'post-install' + end + + def exec_test + run_hook 'pre-test' + each_selected_installers {|inst| inst.exec_test } + run_hook 'post-test' + end + + def exec_clean + rm_f @config.savefile + run_hook 'pre-clean' + each_selected_installers {|inst| inst.exec_clean } + run_hook 'post-clean' + end + + def exec_distclean + rm_f @config.savefile + run_hook 'pre-distclean' + each_selected_installers {|inst| inst.exec_distclean } + run_hook 'post-distclean' + end + + # + # lib + # + + def each_selected_installers + Dir.mkdir 'packages' unless File.dir?('packages') + @selected.each do |pack| + $stderr.puts "Processing the package `#{pack}' ..." if verbose? + Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") + Dir.chdir "packages/#{pack}" + yield @installers[pack] + Dir.chdir '../..' + end + end + + def run_hook(id) + @root_installer.run_hook id + end + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + +end # class ToplevelInstallerMulti + + +class Installer + + FILETYPES = %w( bin lib ext data conf man ) + + include FileOperations + include HookScriptAPI + + def initialize(config, srcroot, objroot) + @config = config + @srcdir = File.expand_path(srcroot) + @objdir = File.expand_path(objroot) + @currdir = '.' + end + + def inspect + "#<#{self.class} #{File.basename(@srcdir)}>" + end + + def noop(rel) + end + + # + # Hook Script API base methods + # + + def srcdir_root + @srcdir + end + + def objdir_root + @objdir + end + + def relpath + @currdir + end + + # + # Config Access + # + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + + def verbose_off + begin + save, @config.verbose = @config.verbose?, false + yield + ensure + @config.verbose = save + end + end + + # + # TASK config + # + + def exec_config + exec_task_traverse 'config' + end + + alias config_dir_bin noop + alias config_dir_lib noop + + def config_dir_ext(rel) + extconf if extdir?(curr_srcdir()) + end + + alias config_dir_data noop + alias config_dir_conf noop + alias config_dir_man noop + + def extconf + ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt + end + + # + # TASK setup + # + + def exec_setup + exec_task_traverse 'setup' + end + + def setup_dir_bin(rel) + files_of(curr_srcdir()).each do |fname| + update_shebang_line "#{curr_srcdir()}/#{fname}" + end + end + + alias setup_dir_lib noop + + def setup_dir_ext(rel) + make if extdir?(curr_srcdir()) + end + + alias setup_dir_data noop + alias setup_dir_conf noop + alias setup_dir_man noop + + def update_shebang_line(path) + return if no_harm? + return if config('shebang') == 'never' + old = Shebang.load(path) + if old + $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 + new = new_shebang(old) + return if new.to_s == old.to_s + else + return unless config('shebang') == 'all' + new = Shebang.new(config('rubypath')) + end + $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? + open_atomic_writer(path) {|output| + File.open(path, 'rb') {|f| + f.gets if old # discard + output.puts new.to_s + output.print f.read + } + } + end + + def new_shebang(old) + if /\Aruby/ =~ File.basename(old.cmd) + Shebang.new(config('rubypath'), old.args) + elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' + Shebang.new(config('rubypath'), old.args[1..-1]) + else + return old unless config('shebang') == 'all' + Shebang.new(config('rubypath')) + end + end + + def open_atomic_writer(path, &block) + tmpfile = File.basename(path) + '.tmp' + begin + File.open(tmpfile, 'wb', &block) + File.rename tmpfile, File.basename(path) + ensure + File.unlink tmpfile if File.exist?(tmpfile) + end + end + + class Shebang + def Shebang.load(path) + line = nil + File.open(path) {|f| + line = f.gets + } + return nil unless /\A#!/ =~ line + parse(line) + end + + def Shebang.parse(line) + cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') + new(cmd, args) + end + + def initialize(cmd, args = []) + @cmd = cmd + @args = args + end + + attr_reader :cmd + attr_reader :args + + def to_s + "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") + end + end + + # + # TASK install + # + + def exec_install + rm_f 'InstalledFiles' + exec_task_traverse 'install' + end + + def install_dir_bin(rel) + install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 + end + + def install_dir_lib(rel) + install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 + end + + def install_dir_ext(rel) + return unless extdir?(curr_srcdir()) + install_files rubyextentions('.'), + "#{config('sodir')}/#{File.dirname(rel)}", + 0555 + end + + def install_dir_data(rel) + install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 + end + + def install_dir_conf(rel) + # FIXME: should not remove current config files + # (rename previous file to .old/.org) + install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 + end + + def install_dir_man(rel) + install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 + end + + def install_files(list, dest, mode) + mkdir_p dest, @config.install_prefix + list.each do |fname| + install fname, dest, mode, @config.install_prefix + end + end + + def libfiles + glob_reject(%w(*.y *.output), targetfiles()) + end + + def rubyextentions(dir) + ents = glob_select("*.#{@config.dllext}", targetfiles()) + if ents.empty? + setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" + end + ents + end + + def targetfiles + mapdir(existfiles() - hookfiles()) + end + + def mapdir(ents) + ents.map {|ent| + if File.exist?(ent) + then ent # objdir + else "#{curr_srcdir()}/#{ent}" # srcdir + end + } + end + + # picked up many entries from cvs-1.11.1/src/ignore.c + JUNK_FILES = %w( + core RCSLOG tags TAGS .make.state + .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb + *~ *.old *.bak *.BAK *.orig *.rej _$* *$ + + *.org *.in .* + ) + + def existfiles + glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) + end + + def hookfiles + %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| + %w( config setup install clean ).map {|t| sprintf(fmt, t) } + }.flatten + end + + def glob_select(pat, ents) + re = globs2re([pat]) + ents.select {|ent| re =~ ent } + end + + def glob_reject(pats, ents) + re = globs2re(pats) + ents.reject {|ent| re =~ ent } + end + + GLOB2REGEX = { + '.' => '\.', + '$' => '\$', + '#' => '\#', + '*' => '.*' + } + + def globs2re(pats) + /\A(?:#{ + pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') + })\z/ + end + + # + # TASK test + # + + TESTDIR = 'test' + + def exec_test + unless File.directory?('test') + $stderr.puts 'no test in this package' if verbose? + return + end + $stderr.puts 'Running tests...' if verbose? + begin + require 'test/unit' + rescue LoadError + setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' + end + runner = Test::Unit::AutoRunner.new(true) + runner.to_run << TESTDIR + runner.run + end + + # + # TASK clean + # + + def exec_clean + exec_task_traverse 'clean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias clean_dir_bin noop + alias clean_dir_lib noop + alias clean_dir_data noop + alias clean_dir_conf noop + alias clean_dir_man noop + + def clean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'clean' if File.file?('Makefile') + end + + # + # TASK distclean + # + + def exec_distclean + exec_task_traverse 'distclean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias distclean_dir_bin noop + alias distclean_dir_lib noop + + def distclean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'distclean' if File.file?('Makefile') + end + + alias distclean_dir_data noop + alias distclean_dir_conf noop + alias distclean_dir_man noop + + # + # Traversing + # + + def exec_task_traverse(task) + run_hook "pre-#{task}" + FILETYPES.each do |type| + if type == 'ext' and config('without-ext') == 'yes' + $stderr.puts 'skipping ext/* by user option' if verbose? + next + end + traverse task, type, "#{task}_dir_#{type}" + end + run_hook "post-#{task}" + end + + def traverse(task, rel, mid) + dive_into(rel) { + run_hook "pre-#{task}" + __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') + directories_of(curr_srcdir()).each do |d| + traverse task, "#{rel}/#{d}", mid + end + run_hook "post-#{task}" + } + end + + def dive_into(rel) + return unless File.dir?("#{@srcdir}/#{rel}") + + dir = File.basename(rel) + Dir.mkdir dir unless File.dir?(dir) + prevdir = Dir.pwd + Dir.chdir dir + $stderr.puts '---> ' + rel if verbose? + @currdir = rel + yield + Dir.chdir prevdir + $stderr.puts '<--- ' + rel if verbose? + @currdir = File.dirname(rel) + end + + def run_hook(id) + path = [ "#{curr_srcdir()}/#{id}", + "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } + return unless path + begin + instance_eval File.read(path), path, 1 + rescue + raise if $DEBUG + setup_rb_error "hook #{path} failed:\n" + $!.message + end + end + +end # class Installer + + +class SetupError < StandardError; end + +def setup_rb_error(msg) + raise SetupError, msg +end + +if $0 == __FILE__ + begin + ToplevelInstaller.invoke + rescue SetupError + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end diff --git a/tasks/deployment.rake b/tasks/deployment.rake new file mode 100644 index 0000000..2f43742 --- /dev/null +++ b/tasks/deployment.rake @@ -0,0 +1,34 @@ +desc 'Release the website and new gem version' +task :deploy => [:check_version, :website, :release] do + puts "Remember to create SVN tag:" + puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " + puts "Suggested comment:" + puts "Tagging release #{CHANGES}" +end + +desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' +task :local_deploy => [:website_generate, :install_gem] + +task :check_version do + unless ENV['VERSION'] + puts 'Must pass a VERSION=x.y.z release version' + exit + end + unless ENV['VERSION'] == VERS + puts "Please update your version.rb to match the release version, currently #{VERS}" + exit + end +end + +desc 'Install the package as a gem, without generating documentation(ri/rdoc)' +task :install_gem_no_doc => [:clean, :package] do + sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" +end + +namespace :manifest do + desc 'Recreate Manifest.txt to include ALL files' + task :refresh do + `rake check_manifest | patch -p0 > Manifest.txt` + end +end \ No newline at end of file diff --git a/tasks/environment.rake b/tasks/environment.rake new file mode 100644 index 0000000..691ed3b --- /dev/null +++ b/tasks/environment.rake @@ -0,0 +1,7 @@ +task :ruby_env do + RUBY_APP = if RUBY_PLATFORM =~ /java/ + "jruby" + else + "ruby" + end unless defined? RUBY_APP +end diff --git a/tasks/website.rake b/tasks/website.rake new file mode 100644 index 0000000..93e03fa --- /dev/null +++ b/tasks/website.rake @@ -0,0 +1,17 @@ +desc 'Generate website files' +task :website_generate => :ruby_env do + (Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt| + sh %{ #{RUBY_APP} script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} } + end +end + +desc 'Upload website files to rubyforge' +task :website_upload do + host = "#{rubyforge_username}@rubyforge.org" + remote_dir = "/var/www/gforge-projects/#{PATH}/" + local_dir = 'website' + sh %{rsync -aCv #{local_dir}/ #{host}:#{remote_dir}} +end + +desc 'Generate and upload website files' +task :website => [:website_generate, :website_upload, :publish_docs] diff --git a/test/test_base62.rb b/test/test_base62.rb new file mode 100644 index 0000000..95b2b2e --- /dev/null +++ b/test/test_base62.rb @@ -0,0 +1,11 @@ +require File.dirname(__FILE__) + '/test_helper.rb' + +class TestBase62 < Test::Unit::TestCase + + def test_1_to_10000000 + (0..10000000).each do |i| + assert_equal(i.to_s, i.base62_encode.base62_decode.to_s, i.to_s + "\t" + i.base62_encode.to_s + "\t" + i.base62_encode.base62_decode.to_s) + end + end + +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..efbfda5 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,2 @@ +require 'test/unit' +require File.dirname(__FILE__) + '/../lib/base62' diff --git a/website/index.html b/website/index.html new file mode 100644 index 0000000..9246dcf --- /dev/null +++ b/website/index.html @@ -0,0 +1,10 @@ +<html> + <head> + <meta http-equiv="Content-type" content="text/html; charset=utf-8"> + <title>base62 ruby gem</title> + + </head> + <body id="body"> + <p>This gem monkeypatches Integer and String to encode integers into a base62 0-9 + A-Z + a-z string format and decode strings in this format back into integers.</p> + </body> +</html> \ No newline at end of file diff --git a/website/index.txt b/website/index.txt new file mode 100644 index 0000000..10ca4d8 --- /dev/null +++ b/website/index.txt @@ -0,0 +1,75 @@ +h1. base62 + +h1. &#x2192; 'base62' + + +h2. What + + +h2. Installing + +<pre syntax="ruby">sudo gem install base62</pre> + +h2. The basics + + +h2. Developer's Site + +"http://geekjacking.com/base62_gem":http://geekjacking.com/base62_gem + +h2. How to submit patches + +Read the "8 steps for fixing other people's code":http://drnicwilliams.com/2007/06/01/8-steps-for-fixing-other-peoples-code/ + +The trunk repository is <code>svn://rubyforge.org/var/svn/base62/trunk</code> for anonymous access. + +OOOORRRR + +You can fetch the source from either: + +<% if rubyforge_project_id %> + +* rubyforge: "http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %>":http://rubyforge.org/scm/?group_id=<%= rubyforge_project_id %> + +<pre>git clone git://rubyforge.org/base62.git</pre> + +<% else %> + +* rubyforge: MISSING IN ACTION + +TODO - You can not created a RubyForge project, OR have not run <code>rubyforge config</code> +yet to refresh your local rubyforge data with this projects' id information. + +When you do this, this message will magically disappear! + +Or you can hack website/index.txt and make it all go away!! + +<% end %> + +* github: "http://github.com/GITHUB_USERNAME/base62/tree/master":http://github.com/GITHUB_USERNAME/base62/tree/master + +<pre>git clone git://github.com/GITHUB_USERNAME/base62.git</pre> + + +TODO - add "github_username: username" to ~/.rubyforge/user-config.yml and newgem will reuse it for future projects. + + +* gitorious: "git://gitorious.org/base62/mainline.git":git://gitorious.org/base62/mainline.git + +<pre>git clone git://gitorious.org/base62/mainline.git</pre> + +h3. Build and test instructions + +<pre>cd base62 +rake test +rake install_gem</pre> + + +h2. License + +This code is free to use under the terms of the MIT license. + +h2. Contact + +Comments are welcome. Send an email to "FIXME full name":mailto:FIXME email via the "forum":http://groups.google.com/group/base62 + diff --git a/website/javascripts/rounded_corners_lite.inc.js b/website/javascripts/rounded_corners_lite.inc.js new file mode 100644 index 0000000..afc3ea3 --- /dev/null +++ b/website/javascripts/rounded_corners_lite.inc.js @@ -0,0 +1,285 @@ + + /**************************************************************** + * * + * curvyCorners * + * ------------ * + * * + * This script generates rounded corners for your divs. * + * * + * Version 1.2.9 * + * Copyright (c) 2006 Cameron Cooke * + * By: Cameron Cooke and Tim Hutchison. * + * * + * * + * Website: http://www.curvycorners.net * + * Email: info@totalinfinity.com * + * Forum: http://www.curvycorners.net/forum/ * + * * + * * + * This library is free software; you can redistribute * + * it and/or modify it under the terms of the GNU * + * Lesser General Public License as published by the * + * Free Software Foundation; either version 2.1 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 Lesser General Public * + * License for more details. * + * * + * You should have received a copy of the GNU Lesser * + * General Public License along with this library; * + * Inc., 59 Temple Place, Suite 330, Boston, * + * MA 02111-1307 USA * + * * + ****************************************************************/ + +var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1; var isMoz = document.implementation && document.implementation.createDocument; var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false; function curvyCorners() +{ if(typeof(arguments[0]) != "object") throw newCurvyError("First parameter of curvyCorners() must be an object."); if(typeof(arguments[1]) != "object" && typeof(arguments[1]) != "string") throw newCurvyError("Second parameter of curvyCorners() must be an object or a class name."); if(typeof(arguments[1]) == "string") +{ var startIndex = 0; var boxCol = getElementsByClass(arguments[1]);} +else +{ var startIndex = 1; var boxCol = arguments;} +var curvyCornersCol = new Array(); if(arguments[0].validTags) +var validElements = arguments[0].validTags; else +var validElements = ["div"]; for(var i = startIndex, j = boxCol.length; i < j; i++) +{ var currentTag = boxCol[i].tagName.toLowerCase(); if(inArray(validElements, currentTag) !== false) +{ curvyCornersCol[curvyCornersCol.length] = new curvyObject(arguments[0], boxCol[i]);} +} +this.objects = curvyCornersCol; this.applyCornersToAll = function() +{ for(var x = 0, k = this.objects.length; x < k; x++) +{ this.objects[x].applyCorners();} +} +} +function curvyObject() +{ this.box = arguments[1]; this.settings = arguments[0]; this.topContainer = null; this.bottomContainer = null; this.masterCorners = new Array(); this.contentDIV = null; var boxHeight = get_style(this.box, "height", "height"); var boxWidth = get_style(this.box, "width", "width"); var borderWidth = get_style(this.box, "borderTopWidth", "border-top-width"); var borderColour = get_style(this.box, "borderTopColor", "border-top-color"); var boxColour = get_style(this.box, "backgroundColor", "background-color"); var backgroundImage = get_style(this.box, "backgroundImage", "background-image"); var boxPosition = get_style(this.box, "position", "position"); var boxPadding = get_style(this.box, "paddingTop", "padding-top"); this.boxHeight = parseInt(((boxHeight != "" && boxHeight != "auto" && boxHeight.indexOf("%") == -1)? boxHeight.substring(0, boxHeight.indexOf("px")) : this.box.scrollHeight)); this.boxWidth = parseInt(((boxWidth != "" && boxWidth != "auto" && boxWidth.indexOf("%") == -1)? boxWidth.substring(0, boxWidth.indexOf("px")) : this.box.scrollWidth)); this.borderWidth = parseInt(((borderWidth != "" && borderWidth.indexOf("px") !== -1)? borderWidth.slice(0, borderWidth.indexOf("px")) : 0)); this.boxColour = format_colour(boxColour); this.boxPadding = parseInt(((boxPadding != "" && boxPadding.indexOf("px") !== -1)? boxPadding.slice(0, boxPadding.indexOf("px")) : 0)); this.borderColour = format_colour(borderColour); this.borderString = this.borderWidth + "px" + " solid " + this.borderColour; this.backgroundImage = ((backgroundImage != "none")? backgroundImage : ""); this.boxContent = this.box.innerHTML; if(boxPosition != "absolute") this.box.style.position = "relative"; this.box.style.padding = "0px"; if(isIE && boxWidth == "auto" && boxHeight == "auto") this.box.style.width = "100%"; if(this.settings.autoPad == true && this.boxPadding > 0) +this.box.innerHTML = ""; this.applyCorners = function() +{ for(var t = 0; t < 2; t++) +{ switch(t) +{ case 0: +if(this.settings.tl || this.settings.tr) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0); newMainContainer.style.height = topMaxRadius + "px"; newMainContainer.style.top = 0 - topMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.topContainer = this.box.appendChild(newMainContainer);} +break; case 1: +if(this.settings.bl || this.settings.br) +{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0); newMainContainer.style.height = botMaxRadius + "px"; newMainContainer.style.bottom = 0 - botMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.bottomContainer = this.box.appendChild(newMainContainer);} +break;} +} +if(this.topContainer) this.box.style.borderTopWidth = "0px"; if(this.bottomContainer) this.box.style.borderBottomWidth = "0px"; var corners = ["tr", "tl", "br", "bl"]; for(var i in corners) +{ if(i > -1 < 4) +{ var cc = corners[i]; if(!this.settings[cc]) +{ if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null)) +{ var newCorner = document.createElement("DIV"); newCorner.style.position = "relative"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; if(this.backgroundImage == "") +newCorner.style.backgroundColor = this.boxColour; else +newCorner.style.backgroundImage = this.backgroundImage; switch(cc) +{ case "tl": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.tr.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.left = -this.borderWidth + "px"; break; case "tr": +newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.tl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; newCorner.style.left = this.borderWidth + "px"; break; case "bl": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.br.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = -this.borderWidth + "px"; newCorner.style.backgroundPosition = "-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break; case "br": +newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.bl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = this.borderWidth + "px" +newCorner.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break;} +} +} +else +{ if(this.masterCorners[this.settings[cc].radius]) +{ var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);} +else +{ var newCorner = document.createElement("DIV"); newCorner.style.height = this.settings[cc].radius + "px"; newCorner.style.width = this.settings[cc].radius + "px"; newCorner.style.position = "absolute"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth); for(var intx = 0, j = this.settings[cc].radius; intx < j; intx++) +{ if((intx +1) >= borderRadius) +var y1 = -1; else +var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1); if(borderRadius != j) +{ if((intx) >= borderRadius) +var y2 = -1; else +var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2))); if((intx+1) >= j) +var y3 = -1; else +var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);} +if((intx) >= j) +var y4 = -1; else +var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2))); if(y1 > -1) this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius); if(borderRadius != j) +{ for(var inty = (y1 + 1); inty < y2; inty++) +{ if(this.settings.antiAlias) +{ if(this.backgroundImage != "") +{ var borderFract = (pixelFraction(intx, inty, borderRadius) * 100); if(borderFract < 30) +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);} +else +{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);} +} +else +{ var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius)); this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);} +} +} +if(this.settings.antiAlias) +{ if(y3 >= y2) +{ if (y2 == -1) y2 = 0; this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);} +} +else +{ if(y3 >= y1) +{ this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);} +} +var outsideColour = this.borderColour;} +else +{ var outsideColour = this.boxColour; var y3 = y1;} +if(this.settings.antiAlias) +{ for(var inty = (y3 + 1); inty < y4; inty++) +{ this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);} +} +} +this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);} +if(cc != "br") +{ for(var t = 0, k = newCorner.childNodes.length; t < k; t++) +{ var pixelBar = newCorner.childNodes[t]; var pixelBarTop = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px"))); var pixelBarLeft = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px"))); var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px"))); if(cc == "tl" || cc == "bl"){ pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px";} +if(cc == "tr" || cc == "tl"){ pixelBar.style.top = this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px";} +switch(cc) +{ case "tr": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "tl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "bl": +pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px"; break;} +} +} +} +if(newCorner) +{ switch(cc) +{ case "tl": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "tr": +if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "bl": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break; case "br": +if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break;} +} +} +} +var radiusDiff = new Array(); radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius) +radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius); for(z in radiusDiff) +{ if(z == "t" || z == "b") +{ if(radiusDiff[z]) +{ var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius)? z +"l" : z +"r"); var newFiller = document.createElement("DIV"); newFiller.style.height = radiusDiff[z] + "px"; newFiller.style.width = this.settings[smallerCornerType].radius+ "px" +newFiller.style.position = "absolute"; newFiller.style.fontSize = "1px"; newFiller.style.overflow = "hidden"; newFiller.style.backgroundColor = this.boxColour; switch(smallerCornerType) +{ case "tl": +newFiller.style.bottom = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.topContainer.appendChild(newFiller); break; case "tr": +newFiller.style.bottom = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.topContainer.appendChild(newFiller); break; case "bl": +newFiller.style.top = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.bottomContainer.appendChild(newFiller); break; case "br": +newFiller.style.top = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.bottomContainer.appendChild(newFiller); break;} +} +var newFillerBar = document.createElement("DIV"); newFillerBar.style.position = "relative"; newFillerBar.style.fontSize = "1px"; newFillerBar.style.overflow = "hidden"; newFillerBar.style.backgroundColor = this.boxColour; newFillerBar.style.backgroundImage = this.backgroundImage; switch(z) +{ case "t": +if(this.topContainer) +{ if(this.settings.tl.radius && this.settings.tr.radius) +{ newFillerBar.style.height = topMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.tl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.tr.radius - this.borderWidth + "px"; newFillerBar.style.borderTop = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; this.topContainer.appendChild(newFillerBar);} +this.box.style.backgroundPosition = "0px -" + (topMaxRadius - this.borderWidth) + "px";} +break; case "b": +if(this.bottomContainer) +{ if(this.settings.bl.radius && this.settings.br.radius) +{ newFillerBar.style.height = botMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.bl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.br.radius - this.borderWidth + "px"; newFillerBar.style.borderBottom = this.borderString; if(this.backgroundImage != "") +newFillerBar.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (topMaxRadius + this.borderWidth)) + "px"; this.bottomContainer.appendChild(newFillerBar);} +} +break;} +} +} +if(this.settings.autoPad == true && this.boxPadding > 0) +{ var contentContainer = document.createElement("DIV"); contentContainer.style.position = "relative"; contentContainer.innerHTML = this.boxContent; contentContainer.className = "autoPadDiv"; var topPadding = Math.abs(topMaxRadius - this.boxPadding); var botPadding = Math.abs(botMaxRadius - this.boxPadding); if(topMaxRadius < this.boxPadding) +contentContainer.style.paddingTop = topPadding + "px"; if(botMaxRadius < this.boxPadding) +contentContainer.style.paddingBottom = botMaxRadius + "px"; contentContainer.style.paddingLeft = this.boxPadding + "px"; contentContainer.style.paddingRight = this.boxPadding + "px"; this.contentDIV = this.box.appendChild(contentContainer);} +} +this.drawPixel = function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius) +{ var pixel = document.createElement("DIV"); pixel.style.height = height + "px"; pixel.style.width = "1px"; pixel.style.position = "absolute"; pixel.style.fontSize = "1px"; pixel.style.overflow = "hidden"; var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius); if(image == -1 && this.backgroundImage != "") +{ pixel.style.backgroundImage = this.backgroundImage; pixel.style.backgroundPosition = "-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px";} +else +{ pixel.style.backgroundColor = colour;} +if (transAmount != 100) +setOpacity(pixel, transAmount); pixel.style.top = inty + "px"; pixel.style.left = intx + "px"; newCorner.appendChild(pixel);} +} +function insertAfter(parent, node, referenceNode) +{ parent.insertBefore(node, referenceNode.nextSibling);} +function BlendColour(Col1, Col2, Col1Fraction) +{ var red1 = parseInt(Col1.substr(1,2),16); var green1 = parseInt(Col1.substr(3,2),16); var blue1 = parseInt(Col1.substr(5,2),16); var red2 = parseInt(Col2.substr(1,2),16); var green2 = parseInt(Col2.substr(3,2),16); var blue2 = parseInt(Col2.substr(5,2),16); if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1; var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction))); if(endRed > 255) endRed = 255; if(endRed < 0) endRed = 0; var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction))); if(endGreen > 255) endGreen = 255; if(endGreen < 0) endGreen = 0; var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction))); if(endBlue > 255) endBlue = 255; if(endBlue < 0) endBlue = 0; return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);} +function IntToHex(strNum) +{ base = strNum / 16; rem = strNum % 16; base = base - (rem / 16); baseS = MakeHex(base); remS = MakeHex(rem); return baseS + '' + remS;} +function MakeHex(x) +{ if((x >= 0) && (x <= 9)) +{ return x;} +else +{ switch(x) +{ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F";} +} +} +function pixelFraction(x, y, r) +{ var pixelfraction = 0; var xvalues = new Array(1); var yvalues = new Array(1); var point = 0; var whatsides = ""; var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = "Left"; xvalues[point] = 0; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Top"; xvalues[point] = intersect - x; yvalues[point] = 1; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2))); if ((intersect >= y) && (intersect < (y+1))) +{ whatsides = whatsides + "Right"; xvalues[point] = 1; yvalues[point] = intersect - y; point = point + 1;} +var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2))); if ((intersect >= x) && (intersect < (x+1))) +{ whatsides = whatsides + "Bottom"; xvalues[point] = intersect - x; yvalues[point] = 0;} +switch (whatsides) +{ case "LeftRight": +pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2); break; case "TopRight": +pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2); break; case "TopBottom": +pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2); break; case "LeftBottom": +pixelfraction = (yvalues[0]*xvalues[1])/2; break; default: +pixelfraction = 1;} +return pixelfraction;} +function rgb2Hex(rgbColour) +{ try{ var rgbArray = rgb2Array(rgbColour); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);} +catch(e){ alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");} +return hexColour;} +function rgb2Array(rgbColour) +{ var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")")); var rgbArray = rgbValues.split(", "); return rgbArray;} +function setOpacity(obj, opacity) +{ opacity = (opacity == 100)?99.999:opacity; if(isSafari && obj.tagName != "IFRAME") +{ var rgbArray = rgb2Array(obj.style.backgroundColor); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";} +else if(typeof(obj.style.opacity) != "undefined") +{ obj.style.opacity = opacity/100;} +else if(typeof(obj.style.MozOpacity) != "undefined") +{ obj.style.MozOpacity = opacity/100;} +else if(typeof(obj.style.filter) != "undefined") +{ obj.style.filter = "alpha(opacity:" + opacity + ")";} +else if(typeof(obj.style.KHTMLOpacity) != "undefined") +{ obj.style.KHTMLOpacity = opacity/100;} +} +function inArray(array, value) +{ for(var i = 0; i < array.length; i++){ if (array[i] === value) return i;} +return false;} +function inArrayKey(array, value) +{ for(key in array){ if(key === value) return true;} +return false;} +function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true;} +else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r;} +else { elm['on' + evType] = fn;} +} +function removeEvent(obj, evType, fn, useCapture){ if (obj.removeEventListener){ obj.removeEventListener(evType, fn, useCapture); return true;} else if (obj.detachEvent){ var r = obj.detachEvent("on"+evType, fn); return r;} else { alert("Handler could not be removed");} +} +function format_colour(colour) +{ var returnColour = "#ffffff"; if(colour != "" && colour != "transparent") +{ if(colour.substr(0, 3) == "rgb") +{ returnColour = rgb2Hex(colour);} +else if(colour.length == 4) +{ returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);} +else +{ returnColour = colour;} +} +return returnColour;} +function get_style(obj, property, propertyNS) +{ try +{ if(obj.currentStyle) +{ var returnVal = eval("obj.currentStyle." + property);} +else +{ if(isSafari && obj.style.display == "none") +{ obj.style.display = ""; var wasHidden = true;} +var returnVal = document.defaultView.getComputedStyle(obj, '').getPropertyValue(propertyNS); if(isSafari && wasHidden) +{ obj.style.display = "none";} +} +} +catch(e) +{ } +return returnVal;} +function getElementsByClass(searchClass, node, tag) +{ var classElements = new Array(); if(node == null) +node = document; if(tag == null) +tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)"); for (i = 0, j = 0; i < elsLen; i++) +{ if(pattern.test(els[i].className)) +{ classElements[j] = els[i]; j++;} +} +return classElements;} +function newCurvyError(errorMessage) +{ return new Error("curvyCorners Error:\n" + errorMessage) +} diff --git a/website/stylesheets/screen.css b/website/stylesheets/screen.css new file mode 100644 index 0000000..2c84cd0 --- /dev/null +++ b/website/stylesheets/screen.css @@ -0,0 +1,138 @@ +body { + background-color: #E1D1F1; + font-family: "Georgia", sans-serif; + font-size: 16px; + line-height: 1.6em; + padding: 1.6em 0 0 0; + color: #333; +} +h1, h2, h3, h4, h5, h6 { + color: #444; +} +h1 { + font-family: sans-serif; + font-weight: normal; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin: 5px; +} +li { + padding: 0; + margin: 0; + list-style-type: square; +} +a { + color: #5E5AFF; + background-color: #DAC; + font-weight: normal; + text-decoration: underline; +} +blockquote { + font-size: 90%; + font-style: italic; + border-left: 1px solid #111; + padding-left: 1em; +} +.caps { + font-size: 80%; +} + +#main { + width: 45em; + padding: 0; + margin: 0 auto; +} +.coda { + text-align: right; + color: #77f; + font-size: smaller; +} + +table { + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; + border-style: dashed; +} + +th { + color: #fff; +} + +td { + padding: 2px 10px 2px 10px; +} + +.success { + color: #0CC52B; +} + +.failed { + color: #E90A1B; +} + +.unknown { + color: #995000; +} +pre, code { + font-family: monospace; + font-size: 90%; + line-height: 1.4em; + color: #ff8; + background-color: #111; + padding: 2px 10px 2px 10px; +} +.comment { color: #aaa; font-style: italic; } +.keyword { color: #eff; font-weight: bold; } +.punct { color: #eee; font-weight: bold; } +.symbol { color: #0bb; } +.string { color: #6b4; } +.ident { color: #ff8; } +.constant { color: #66f; } +.regex { color: #ec6; } +.number { color: #F99; } +.expr { color: #227; } + +#version { + float: right; + text-align: right; + font-family: sans-serif; + font-weight: normal; + background-color: #B3ABFF; + color: #141331; + padding: 15px 20px 10px 20px; + margin: 0 auto; + margin-top: 15px; + border: 3px solid #141331; +} + +#version .numbers { + display: block; + font-size: 4em; + line-height: 0.8em; + letter-spacing: -0.1ex; + margin-bottom: 15px; +} + +#version p { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; + margin: 0; + padding: 0; +} + +#version a { + text-decoration: none; + color: #141331; + background-color: #B3ABFF; +} + +.clickable { + cursor: pointer; + cursor: hand; +} + diff --git a/website/template.html.erb b/website/template.html.erb new file mode 100644 index 0000000..e851735 --- /dev/null +++ b/website/template.html.erb @@ -0,0 +1,48 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <link rel="stylesheet" href="stylesheets/screen.css" type="text/css" media="screen" /> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title> + <%= title %> + </title> + <script src="javascripts/rounded_corners_lite.inc.js" type="text/javascript"></script> +<style> + +</style> + <script type="text/javascript"> + window.onload = function() { + settings = { + tl: { radius: 10 }, + tr: { radius: 10 }, + bl: { radius: 10 }, + br: { radius: 10 }, + antiAlias: true, + autoPad: true, + validTags: ["div"] + } + var versionBox = new curvyCorners(settings, document.getElementById("version")); + versionBox.applyCornersToAll(); + } + </script> +</head> +<body> +<div id="main"> + + <h1><%= title %></h1> + <div id="version" class="clickable" onclick='document.location = "<%= download %>"; return false'> + <p>Get Version</p> + <a href="<%= download %>" class="numbers"><%= version %></a> + </div> + <%= body %> + <p class="coda"> + <a href="FIXME email">FIXME full name</a>, <%= modified.pretty %><br> + Theme extended from <a href="http://rb2js.rubyforge.org/">Paul Battley</a> + </p> +</div> + +<!-- insert site tracking codes here, like Google Urchin --> + +</body> +</html>
jhasse/jntetri
1344eb507f5f6d3abdf22cbee4c6463113f3bf83
Make Input scale-independent
diff --git a/src/gui/input.cpp b/src/gui/input.cpp index 237394a..1808a31 100644 --- a/src/gui/input.cpp +++ b/src/gui/input.cpp @@ -1,89 +1,87 @@ #include "input.hpp" #include <jngl.hpp> Input::Input(const jngl::Vec2 position) : displayCursor(0) { setPos(position); } void Input::setMaxWidth(unsigned int width) { maxWidth = width; } void Input::setPassword(bool password) { this->password = password; } void Input::onFocusChanged() { displayCursor = 50; } void Input::step() { const auto mousePos = jngl::getMousePos(); - if (mousePos.x > position.x && mousePos.y > position.y && mousePos.x < position.x + maxWidth && - mousePos.y < position.y + 94 /* TODO: Do not hardcode */) { + if (mousePos.x > getX() && mousePos.y > getY() && mousePos.x < getX() + maxWidth && + mousePos.y < getY() + 94 /* TODO: Do not hardcode */) { jngl::setCursor(jngl::Cursor::I); if (jngl::mousePressed()) { setFocus(true); } } if (!sensitive || !focus) { return; } --displayCursor; if (displayCursor < -35 || !jngl::getTextInput().empty()) { displayCursor = 35; } text += jngl::getTextInput(); if (jngl::keyPressed(jngl::key::BackSpace) && !text.empty()) { removeLastCharacter(); } while (jngl::getTextWidth(text) > maxWidth) { removeLastCharacter(); } } void Input::draw() const { std::string temp; if (password) { temp = text; size_t size = jngl::utf8Length(text); text.clear(); for (size_t i = 0; i < size; ++i) { text += "●"; } } if (sensitive) { jngl::setFontColor(0, 0, 0); } else { jngl::setFontColor(150, 150, 150); } if (focus && displayCursor > 0) { - jngl::print(text + "|", static_cast<int>(std::lround(position.x)), - static_cast<int>(std::lround(position.y))); + jngl::print(text + "|", getPos()); } else { - jngl::print(text, static_cast<int>(std::lround(position.x)), - static_cast<int>(std::lround(position.y))); + jngl::print(text, getPos()); } if (password) { text = temp; } } std::string Input::getText() const { return text; } void Input::setText(const std::string& text) { this->text = text; } void Input::removeLastCharacter() { displayCursor = 50; auto it = text.end(); --it; while (*it & 0x80 && !(*it & 0x40)) { // Unicode character? --it; } text.erase(it, text.end()); } diff --git a/src/main.cpp b/src/main.cpp index 9cc2d01..0c3ea0a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,21 +1,20 @@ #include "Intro.hpp" #include "engine/debugoverlay.hpp" #include "constants.hpp" #include <jngl.hpp> #include <jngl/init.hpp> jngl::AppParameters jnglInit() { jngl::AppParameters params; params.displayName = programDisplayName; params.screenSize = { 1280, 720 }; params.start = []() { jngl::setAntiAliasing(true); jngl::setIcon("icon"); jngl::setFont("Inter-ExtraLight.ttf"); - jngl::setFontSize(jngl::getScaleFactor() * 13); jngl::addJob(std::make_shared<DebugOverlay>()); return std::make_shared<Intro>(); }; return params; } diff --git a/subprojects/jngl b/subprojects/jngl index 0040037..1c88d68 160000 --- a/subprojects/jngl +++ b/subprojects/jngl @@ -1 +1 @@ -Subproject commit 004003756c03f0124ac1daf9b921ffc20e661e72 +Subproject commit 1c88d68729b175bd3024314abc1b2c810499e64e
jhasse/jntetri
31c1857f698c2b849051d4418406f8aa43d279cb
Accept Vec2 in Input ctor
diff --git a/src/gameoverscreen.cpp b/src/gameoverscreen.cpp index 1d22183..7ff847e 100644 --- a/src/gameoverscreen.cpp +++ b/src/gameoverscreen.cpp @@ -1,82 +1,83 @@ #include "gameoverscreen.hpp" #include "Game.hpp" #include "engine/Options.hpp" #include "engine/fade.hpp" #include "engine/screen.hpp" #include "menu.hpp" #include <jngl.hpp> -GameOverScreen::GameOverScreen(Game* game) : game_(game), blink_(0), highscore_(game_->getType()), -input_(new Input(-160, 200)), work_(jngl::getWork()) { +GameOverScreen::GameOverScreen(Game* game) +: game_(game), blink_(0), highscore_(game_->getType()), input_(new Input({ -160, 200 })), + work_(jngl::getWork()) { data_.score = game_->GetField().GetScore(); data_.time = game_->GetTime(); input_->setText(getOptions().lastHighscoreName); input_->setMaxWidth(400); addWidget(input_); } bool GameOverScreen::isHighscore() const { return !game_->isReplay() && highscore_.isHighscore(data_) && (game_->getType() == GameType::NORMAL || game_->GetField().GetLines() >= 50); } void GameOverScreen::step() { game_->GetField().step(); // Show GameOver animation game_->StepToRotateScreen(); if (game_->GameOverAnimationFinished()) { if (isHighscore()) { StepWidgets(); if (jngl::keyPressed(jngl::key::Return)) { data_.name = input_->getText(); getOptions().lastHighscoreName = data_.name; highscore_.Add(data_); highscore_.save(); auto menu = std::make_shared<Menu>(); menu->BlinkHighscore(data_); jngl::setWork(std::make_shared<Fade>(std::move(menu))); } } else { blink_ += 4; if (blink_ > 2 * 255) { blink_ = 0; } if (jngl::mousePressed() || jngl::keyPressed(jngl::key::Any)) { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } } } else if (jngl::keyPressed(jngl::key::Escape)) { while (!game_->GameOverAnimationFinished()) { game_->GetField().step(); } } } void GameOverScreen::onQuitEvent() { while (!game_->GameOverAnimationFinished()) { game_->GetField().step(); } if (!isHighscore()) { jngl::quit(); } } void GameOverScreen::draw() const { game_->draw(); jngl::setFontSize(80); jngl::setFontColor(0, 0, 0); GetScreen().printCentered("GAMEOVER", { 0, -100 }); if (game_->GameOverAnimationFinished()) { jngl::setFontSize(50); if (isHighscore()) { jngl::setFontColor(0, 0, 0); GetScreen().printCentered("You entered the top!", { 0, 50 }); GetScreen().printCentered("Enter your name:", { 0, 130 }); DrawWidgets(); } else { jngl::setFontColor(0, 0, 0, blink_ > 255 ? 510 - blink_ : blink_); GetScreen().printCentered("Press any key", { 0, 100 }); } } } diff --git a/src/gui/input.cpp b/src/gui/input.cpp index e3eb5bb..237394a 100644 --- a/src/gui/input.cpp +++ b/src/gui/input.cpp @@ -1,89 +1,89 @@ #include "input.hpp" #include <jngl.hpp> -Input::Input(int x, int y) : displayCursor(0) { - setPos(x, y); +Input::Input(const jngl::Vec2 position) : displayCursor(0) { + setPos(position); } void Input::setMaxWidth(unsigned int width) { maxWidth = width; } void Input::setPassword(bool password) { this->password = password; } void Input::onFocusChanged() { displayCursor = 50; } void Input::step() { const auto mousePos = jngl::getMousePos(); if (mousePos.x > position.x && mousePos.y > position.y && mousePos.x < position.x + maxWidth && mousePos.y < position.y + 94 /* TODO: Do not hardcode */) { jngl::setCursor(jngl::Cursor::I); if (jngl::mousePressed()) { setFocus(true); } } if (!sensitive || !focus) { return; } --displayCursor; if (displayCursor < -35 || !jngl::getTextInput().empty()) { displayCursor = 35; } text += jngl::getTextInput(); if (jngl::keyPressed(jngl::key::BackSpace) && !text.empty()) { removeLastCharacter(); } while (jngl::getTextWidth(text) > maxWidth) { removeLastCharacter(); } } void Input::draw() const { std::string temp; if (password) { temp = text; size_t size = jngl::utf8Length(text); text.clear(); for (size_t i = 0; i < size; ++i) { text += "●"; } } if (sensitive) { jngl::setFontColor(0, 0, 0); } else { jngl::setFontColor(150, 150, 150); } if (focus && displayCursor > 0) { jngl::print(text + "|", static_cast<int>(std::lround(position.x)), static_cast<int>(std::lround(position.y))); } else { jngl::print(text, static_cast<int>(std::lround(position.x)), static_cast<int>(std::lround(position.y))); } if (password) { text = temp; } } std::string Input::getText() const { return text; } void Input::setText(const std::string& text) { this->text = text; } void Input::removeLastCharacter() { displayCursor = 50; auto it = text.end(); --it; while (*it & 0x80 && !(*it & 0x40)) { // Unicode character? --it; } text.erase(it, text.end()); } diff --git a/src/gui/input.hpp b/src/gui/input.hpp index 9b6dc70..9479544 100644 --- a/src/gui/input.hpp +++ b/src/gui/input.hpp @@ -1,30 +1,30 @@ #pragma once #include "widget.hpp" #include <string> class Input : public Widget { public: - Input(int x, int y); + explicit Input(jngl::Vec2 position); void step() override; void draw() const override; std::string getText() const; void setText(const std::string&); void setMaxWidth(unsigned int); void setPassword(bool); void onFocusChanged() override; private: void removeLastCharacter(); mutable std::string text; bool password = false; int displayCursor; unsigned int maxWidth = 999; }; diff --git a/src/lobby.cpp b/src/lobby.cpp index 05b7d16..d886f0d 100644 --- a/src/lobby.cpp +++ b/src/lobby.cpp @@ -1,101 +1,101 @@ #include "lobby.hpp" #include "NetworkControl.hpp" #include "SplitScreen.hpp" #include "engine/fade.hpp" #include "gui/MessageBox.hpp" #include "multiplayermenu.hpp" #include <jngl.hpp> #include <nlohmann/json.hpp> Lobby::Lobby(std::shared_ptr<Socket> socket, bool quickLogin) -: socket_(socket), chatText_(""), input_(new Input(-700, 500)) { +: socket_(std::move(socket)), input_(new Input({ -700, 500 })) { logout_.reset(new Button("Logout", [this]() { OnLogout(); })); play_.reset(new Button("Play!™", [this]() { OnPlay(); })); startReceiving(); input_->setMaxWidth(2500); addWidget(input_); addWidget(logout_); addWidget(play_); logout_->setCenter(-450, -450); play_->setCenter(450, -450); if (quickLogin) { OnPlay(); } } void Lobby::OnLogout() { jngl::setWork(std::make_shared<Fade>(std::make_shared<MultiplayerMenu>(false))); } void Lobby::OnPlay() { play_->setSensitive(false); socket_->send(json{ { "type", "play" } }, []() { jngl::info("Successfully sent 'play'."); }); } void Lobby::step() { try { socket_->step(); } catch (std::exception& e) { jngl::setWork(std::make_shared<Fade>( std::make_shared<MessageBox>(e.what(), std::make_shared<MultiplayerMenu>(false)))); } if (jngl::keyPressed(jngl::key::Return)) { nlohmann::json j = { { "type", "chat" }, { "text", input_->getText() }, }; jngl::debug("Sending: {}", j.dump()); socket_->send(j, [this]() { OnMessageSent(); }); input_->setSensitive(false); } StepWidgets(); } void Lobby::OnMessageSent() { input_->setText(""); input_->setSensitive(true); } void Lobby::draw() const { jngl::setFontColor(0, 0, 0); jngl::setFontSize(35); jngl::print(chatText_, -700, -250); DrawWidgets(); } void Lobby::handleReceive(json buf) { if (buf["type"] == "chat") { chatText_ += buf["text"]; chatText_ += '\n'; int lineCount = 0; size_t pos = 0; while ((pos = chatText_.find_first_of("\n", pos + 1)) != std::string::npos) { ++lineCount; } if (lineCount > 13) { pos = chatText_.find_first_of("\n"); chatText_ = chatText_.substr(pos + 1); } } else if (buf["type"] == "play") { // Matchmaking was successful and an opponent found. Let's start the game. jngl::debug("Starting match making"); auto control = std::make_shared<NetworkControl>(socket_); jngl::setWork(std::make_shared<Fade>( std::make_shared<SplitScreen>(control, buf["seed"].get<int32_t>()))); return; // move out of Lobby loop } else if (buf["type"] == "error") { jngl::setWork<MessageBox>(buf["msg"], std::make_shared<MultiplayerMenu>(false)); return; } else { std::ostringstream tmp; tmp << buf; jngl::warn("Received unknown type: {}", tmp.str()); } startReceiving(); } void Lobby::startReceiving() { socket_->receive([this](json buf) { handleReceive(std::move(buf)); }); } diff --git a/src/multiplayermenu.cpp b/src/multiplayermenu.cpp index 411519f..cd06316 100644 --- a/src/multiplayermenu.cpp +++ b/src/multiplayermenu.cpp @@ -1,57 +1,57 @@ #include "multiplayermenu.hpp" #include "Login.hpp" #include "engine/Options.hpp" #include "engine/fade.hpp" #include "menu.hpp" #include <jngl.hpp> MultiplayerMenu::MultiplayerMenu(const bool quickLogin) -: name_(new Input(50, -240)), password_(new Input(50, -100)), quickLogin(quickLogin) { +: name_(new Input({ 50, -240 })), password_(new Input({ 50, -100 })), quickLogin(quickLogin) { addWidget(name_); addWidget(password_); login_.reset(new Button("Login", [this]() { OnLogin(); })); addWidget(login_); back_.reset(new Button("Back", [this]() { OnBack(); })); addWidget(back_); back_->setCenter(-350, 280); login_->setCenter(350, 280); password_->setPassword(true); name_->setText(getOptions().lastLoginName); if (name_->getText() != "") { FocusNext(); } } void MultiplayerMenu::step() { StepWidgets(); if (jngl::keyPressed(jngl::key::Return) || quickLogin) { OnLogin(); quickLogin = false; // if an error happens we will be reactivated } } void MultiplayerMenu::draw() const { jngl::setFontColor(0, 0, 0); jngl::print("Name:", -500, -240); jngl::print("Password:", -500, -100); DrawWidgets(); } void MultiplayerMenu::OnBack() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void MultiplayerMenu::OnLogin() { jngl::setWork(std::make_shared<Login>( std::dynamic_pointer_cast<MultiplayerMenu>(jngl::getWork()), quickLogin)); } std::string MultiplayerMenu::GetName() const { return name_->getText(); } std::string MultiplayerMenu::GetPassword() const { return password_->getText(); }
jhasse/jntetri
a93b1cbe6f1e1b776a6388acbbaf694492ab70cd
Rename Input::displayCursor_ to displayCursor
diff --git a/src/gui/input.cpp b/src/gui/input.cpp index ad83ca3..e3eb5bb 100644 --- a/src/gui/input.cpp +++ b/src/gui/input.cpp @@ -1,89 +1,89 @@ #include "input.hpp" #include <jngl.hpp> -Input::Input(int x, int y) : displayCursor_(0) { +Input::Input(int x, int y) : displayCursor(0) { setPos(x, y); } void Input::setMaxWidth(unsigned int width) { maxWidth = width; } void Input::setPassword(bool password) { this->password = password; } void Input::onFocusChanged() { - displayCursor_ = 50; + displayCursor = 50; } void Input::step() { const auto mousePos = jngl::getMousePos(); if (mousePos.x > position.x && mousePos.y > position.y && mousePos.x < position.x + maxWidth && mousePos.y < position.y + 94 /* TODO: Do not hardcode */) { jngl::setCursor(jngl::Cursor::I); if (jngl::mousePressed()) { setFocus(true); } } if (!sensitive || !focus) { return; } - --displayCursor_; - if (displayCursor_ < -35 || !jngl::getTextInput().empty()) { - displayCursor_ = 35; + --displayCursor; + if (displayCursor < -35 || !jngl::getTextInput().empty()) { + displayCursor = 35; } text += jngl::getTextInput(); if (jngl::keyPressed(jngl::key::BackSpace) && !text.empty()) { removeLastCharacter(); } while (jngl::getTextWidth(text) > maxWidth) { removeLastCharacter(); } } void Input::draw() const { std::string temp; if (password) { temp = text; size_t size = jngl::utf8Length(text); text.clear(); for (size_t i = 0; i < size; ++i) { text += "●"; } } if (sensitive) { jngl::setFontColor(0, 0, 0); } else { jngl::setFontColor(150, 150, 150); } - if (focus && displayCursor_ > 0) { + if (focus && displayCursor > 0) { jngl::print(text + "|", static_cast<int>(std::lround(position.x)), static_cast<int>(std::lround(position.y))); } else { jngl::print(text, static_cast<int>(std::lround(position.x)), static_cast<int>(std::lround(position.y))); } if (password) { text = temp; } } std::string Input::getText() const { return text; } void Input::setText(const std::string& text) { this->text = text; } void Input::removeLastCharacter() { - displayCursor_ = 50; + displayCursor = 50; auto it = text.end(); --it; while (*it & 0x80 && !(*it & 0x40)) { // Unicode character? --it; } text.erase(it, text.end()); } diff --git a/src/gui/input.hpp b/src/gui/input.hpp index 360e877..9b6dc70 100644 --- a/src/gui/input.hpp +++ b/src/gui/input.hpp @@ -1,31 +1,30 @@ #pragma once #include "widget.hpp" #include <string> -#include <vector> class Input : public Widget { public: Input(int x, int y); void step() override; void draw() const override; std::string getText() const; void setText(const std::string&); void setMaxWidth(unsigned int); void setPassword(bool); void onFocusChanged() override; private: void removeLastCharacter(); mutable std::string text; bool password = false; - int displayCursor_; + int displayCursor; unsigned int maxWidth = 999; };
jhasse/jntetri
bfb49ccb8ea0921ef87aad2149bd15d83accf87c
Add --server argument
diff --git a/.vscode/launch.json b/.vscode/launch.json index 1e9ecbe..79b099d 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,23 +1,26 @@ { "version": "0.2.0", "configurations": [ { - "type": "gdb", + "type": "lldb", "request": "launch", - "name": "jntetri (GDB)", - "target": "./build/Debug/jntetri", + "name": "jntetri", + "program": "${workspaceRoot}/build/Debug/jntetri", + "args": [], "cwd": "${workspaceRoot}", - "valuesFormatting": "prettyPrinters", "preLaunchTask": "build" }, { "type": "lldb", "request": "launch", - "name": "jntetri (lldb)", + "name": "jntetri --server 127.0.0.1", "program": "${workspaceRoot}/build/Debug/jntetri", - "args": [], + "args": [ + "--server", + "127.0.0.1" + ], "cwd": "${workspaceRoot}", "preLaunchTask": "build" } ] } diff --git a/src/Login.cpp b/src/Login.cpp index 43d3581..413b024 100644 --- a/src/Login.cpp +++ b/src/Login.cpp @@ -1,182 +1,187 @@ #include "Login.hpp" #include "../server/NetworkConstants.hpp" #include "engine/Options.hpp" #include "engine/fade.hpp" #include "engine/screen.hpp" #include "gui/Button.hpp" #include "lobby.hpp" #include <boost/bind/bind.hpp> -#include <jngl.hpp> #include <utility> +Login::Settings::Settings() +: server("185.232.70.178"), // boomshine.de #ifdef __EMSCRIPTEN__ -const std::string Login::server_("89.58.48.219"); // boomshine.de -const int Login::port_ = 9999; + port(9999) #else -// const std::string Login::server_("127.0.0.1"); -const std::string Login::server_("185.232.70.178"); // boomshine.de -const int Login::port_ = 7070; + port(7070) #endif +{ + const auto args = jngl::getArgs(); + if (args.size() == 2 && args[0] == "--server") { + server = args[1]; + } +} Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu, bool quickLogin) : menu(std::move(multiplayerMenu)), text_("connecting ..."), cancel_("Cancel", [this]() { OnCancel(); }), socket_(new Socket), quickLogin(quickLogin) { - jngl::info("Connecting to {}:{}", server_, port_); + jngl::info("Connecting to {}:{}", Settings::handle().server, Settings::handle().port); try { - socket_->connect(server_, port_, [this]() { HandleConnect(); }); + socket_->connect(Settings::handle().server, Settings::handle().port, + [this]() { HandleConnect(); }); } catch (std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.setCenter(0, 200); } void Login::HandleConnect() { text_ = "sending ..."; jngl::info("Sending protocol version {}", PROTOCOL_VERSION); socket_->send(std::to_string(PROTOCOL_VERSION), [this]() { ProtocolCheck1(); }); } void Login::ProtocolCheck1() { text_ = "receiving ..."; jngl::info("Waiting for server accept connection"); socket_->receive([this](json data) { ProtocolCheck2(std::move(data)); }); } void Login::ProtocolCheck2(json temp) { if (temp["type"] != "ok") { text_ = "Error: "; if (const std::string msg = temp["msg"]; !msg.empty()) { text_ += msg; } else { text_ += temp.dump(); } OnError(); } else { if (menu->GetName().empty()) { if (!menu->GetPassword().empty()) { text_ = "Name must not be empty!"; return OnError(); } socket_->send(json{ { "type", "login_anonymous" } }, [this]() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; }); } else { socket_->send(json{ { "type", "login" }, { "name", menu->GetName() }, { "password", menu->GetPassword() } }, [this]() { HandleLogin1(); }); } } } void Login::HandleLogin1() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; } void Login::HandleLogin2(json temp) { if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else if (temp["type"] == "unknown name") { text_ = "No user with this name found.\nDo you want to register yourself?"; cancel_.setCenter(-350, 280); cancel_.SetText("No"); - Button* yes = new Button("Yes", boost::bind(&Login::Register, this)); + Button* yes = new Button("Yes", [this] { Register(); }); yes->setCenter(350, 280); addWidget(std::shared_ptr<Widget>(yes)); } else if (temp["type"] == "wrong password") { text_ = "The password you've entered\nis wrong. Please try again."; OnError(); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::Register() { json j{ { "type", "register" }, { "name", menu->GetName() }, { "password", menu->GetPassword() } }; jngl::info("Sending: {}", j.dump()); - socket_->send(j, boost::bind(&Login::HandleRegister1, this)); + socket_->send(j, [this] { HandleRegister1(); }); cancel_.setCenter(0, 200); cancel_.SetText("Cancel"); widgets_.clear(); // FIXME: Implement RemoveWidget function } void Login::HandleRegister1() { socket_->receive([this](json temp) { HandleRegister2(std::move(temp)); }); text_ = "please wait ..."; } void Login::HandleRegister2(json temp) { jngl::debug("HandleRegister2"); if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::step() { try { if (socket_) { socket_->step(); } } catch (std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.step(); StepWidgets(); } void Login::GoToLobby(std::string username) { getOptions().lastLoginName = std::move(username); getOptions().Save(); jngl::setWork(std::make_shared<Fade>(std::make_shared<Lobby>(std::move(socket_), quickLogin))); } void Login::draw() const { menu->draw(); jngl::setColor(255, 255, 255, 220); jngl::drawRect(-jngl::getScreenWidth() / 2, -jngl::getScreenHeight() / 2, jngl::getScreenWidth(), jngl::getScreenHeight()); jngl::setFontColor(0, 0, 0); GetScreen().printCentered(text_, { 0, -150 }); cancel_.draw(); DrawWidgets(); } void Login::OnCancel() { jngl::setWork(menu); } void Login::OnError() { // hacked together algorithm to word wrap long error messages: size_t pos = 42; while (jngl::getTextWidth(text_) > jngl::getScreenWidth() && pos < text_.size()) { size_t i = pos; while (i > 0 && text_[i - 1] != ' ') { if (text_[i] == '\n') { i = pos; break; } --i; } text_.insert(text_.begin() + i, '\n'); pos += 42; } cancel_.SetText("OK"); cancel_.setFocus(true); } diff --git a/src/Login.hpp b/src/Login.hpp index 2c4d1ac..8ee50bc 100644 --- a/src/Login.hpp +++ b/src/Login.hpp @@ -1,36 +1,40 @@ #pragma once #include "engine/work.hpp" #include "engine/socket.hpp" #include "gui/Button.hpp" #include "multiplayermenu.hpp" #include <boost/asio.hpp> +#include <jngl.hpp> class Login : public Work { public: Login(std::shared_ptr<MultiplayerMenu>, bool quickLogin); void step() override; void draw() const override; void HandleConnect(); void ProtocolCheck1(); void ProtocolCheck2(json); void HandleLogin1(); void HandleLogin2(json); void OnCancel(); void OnError(); void Register(); void HandleRegister1(); void HandleRegister2(json); void GoToLobby(std::string username); private: std::shared_ptr<MultiplayerMenu> menu; std::string text_; - const static std::string server_; - const static int port_; - const static std::string protocolVersion_; Button cancel_; std::shared_ptr<Socket> socket_; bool quickLogin; + + struct Settings : jngl::Singleton<Settings> { + Settings(); + std::string server; + int port; + }; };
jhasse/jntetri
8565fa90bcf68cef41a64a1ef06d99d3a5539a58
Fix warnings in tetromino.cpp
diff --git a/src/tetromino.cpp b/src/tetromino.cpp index cf1b22b..dd8aa73 100644 --- a/src/tetromino.cpp +++ b/src/tetromino.cpp @@ -1,315 +1,317 @@ #include "tetromino.hpp" #include "Field.hpp" #include <numbers> Tetromino::Tetromino(int type, Field& field) : field_(field), shadow(jngl::ScaleablePixels(6 * Block::size), jngl::ScaleablePixels(6 * Block::size)) { assert(0 <= type && type < 7); switch (type) { case 0: { jngl::Color color(200, 200, 0); - blocks_.push_back(Block(-1, 1, color)); // XX - blocks_.push_back(Block(0, 1, color)); // XX - blocks_.push_back(Block(-1, 0, color)); - blocks_.push_back(Block(0, 0, color)); + blocks_.emplace_back(-1, 1, color); // XX + blocks_.emplace_back(0, 1, color); // XX + blocks_.emplace_back(-1, 0, color); + blocks_.emplace_back(0, 0, color); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); break; } case 1: { jngl::Color color(200, 0, 0); - blocks_.push_back(Block(-1, 0, color)); // 1234 - blocks_.push_back(Block(0, 0, color)); - blocks_.push_back(Block(1, 0, color)); - blocks_.push_back(Block(2, 0, color)); + blocks_.emplace_back(-1, 0, color); // 1234 + blocks_.emplace_back(0, 0, color); + blocks_.emplace_back(1, 0, color); + blocks_.emplace_back(2, 0, color); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(0.5); rotationCenterY_.push_back(-0.5); break; } case 2: { jngl::Color color(0, 200, 200); - blocks_.push_back(Block(0, 1, color)); // 1 - blocks_.push_back(Block(-1, 0, color)); // 234 - blocks_.push_back(Block(0, 0, color)); - blocks_.push_back(Block(1, 0, color)); + blocks_.emplace_back(0, 1, color); // 1 + blocks_.emplace_back(-1, 0, color); // 234 + blocks_.emplace_back(0, 0, color); + blocks_.emplace_back(1, 0, color); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); break; } case 3: { jngl::Color color(0, 0, 200); - blocks_.push_back(Block(0, 1, color)); // 1 - blocks_.push_back(Block(0, 0, color)); // 2 - blocks_.push_back(Block(0, -1, color)); // 43 - blocks_.push_back(Block(-1, -1, color)); + blocks_.emplace_back(0, 1, color); // 1 + blocks_.emplace_back(0, 0, color); // 2 + blocks_.emplace_back(0, -1, color); // 43 + blocks_.emplace_back(-1, -1, color); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); break; } case 4: { jngl::Color color(200, 100, 0); - blocks_.push_back(Block(-1, 1, color)); // 12 - blocks_.push_back(Block(0, 1, color)); // 3 - blocks_.push_back(Block(0, 0, color)); // 4 - blocks_.push_back(Block(0, -1, color)); + blocks_.emplace_back(-1, 1, color); // 12 + blocks_.emplace_back(0, 1, color); // 3 + blocks_.emplace_back(0, 0, color); // 4 + blocks_.emplace_back(0, -1, color); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); break; } case 5: { jngl::Color color(200, 0, 200); - blocks_.push_back(Block(0, 1, color)); // 12 - blocks_.push_back(Block(1, 1, color)); // 34 - blocks_.push_back(Block(-1, 0, color)); - blocks_.push_back(Block(0, 0, color)); + blocks_.emplace_back(0, 1, color); // 12 + blocks_.emplace_back(1, 1, color); // 34 + blocks_.emplace_back(-1, 0, color); + blocks_.emplace_back(0, 0, color); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); break; } case 6: { jngl::Color color(0, 200, 0); - blocks_.push_back(Block(-1, 1, color)); // 12 - blocks_.push_back(Block(0, 1, color)); // 34 - blocks_.push_back(Block(0, 0, color)); - blocks_.push_back(Block(1, 0, color)); + blocks_.emplace_back(-1, 1, color); // 12 + blocks_.emplace_back(0, 1, color); // 34 + blocks_.emplace_back(0, 0, color); + blocks_.emplace_back(1, 0, color); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); break; } + default: + assert(false); } - int numberOfRotations = field_.getRandom() % 4; - for (int i = 0; i < numberOfRotations; ++i) { + uint32_t numberOfRotations = field_.getRandom() % 4; + for (uint32_t i = 0; i < numberOfRotations; ++i) { Rotate(CLOCKWISE, true); } animationX_ = animationY_ = rotation_ = 0; // Clear animation set by Rotate(CLOCKWISE) x_ = 5; y_ = 17; } void Tetromino::Step() { animationX_ *= 0.7; animationY_ *= 0.8; rotation_ *= 0.8; if (field_.getControl().Check(ControlType::Left)) { changeX(-1); if (Collided()) { changeX(1); } } if (field_.getControl().Check(ControlType::Right)) { changeX(1); if (Collided()) { changeX(-1); } } if (field_.getControl().Check(ControlType::Rotate)) { Rotate(CLOCKWISE, false); } if (field_.getControl().Check(ControlType::RotateCounter)) { Rotate(COUNTERCLOCKWISE, false); } } void Tetromino::SetX(const int x) { x_ = x; } void Tetromino::changeX(int c) { x_ += c; animationX_ -= c; } void Tetromino::changeY(int c) { y_ += c; animationY_ -= c; } void Tetromino::Rotate(const Direction direction, bool ignoreCollision) { // if ignoreCollision is true, we don't want to make any calls to Collided() bool collidedBeforeRotation = ignoreCollision || Collided(); auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (direction == CLOCKWISE) { it->rotate(direction, rotationCenterX_.front(), rotationCenterY_.front()); } else { it->rotate(direction, rotationCenterX_.back(), rotationCenterY_.back()); } } rotationCenterX_.push_back(rotationCenterX_.front()); rotationCenterX_.pop_front(); rotationCenterY_.push_back(rotationCenterY_.front()); rotationCenterY_.pop_front(); if (direction == CLOCKWISE) { rotation_ -= 90; } else { rotation_ += 90; } if (!collidedBeforeRotation && Collided()) { changeX(1); if (Collided()) { changeX(-2); if (Collided()) { changeX(3); if (Collided()) { changeX(-4); if (Collided()) { changeX(2); // Undo rotation if (direction == CLOCKWISE) { Rotate(COUNTERCLOCKWISE, true); } else { Rotate(CLOCKWISE, true); } } } } } } } void Tetromino::AttachToField() { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { it->setX(it->getX() + x_); it->setY(it->getY() + y_); it->setAnimationX(animationX_); it->setAnimationY(animationY_); it->flash(); field_.AddBlock(*it); } } bool Tetromino::MoveDown() { --y_; if (Collided()) { ++y_; return false; } animationY_ += 1; return true; } void Tetromino::moveUp(int amount) { y_ += amount; animationY_ -= amount; } void Tetromino::draw(bool withShadow) const { if (withShadow) { auto context = shadow.use(); jngl::translate(-Block::size / 2., -Block::size / 2.); context.clear(); jngl::setSpriteColor(0, 0, 0, 10); // 10 // at y == 310 no tetromino would be visible const double STEP_SIZE = 2; for (double y = 1; y < 310; y += STEP_SIZE) { jngl::translate(0, STEP_SIZE); drawBlocks(jngl::modelview()); } jngl::setSpriteAlpha(255); } assert(!blocks_.empty()); blocks_.front().setSpriteColor(); drawBlocks( jngl::modelview().translate({ field_.indexToPixel(x_ + animationX_, y_ + animationY_) })); jngl::setSpriteColor(255, 255, 255); } void Tetromino::drawShadow() const { jngl::pushMatrix(); const auto pos = field_.indexToPixel(x_ + animationX_, y_ + animationY_); jngl::translate(pos); jngl::translate(-Block::size * 2.5, -Block::size * 2.5); jngl::setSpriteAlpha(50); const float width = shadow.getSize().x; float height = shadow.getSize().y; float minV = 0; float extensionHeight = field_.getBottomY() - pos.y - height / 2.; if (extensionHeight < 0) { height += extensionHeight; minV = -extensionHeight / shadow.getSize().y; assert(minV >= 0 && minV <= 1); extensionHeight = 0; } shadow.drawMesh({ // top right triangle jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, jngl::Vertex{ .x = width, .y = 0, .u = 1, .v = 1 }, jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, // bottom left triangle jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, jngl::Vertex{ .x = 0, .y = height, .u = 0, .v = minV }, jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, // Now extend the end of the shadow (v == 0) to the bottom of the field: // top right triangle jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, jngl::Vertex{ .x = width, .y = height + 0, .u = 1, .v = 0 }, jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, // bottom left triangle jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, jngl::Vertex{ .x = 0, .y = height + extensionHeight, .u = 0, .v = 0 }, jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, }); jngl::setSpriteAlpha(255); jngl::popMatrix(); } bool Tetromino::Collided() const { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (field_.checkCollision(x_ + it->getX(), y_ + it->getY())) { return true; } } return false; } void Tetromino::drop() { - while (MoveDown()) - ; + while (MoveDown()) { + } animationX_ = animationY_ = 0; } void Tetromino::drawBlocks(jngl::Mat3 modelview) const { const int blockSize = field_.getBlockSize(); if (rotation_ < 0) { // Clockwise modelview .translate( { rotationCenterX_.back() * blockSize, -rotationCenterY_.back() * blockSize }) .rotate(rotation_ * std::numbers::pi / 180) .translate( { -rotationCenterX_.back() * blockSize, rotationCenterY_.back() * blockSize }); } else { modelview .translate( { rotationCenterX_.front() * blockSize, -rotationCenterY_.front() * blockSize }) .rotate(rotation_ * std::numbers::pi / 180) .translate( { -rotationCenterX_.front() * blockSize, rotationCenterY_.front() * blockSize }); } for (auto& block : blocks_) { block.draw(modelview); } }
jhasse/jntetri
d005e73f419f027bdc460afded25a11f9b0eda98
web: Add #include <numbers>
diff --git a/src/tetromino.cpp b/src/tetromino.cpp index 7d25a1e..cf1b22b 100644 --- a/src/tetromino.cpp +++ b/src/tetromino.cpp @@ -1,313 +1,315 @@ #include "tetromino.hpp" #include "Field.hpp" +#include <numbers> + Tetromino::Tetromino(int type, Field& field) : field_(field), shadow(jngl::ScaleablePixels(6 * Block::size), jngl::ScaleablePixels(6 * Block::size)) { assert(0 <= type && type < 7); switch (type) { case 0: { jngl::Color color(200, 200, 0); blocks_.push_back(Block(-1, 1, color)); // XX blocks_.push_back(Block(0, 1, color)); // XX blocks_.push_back(Block(-1, 0, color)); blocks_.push_back(Block(0, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); break; } case 1: { jngl::Color color(200, 0, 0); blocks_.push_back(Block(-1, 0, color)); // 1234 blocks_.push_back(Block(0, 0, color)); blocks_.push_back(Block(1, 0, color)); blocks_.push_back(Block(2, 0, color)); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(0.5); rotationCenterY_.push_back(-0.5); break; } case 2: { jngl::Color color(0, 200, 200); blocks_.push_back(Block(0, 1, color)); // 1 blocks_.push_back(Block(-1, 0, color)); // 234 blocks_.push_back(Block(0, 0, color)); blocks_.push_back(Block(1, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); break; } case 3: { jngl::Color color(0, 0, 200); blocks_.push_back(Block(0, 1, color)); // 1 blocks_.push_back(Block(0, 0, color)); // 2 blocks_.push_back(Block(0, -1, color)); // 43 blocks_.push_back(Block(-1, -1, color)); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); break; } case 4: { jngl::Color color(200, 100, 0); blocks_.push_back(Block(-1, 1, color)); // 12 blocks_.push_back(Block(0, 1, color)); // 3 blocks_.push_back(Block(0, 0, color)); // 4 blocks_.push_back(Block(0, -1, color)); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); break; } case 5: { jngl::Color color(200, 0, 200); blocks_.push_back(Block(0, 1, color)); // 12 blocks_.push_back(Block(1, 1, color)); // 34 blocks_.push_back(Block(-1, 0, color)); blocks_.push_back(Block(0, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); break; } case 6: { jngl::Color color(0, 200, 0); blocks_.push_back(Block(-1, 1, color)); // 12 blocks_.push_back(Block(0, 1, color)); // 34 blocks_.push_back(Block(0, 0, color)); blocks_.push_back(Block(1, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back(0.5); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); break; } } int numberOfRotations = field_.getRandom() % 4; for (int i = 0; i < numberOfRotations; ++i) { Rotate(CLOCKWISE, true); } animationX_ = animationY_ = rotation_ = 0; // Clear animation set by Rotate(CLOCKWISE) x_ = 5; y_ = 17; } void Tetromino::Step() { animationX_ *= 0.7; animationY_ *= 0.8; rotation_ *= 0.8; if (field_.getControl().Check(ControlType::Left)) { changeX(-1); if (Collided()) { changeX(1); } } if (field_.getControl().Check(ControlType::Right)) { changeX(1); if (Collided()) { changeX(-1); } } if (field_.getControl().Check(ControlType::Rotate)) { Rotate(CLOCKWISE, false); } if (field_.getControl().Check(ControlType::RotateCounter)) { Rotate(COUNTERCLOCKWISE, false); } } void Tetromino::SetX(const int x) { x_ = x; } void Tetromino::changeX(int c) { x_ += c; animationX_ -= c; } void Tetromino::changeY(int c) { y_ += c; animationY_ -= c; } void Tetromino::Rotate(const Direction direction, bool ignoreCollision) { // if ignoreCollision is true, we don't want to make any calls to Collided() bool collidedBeforeRotation = ignoreCollision || Collided(); auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (direction == CLOCKWISE) { it->rotate(direction, rotationCenterX_.front(), rotationCenterY_.front()); } else { it->rotate(direction, rotationCenterX_.back(), rotationCenterY_.back()); } } rotationCenterX_.push_back(rotationCenterX_.front()); rotationCenterX_.pop_front(); rotationCenterY_.push_back(rotationCenterY_.front()); rotationCenterY_.pop_front(); if (direction == CLOCKWISE) { rotation_ -= 90; } else { rotation_ += 90; } if (!collidedBeforeRotation && Collided()) { changeX(1); if (Collided()) { changeX(-2); if (Collided()) { changeX(3); if (Collided()) { changeX(-4); if (Collided()) { changeX(2); // Undo rotation if (direction == CLOCKWISE) { Rotate(COUNTERCLOCKWISE, true); } else { Rotate(CLOCKWISE, true); } } } } } } } void Tetromino::AttachToField() { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { it->setX(it->getX() + x_); it->setY(it->getY() + y_); it->setAnimationX(animationX_); it->setAnimationY(animationY_); it->flash(); field_.AddBlock(*it); } } bool Tetromino::MoveDown() { --y_; if (Collided()) { ++y_; return false; } animationY_ += 1; return true; } void Tetromino::moveUp(int amount) { y_ += amount; animationY_ -= amount; } void Tetromino::draw(bool withShadow) const { if (withShadow) { auto context = shadow.use(); jngl::translate(-Block::size / 2., -Block::size / 2.); context.clear(); jngl::setSpriteColor(0, 0, 0, 10); // 10 // at y == 310 no tetromino would be visible const double STEP_SIZE = 2; for (double y = 1; y < 310; y += STEP_SIZE) { jngl::translate(0, STEP_SIZE); drawBlocks(jngl::modelview()); } jngl::setSpriteAlpha(255); } assert(!blocks_.empty()); blocks_.front().setSpriteColor(); drawBlocks( jngl::modelview().translate({ field_.indexToPixel(x_ + animationX_, y_ + animationY_) })); jngl::setSpriteColor(255, 255, 255); } void Tetromino::drawShadow() const { jngl::pushMatrix(); const auto pos = field_.indexToPixel(x_ + animationX_, y_ + animationY_); jngl::translate(pos); jngl::translate(-Block::size * 2.5, -Block::size * 2.5); jngl::setSpriteAlpha(50); const float width = shadow.getSize().x; float height = shadow.getSize().y; float minV = 0; float extensionHeight = field_.getBottomY() - pos.y - height / 2.; if (extensionHeight < 0) { height += extensionHeight; minV = -extensionHeight / shadow.getSize().y; assert(minV >= 0 && minV <= 1); extensionHeight = 0; } shadow.drawMesh({ // top right triangle jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, jngl::Vertex{ .x = width, .y = 0, .u = 1, .v = 1 }, jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, // bottom left triangle jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, jngl::Vertex{ .x = 0, .y = height, .u = 0, .v = minV }, jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, // Now extend the end of the shadow (v == 0) to the bottom of the field: // top right triangle jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, jngl::Vertex{ .x = width, .y = height + 0, .u = 1, .v = 0 }, jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, // bottom left triangle jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, jngl::Vertex{ .x = 0, .y = height + extensionHeight, .u = 0, .v = 0 }, jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, }); jngl::setSpriteAlpha(255); jngl::popMatrix(); } bool Tetromino::Collided() const { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (field_.checkCollision(x_ + it->getX(), y_ + it->getY())) { return true; } } return false; } void Tetromino::drop() { while (MoveDown()) ; animationX_ = animationY_ = 0; } void Tetromino::drawBlocks(jngl::Mat3 modelview) const { const int blockSize = field_.getBlockSize(); if (rotation_ < 0) { // Clockwise modelview .translate( { rotationCenterX_.back() * blockSize, -rotationCenterY_.back() * blockSize }) .rotate(rotation_ * std::numbers::pi / 180) .translate( { -rotationCenterX_.back() * blockSize, rotationCenterY_.back() * blockSize }); } else { modelview .translate( { rotationCenterX_.front() * blockSize, -rotationCenterY_.front() * blockSize }) .rotate(rotation_ * std::numbers::pi / 180) .translate( { -rotationCenterX_.front() * blockSize, rotationCenterY_.front() * blockSize }); } for (auto& block : blocks_) { block.draw(modelview); } }
jhasse/jntetri
bdf6086fde6e034a059a232ab36d15edb738c92c
clang-tidy: -readability-math-missing-parentheses
diff --git a/.clang-tidy b/.clang-tidy index 7f9acec..be8df53 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,71 +1,72 @@ --- Checks: ' ,*, ,-altera-id-dependent-backward-branch, ,-altera-struct-pack-align, ,-altera-unroll-loops, ,-android-cloexec-fopen, ,-bugprone-easily-swappable-parameters, ,-cert-err52-cpp, ,-cert-err58-cpp, ,-cert-flp30-c, ,-clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, ,-clang-diagnostic-unused-command-line-argument, ,-cppcoreguidelines-avoid-c-arrays, ,-cppcoreguidelines-avoid-const-or-ref-data-members, ,-cppcoreguidelines-avoid-magic-numbers, ,-cppcoreguidelines-avoid-non-const-global-variables, ,-cppcoreguidelines-init-variables, ,-cppcoreguidelines-non-private-member-variables-in-classes, ,-cppcoreguidelines-owning-memory, ,-cppcoreguidelines-pro-bounds-array-to-pointer-decay, ,-cppcoreguidelines-pro-bounds-constant-array-index, ,-cppcoreguidelines-pro-bounds-pointer-arithmetic, ,-cppcoreguidelines-pro-type-vararg, ,-cppcoreguidelines-special-member-functions, ,-fuchsia-default-arguments-calls, ,-fuchsia-default-arguments-declarations, ,-fuchsia-default-arguments, ,-fuchsia-multiple-inheritance, ,-fuchsia-overloaded-operator, ,-fuchsia-statically-constructed-objects, ,-google-global-names-in-headers, ,-google-readability-todo, ,-google-runtime-int, ,-google-runtime-references, ,-hicpp-avoid-c-arrays, ,-hicpp-named-parameter, ,-hicpp-no-array-decay, ,-hicpp-signed-bitwise, ,-hicpp-special-member-functions, ,-hicpp-uppercase-literal-suffix, ,-hicpp-vararg, ,-llvm-header-guard, ,-llvm-qualified-auto, ,-llvmlibc-callee-namespace, ,-llvmlibc-implementation-in-namespace, ,-llvmlibc-inline-function-decl, ,-llvmlibc-restrict-system-libc-headers, ,-misc-no-recursion, ,-misc-non-private-member-variables-in-classes, ,-modernize-avoid-c-arrays, ,-modernize-use-nodiscard, ,-modernize-use-trailing-return-type, ,-readability-function-cognitive-complexity, ,-readability-identifier-length, ,-readability-magic-numbers, + ,-readability-math-missing-parentheses, ,-readability-named-parameter, ,-readability-qualified-auto, ,-readability-uppercase-literal-suffix, ,-readability-use-anyofallof, ' WarningsAsErrors: 'hicpp-use-override,modernize-avoid-bind,llvm-namespace-comment,modernize-use-nullptr,modernize-pass-by-value,hicpp-noexcept-move,boost-use-to-string,google-readability-namespace-comments,modernize-use-default-member-init,modernize-loop-convert,hicpp-use-nullptr,google-readability-braces-around-statements,cert-dcl03-c,readability-else-after-return,bugprone-macro-parentheses,readability-redundant-declaration,google-explicit-constructor,readability-avoid-const-params-in-decls' CheckOptions: - key: readability-implicit-bool-conversion.AllowPointerConditions value: '1' - key: readability-implicit-bool-conversion.AllowIntegerConditions value: '1' - key: bugprone-narrowing-conversions.WarnOnFloatingPointNarrowingConversion value: '0' - key: cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion value: '0'
jhasse/jntetri
b6ca17e3a7c809aa7d685f419229914c0117fb2e
Modernize drawing of Block using jngl::Mat3 modelview
diff --git a/src/Block.cpp b/src/Block.cpp index 2ed22d3..b84c68d 100644 --- a/src/Block.cpp +++ b/src/Block.cpp @@ -1,87 +1,87 @@ #include "Block.hpp" #include "engine/screen.hpp" #include <jngl/Sprite.hpp> const int Block::size = 60; Block::Block(int x, int y, jngl::Color color) : x(x), y(y), color(color), flashAnimation(0) { } void Block::step() { animationX *= 0.7; animationY *= 0.95; if (flashAnimation > 0) { flashAnimation *= 0.96; } } void Block::setAnimationY(double a) { animationY = a; } double Block::getAnimationY() const { return animationY; } void Block::setAnimationX(double a) { animationX = a; } double Block::getAnimationX() const { return animationX; } void Block::setSpriteColor() const { jngl::setSpriteColor(static_cast<unsigned char>(color.getRed() + flashAnimation), static_cast<unsigned char>(color.getGreen() + flashAnimation), static_cast<unsigned char>(color.getBlue() + flashAnimation)); } -void Block::draw() const { - GetScreen().DrawCentered("block", (x + animationX) * size, -(y + animationY) * size); +void Block::draw(jngl::Mat3 modelview) const { + sprite.draw(modelview.translate({ (x + animationX) * size, -(y + animationY) * size })); } void Block::rotate(Direction direction, double rotationCenterX, double rotationCenterY) { double tempX, tempY; double xRot = x - rotationCenterX; double yRot = y - rotationCenterY; if (direction == CLOCKWISE) { tempX = yRot; tempY = -xRot; } else { tempX = -yRot; tempY = xRot; } x = static_cast<int>(tempX + rotationCenterX); y = static_cast<int>(tempY + rotationCenterY); } int Block::getX() const { return x; } int Block::getY() const { return y; } void Block::setX(const int x) { this->x = x; } void Block::setY(const int y) { this->y = y; } int Block::getSize() const { return size; } jngl::Color Block::getColor() const { return color; } void Block::flash() { flashAnimation = 50; } diff --git a/src/Block.hpp b/src/Block.hpp index a0f81a5..d049b6b 100644 --- a/src/Block.hpp +++ b/src/Block.hpp @@ -1,42 +1,43 @@ #pragma once -#include <jngl/Color.hpp> +#include <jngl.hpp> enum Direction { CLOCKWISE, COUNTERCLOCKWISE }; class Block { public: Block(int x, int y, jngl::Color color); void step(); void setSpriteColor() const; - void draw() const; + void draw(jngl::Mat3 modelview) const; int getX() const; int getY() const; void setX(int); void setY(int); void rotate(Direction, double rotationCenterX, double rotationCenterY); void setAnimationX(double); void setAnimationY(double); double getAnimationX() const; double getAnimationY() const; /// Returns width/height in dp int getSize() const; jngl::Color getColor() const; void flash(); /// width/height in dp const static int size; private: int x, y; double animationX = 0; double animationY = 0; jngl::Color color; double flashAnimation; + jngl::Sprite sprite{ "gfx/block" }; }; diff --git a/src/Field.cpp b/src/Field.cpp index 46397cf..06d3085 100644 --- a/src/Field.cpp +++ b/src/Field.cpp @@ -1,375 +1,373 @@ #include "Field.hpp" #include <algorithm> #include <jngl.hpp> #include <map> #include <set> const int Field::width_ = 11; const int Field::height_ = 19; Field::Field(int seed, const int level, const uint32_t startJunks) : blockSize_(60), counter_(0), gameOver_(false), score_(0), level_(level), lines(0), maxY(0), pause_(false), control_(new Control{ std::make_shared<KeyboardControl>(), std::make_shared<GamepadControl>(0) }), randomSeed(seed), linesCleared(0) { random.seed(seed); NewTetromino(); NewTetromino(); score_ = 0; std::mt19937 colorRandom; std::uniform_int_distribution<int> colorDist(0, 255); for (unsigned int i = 0; i < startJunks; ++i) { int leaveOut = random() % (width_ - 1); for (int x = 0; x < width_; ++x) { if (x != leaveOut) { jngl::Color color(colorDist(colorRandom), colorDist(colorRandom), colorDist(colorRandom)); AddBlock(Block(x, i, color)); } } } } void Field::addJunk(int nr) { for (int i = 0; i < nr; ++i) { control_->addJunk(); } } double Field::getSecondsPlayed() const { return secondsPlayed; } void Field::ResetCounter() { counter_ = static_cast<int>(200 / (level_ * 1.5 + 1)); } void Field::step() { if (desyncInfo) { desyncInfo->step(); if (!checkDesync()) { desyncInfo = std::nullopt; } return; } if (pause_) { return; } if (checkDesync && checkDesync()) { // is our opponent having network issues? desyncInfo = DesyncInfo(onUserQuitCallback); } else { if (!control_->step()) { ++stepsWithoutPackage; return; } } if (gameOver_) { --counter_; if (counter_ <= 0 && !blocks_.empty()) { counter_ = 5; std::vector<Block>::iterator randomBlock = blocks_.size() == 1 ? blocks_.begin() : (blocks_.begin() + (random() % (blocks_.size() - 1))); explosions_.push_back(Explosion(*randomBlock, 1)); blocks_.erase(randomBlock); } } else { --counter_; stepsWithoutPackage = 0; secondsPlayed += 1. / double(jngl::getStepsPerSecond()); linesCleared = 0; if (counter_ <= 0) { ResetCounter(); if (!tetromino_->MoveDown()) { if (delay_) { NewTetromino(); delay_ = false; } else { counter_ = 30; // Wait 0.3 seconds so that it's possible to move blocks // below others delay_ = true; } } else { delay_ = false; } } tetromino_->Step(); if (control_->Check(ControlType::Drop)) { tetromino_->drop(); NewTetromino(); } if (control_->Check(ControlType::Down)) { if (downKeyReleased_ && counter_ > 7) { counter_ = 7; } } else { downKeyReleased_ = true; } if (control_->Check(ControlType::AddJunk)) { for (auto& block : blocks_) { block.setY(block.getY() + 1); block.setAnimationY(block.getAnimationY() - 1); } if (tetromino_) { tetromino_->moveUp(1); } std::mt19937 colorRandom; std::uniform_int_distribution<int> colorDist(0, 255); int leaveOut = random() % (width_ - 1); for (int x = 0; x < width_; ++x) { if (x != leaveOut) { jngl::Color color(colorDist(colorRandom), colorDist(colorRandom), colorDist(colorRandom)); Block block(x, 0, color); block.setAnimationY(-1); AddBlock(block); } } } } for (auto& b : blocks_) { b.step(); } if ((level_ + 1) * 10 <= lines) { ++level_; } for (auto& e : explosions_) { e.Step(); } explosions_.erase(std::remove_if(explosions_.begin(), explosions_.end(), [](const Explosion& e) { return e.isFinished(); }), explosions_.end()); } void Field::CheckLines() { std::set<int> linesToRemove; // We need to sort the lines so that they are removed from top to bottom std::map<int, int> blocksInLine; for (const auto& block : blocks_) { if (++blocksInLine[block.getY()] == width_) { linesToRemove.insert(block.getY()); } } linesCleared = linesToRemove.size(); score_ += linesCleared * linesCleared * (level_ + 1) * (level_ + 1); // Remove lines from top to bottom so that explosions will be placed correctly auto rend = linesToRemove.rend(); for (auto it = linesToRemove.rbegin(); it != rend; ++it) { removeLine(*it, static_cast<int>(linesToRemove.size())); } } void Field::NewTetromino() { downKeyReleased_ = false; ResetCounter(); score_ += level_; if (tetromino_) { tetromino_->AttachToField(); CheckLines(); } tetromino_ = nextTetromino_; nextTetromino_.reset(new Tetromino(random() % 7, *this)); if (tetromino_) { const int xPositions[] = { 5, 6, 4, 7, 3, 8, 2, 9, 1, 10, 0 }; for (int xPosition : xPositions) { tetromino_->SetX(xPosition); if (!tetromino_->Collided()) { return; } } tetromino_->SetX(xPositions[0]); gameOver_ = true; nextTetromino_ = tetromino_; counter_ = 10; } } bool Field::GameOver() const { return gameOver_; } jngl::Vec2 Field::indexToPixel(const double x, const double y) const { return { -double(width_ * blockSize_) / 2.0 + (x + 0.5) * blockSize_, height_ * blockSize_ - y * blockSize_ - 600 }; } double Field::getBottomY() const { return height_ * blockSize_; } int Field::GetNextPosition() const { int nextPosition = 300 - (maxY - 4) * blockSize_; if (nextPosition > 300) { return 300; } if (nextPosition < -425) { return -425; } return nextPosition; } void Field::drawNextTetromino() const { jngl::print("Next:", -100, -75); jngl::pushMatrix(); jngl::translate(0, 600); nextTetromino_->draw(false); jngl::popMatrix(); } void Field::draw() const { bg.draw(); if (stepsWithoutPackage > 480) { jngl::setFontColor(0x000000_rgb); jngl::print(std::string((stepsWithoutPackage / 20) % 4, '.'), { -60, -100 }); return; } if (desyncInfo && desyncInfo->getStepsAlive() > 0.5 * jngl::getStepsPerSecond()) { desyncInfo->draw(); } else if (!pause_) { if (!gameOver_) { tetromino_->drawShadow(); } - jngl::pushMatrix(); - jngl::translate(indexToPixel(0, 0)); + auto mv = jngl::modelview().translate(indexToPixel(0, 0)); - std::vector<Block>::const_iterator end = blocks_.end(); - for (std::vector<Block>::const_iterator it = blocks_.begin(); it != end; ++it) { + auto end = blocks_.end(); + for (auto it = blocks_.begin(); it != end; ++it) { it->setSpriteColor(); - it->draw(); + it->draw(mv); } jngl::setSpriteColor(255, 255, 255); - std::vector<Explosion>::const_iterator end2 = explosions_.end(); - for (std::vector<Explosion>::const_iterator it = explosions_.begin(); it != end2; ++it) { - it->Draw(); + auto end2 = explosions_.end(); + for (auto it = explosions_.begin(); it != end2; ++it) { + it->draw(mv); } - jngl::popMatrix(); if (!gameOver_) { tetromino_->draw(true); } } } Block* Field::getBlock(int x, int y) { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (x == it->getX() && y == it->getY()) { return &(*it); } } return nullptr; } bool Field::checkCollision(const int x, const int y) const { if (x < 0 || x >= width_ || y < 0) { return true; } auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (x == it->getX() && y == it->getY()) { return true; } } return false; } void Field::AddBlock(const Block& block) { blocks_.push_back(block); if (blocks_.back().getY() > maxY) { maxY = blocks_.back().getY(); } // Copy the current animation for (const auto& block : blocks_) { if (block.getAnimationY() > 0.0001 || block.getAnimationY() < -0.0001) { blocks_.back().setAnimationY(block.getAnimationY()); } } } int Field::getBlockSize() const { return blockSize_; } void Field::removeLine(const int y, const int numberOfLines) { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (it->getY() == y) { explosions_.push_back(Explosion(*it, numberOfLines)); blocks_.erase(it); return removeLine(y, numberOfLines); } } for (auto it = blocks_.begin(); it != end; ++it) { if (it->getY() > y) { it->setY(it->getY() - 1); it->setAnimationY(it->getAnimationY() + 1); } } ++lines; --maxY; } int Field::GetScore() const { return score_; } int Field::GetLines() const { return lines; } int Field::GetLevel() const { return level_; } void Field::SetPause(bool pause) { pause_ = pause; jngl::setMouseVisible(pause); } bool Field::desync() const { return control_->desync(); } void Field::setCheckDesync(std::function<bool()> checkDesync) { this->checkDesync = std::move(checkDesync); } void Field::onUserQuit(std::function<void()> onUserQuitCallback) { this->onUserQuitCallback = std::move(onUserQuitCallback); } bool Field::GameOverAnimationFinished() const { return blocks_.empty(); } void Field::setGameOver(bool gameOver) { gameOver_ = gameOver; } void Field::setControl(Control* control) { control_.reset(control); } Control& Field::getControl() const { return *control_; } unsigned int Field::getRandom() { return random(); } int Field::getRandomSeed() const { return randomSeed; } int Field::getLinesCleared() const { return linesCleared; } diff --git a/src/explosion.cpp b/src/explosion.cpp index d83977c..ebf6dbd 100644 --- a/src/explosion.cpp +++ b/src/explosion.cpp @@ -1,27 +1,26 @@ #include "explosion.hpp" #include <jngl.hpp> Explosion::Explosion(const Block& block, const int numberOfLines) : block_(block), countdown_(255), numberOfLines_(numberOfLines), sprite(std::string("gfx/") + (numberOfLines == 4 ? "explosion4" : "explosion")) { } void Explosion::Step() { countdown_ -= 5; } bool Explosion::isFinished() const { return countdown_ < 0; } -void Explosion::Draw() const { - jngl::setSpriteAlpha(countdown_); +void Explosion::draw(jngl::Mat3 modelview) const { sprite.draw( - jngl::modelview() + modelview .translate({ double(block_.getX() * block_.getSize()), -(block_.getY() - double(255 - countdown_) / 510 * numberOfLines_) * block_.getSize() }) - .scale(float(510 - countdown_) / 510)); - jngl::setSpriteAlpha(255); + .scale(float(510 - countdown_) / 510), + jngl::Alpha::u8(countdown_)); } diff --git a/src/explosion.hpp b/src/explosion.hpp index f8bc5e7..1eab42c 100644 --- a/src/explosion.hpp +++ b/src/explosion.hpp @@ -1,18 +1,18 @@ #pragma once #include "Block.hpp" #include <jngl/Sprite.hpp> class Explosion { public: Explosion(const Block&, int numberOfLines); void Step(); - void Draw() const; + void draw(jngl::Mat3 modelview) const; bool isFinished() const; private: Block block_; int countdown_; int numberOfLines_; jngl::Sprite sprite; }; diff --git a/src/tetromino.cpp b/src/tetromino.cpp index 073ec99..7d25a1e 100644 --- a/src/tetromino.cpp +++ b/src/tetromino.cpp @@ -1,303 +1,313 @@ #include "tetromino.hpp" #include "Field.hpp" Tetromino::Tetromino(int type, Field& field) : field_(field), shadow(jngl::ScaleablePixels(6 * Block::size), jngl::ScaleablePixels(6 * Block::size)) { assert(0 <= type && type < 7); - switch(type) { - case 0:{ + switch (type) { + case 0: { jngl::Color color(200, 200, 0); blocks_.push_back(Block(-1, 1, color)); // XX - blocks_.push_back(Block( 0, 1, color)); // XX + blocks_.push_back(Block(0, 1, color)); // XX blocks_.push_back(Block(-1, 0, color)); - blocks_.push_back(Block( 0, 0, color)); + blocks_.push_back(Block(0, 0, color)); rotationCenterX_.push_back(-0.5); - rotationCenterY_.push_back( 0.5); - break;} - case 1:{ + rotationCenterY_.push_back(0.5); + break; + } + case 1: { jngl::Color color(200, 0, 0); blocks_.push_back(Block(-1, 0, color)); // 1234 - blocks_.push_back(Block( 0, 0, color)); - blocks_.push_back(Block( 1, 0, color)); - blocks_.push_back(Block( 2, 0, color)); - rotationCenterX_.push_back( 0); - rotationCenterY_.push_back( 0); - rotationCenterX_.push_back( 0.5); + blocks_.push_back(Block(0, 0, color)); + blocks_.push_back(Block(1, 0, color)); + blocks_.push_back(Block(2, 0, color)); + rotationCenterX_.push_back(0); + rotationCenterY_.push_back(0); + rotationCenterX_.push_back(0.5); rotationCenterY_.push_back(-0.5); - break;} - case 2:{ + break; + } + case 2: { jngl::Color color(0, 200, 200); - blocks_.push_back(Block( 0, 1, color)); // 1 + blocks_.push_back(Block(0, 1, color)); // 1 blocks_.push_back(Block(-1, 0, color)); // 234 - blocks_.push_back(Block( 0, 0, color)); - blocks_.push_back(Block( 1, 0, color)); + blocks_.push_back(Block(0, 0, color)); + blocks_.push_back(Block(1, 0, color)); rotationCenterX_.push_back(-0.5); - rotationCenterY_.push_back( 0.5); - rotationCenterX_.push_back( 0); - rotationCenterY_.push_back( 0); - break;} - case 3:{ + rotationCenterY_.push_back(0.5); + rotationCenterX_.push_back(0); + rotationCenterY_.push_back(0); + break; + } + case 3: { jngl::Color color(0, 0, 200); - blocks_.push_back(Block( 0, 1, color)); // 1 - blocks_.push_back(Block( 0, 0, color)); // 2 - blocks_.push_back(Block( 0, -1, color)); // 43 + blocks_.push_back(Block(0, 1, color)); // 1 + blocks_.push_back(Block(0, 0, color)); // 2 + blocks_.push_back(Block(0, -1, color)); // 43 blocks_.push_back(Block(-1, -1, color)); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); - rotationCenterY_.push_back( 0.5); - break;} - case 4:{ + rotationCenterY_.push_back(0.5); + break; + } + case 4: { jngl::Color color(200, 100, 0); - blocks_.push_back(Block(-1, 1, color)); // 12 - blocks_.push_back(Block( 0, 1, color)); // 3 - blocks_.push_back(Block( 0, 0, color)); // 4 - blocks_.push_back(Block( 0, -1, color)); + blocks_.push_back(Block(-1, 1, color)); // 12 + blocks_.push_back(Block(0, 1, color)); // 3 + blocks_.push_back(Block(0, 0, color)); // 4 + blocks_.push_back(Block(0, -1, color)); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); - rotationCenterY_.push_back( 0.5); - break;} - case 5:{ + rotationCenterY_.push_back(0.5); + break; + } + case 5: { jngl::Color color(200, 0, 200); - blocks_.push_back(Block( 0, 1, color)); // 12 - blocks_.push_back(Block( 1, 1, color)); // 34 + blocks_.push_back(Block(0, 1, color)); // 12 + blocks_.push_back(Block(1, 1, color)); // 34 blocks_.push_back(Block(-1, 0, color)); - blocks_.push_back(Block( 0, 0, color)); + blocks_.push_back(Block(0, 0, color)); rotationCenterX_.push_back(-0.5); - rotationCenterY_.push_back( 0.5); - rotationCenterX_.push_back( 0); - rotationCenterY_.push_back( 0); - break;} - case 6:{ + rotationCenterY_.push_back(0.5); + rotationCenterX_.push_back(0); + rotationCenterY_.push_back(0); + break; + } + case 6: { jngl::Color color(0, 200, 0); blocks_.push_back(Block(-1, 1, color)); // 12 - blocks_.push_back(Block( 0, 1, color)); // 34 - blocks_.push_back(Block( 0, 0, color)); - blocks_.push_back(Block( 1, 0, color)); + blocks_.push_back(Block(0, 1, color)); // 34 + blocks_.push_back(Block(0, 0, color)); + blocks_.push_back(Block(1, 0, color)); rotationCenterX_.push_back(-0.5); - rotationCenterY_.push_back( 0.5); - rotationCenterX_.push_back( 0); - rotationCenterY_.push_back( 0); - break;} + rotationCenterY_.push_back(0.5); + rotationCenterX_.push_back(0); + rotationCenterY_.push_back(0); + break; + } } int numberOfRotations = field_.getRandom() % 4; for (int i = 0; i < numberOfRotations; ++i) { Rotate(CLOCKWISE, true); } animationX_ = animationY_ = rotation_ = 0; // Clear animation set by Rotate(CLOCKWISE) x_ = 5; y_ = 17; } void Tetromino::Step() { animationX_ *= 0.7; animationY_ *= 0.8; rotation_ *= 0.8; if (field_.getControl().Check(ControlType::Left)) { changeX(-1); if (Collided()) { changeX(1); } } if (field_.getControl().Check(ControlType::Right)) { changeX(1); if (Collided()) { changeX(-1); } } if (field_.getControl().Check(ControlType::Rotate)) { Rotate(CLOCKWISE, false); } if (field_.getControl().Check(ControlType::RotateCounter)) { Rotate(COUNTERCLOCKWISE, false); } } void Tetromino::SetX(const int x) { x_ = x; } void Tetromino::changeX(int c) { x_ += c; animationX_ -= c; } void Tetromino::changeY(int c) { y_ += c; animationY_ -= c; } void Tetromino::Rotate(const Direction direction, bool ignoreCollision) { // if ignoreCollision is true, we don't want to make any calls to Collided() bool collidedBeforeRotation = ignoreCollision || Collided(); auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (direction == CLOCKWISE) { it->rotate(direction, rotationCenterX_.front(), rotationCenterY_.front()); } else { it->rotate(direction, rotationCenterX_.back(), rotationCenterY_.back()); } } rotationCenterX_.push_back(rotationCenterX_.front()); rotationCenterX_.pop_front(); rotationCenterY_.push_back(rotationCenterY_.front()); rotationCenterY_.pop_front(); if (direction == CLOCKWISE) { rotation_ -= 90; } else { rotation_ += 90; } if (!collidedBeforeRotation && Collided()) { changeX(1); if (Collided()) { changeX(-2); if (Collided()) { changeX(3); if (Collided()) { changeX(-4); if (Collided()) { changeX(2); // Undo rotation if (direction == CLOCKWISE) { Rotate(COUNTERCLOCKWISE, true); } else { Rotate(CLOCKWISE, true); } } } } } } } void Tetromino::AttachToField() { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { it->setX(it->getX() + x_); it->setY(it->getY() + y_); it->setAnimationX(animationX_); it->setAnimationY(animationY_); it->flash(); field_.AddBlock(*it); } } bool Tetromino::MoveDown() { --y_; if (Collided()) { ++y_; return false; } animationY_ += 1; return true; } void Tetromino::moveUp(int amount) { y_ += amount; animationY_ -= amount; } void Tetromino::draw(bool withShadow) const { if (withShadow) { auto context = shadow.use(); jngl::translate(-Block::size / 2., -Block::size / 2.); context.clear(); jngl::setSpriteColor(0, 0, 0, 10); // 10 // at y == 310 no tetromino would be visible const double STEP_SIZE = 2; for (double y = 1; y < 310; y += STEP_SIZE) { jngl::translate(0, STEP_SIZE); - jngl::pushMatrix(); - drawBlocks(); - jngl::popMatrix(); + drawBlocks(jngl::modelview()); } jngl::setSpriteAlpha(255); } - jngl::pushMatrix(); - jngl::translate(field_.indexToPixel(x_ + animationX_, y_ + animationY_)); assert(!blocks_.empty()); blocks_.front().setSpriteColor(); - drawBlocks(); + drawBlocks( + jngl::modelview().translate({ field_.indexToPixel(x_ + animationX_, y_ + animationY_) })); jngl::setSpriteColor(255, 255, 255); - jngl::popMatrix(); } void Tetromino::drawShadow() const { jngl::pushMatrix(); const auto pos = field_.indexToPixel(x_ + animationX_, y_ + animationY_); jngl::translate(pos); jngl::translate(-Block::size * 2.5, -Block::size * 2.5); jngl::setSpriteAlpha(50); const float width = shadow.getSize().x; float height = shadow.getSize().y; float minV = 0; float extensionHeight = field_.getBottomY() - pos.y - height / 2.; if (extensionHeight < 0) { height += extensionHeight; minV = -extensionHeight / shadow.getSize().y; assert(minV >= 0 && minV <= 1); extensionHeight = 0; } shadow.drawMesh({ - // top right triangle - jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, - jngl::Vertex{ .x = width, .y = 0, .u = 1, .v = 1 }, - jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, + // top right triangle + jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, + jngl::Vertex{ .x = width, .y = 0, .u = 1, .v = 1 }, + jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, - // bottom left triangle - jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, - jngl::Vertex{ .x = 0, .y = height, .u = 0, .v = minV }, - jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, + // bottom left triangle + jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, + jngl::Vertex{ .x = 0, .y = height, .u = 0, .v = minV }, + jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, - // Now extend the end of the shadow (v == 0) to the bottom of the field: - // top right triangle - jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, - jngl::Vertex{ .x = width, .y = height + 0, .u = 1, .v = 0 }, - jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, + // Now extend the end of the shadow (v == 0) to the bottom of the field: + // top right triangle + jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, + jngl::Vertex{ .x = width, .y = height + 0, .u = 1, .v = 0 }, + jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, - // bottom left triangle - jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, - jngl::Vertex{ .x = 0, .y = height + extensionHeight, .u = 0, .v = 0 }, - jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, + // bottom left triangle + jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, + jngl::Vertex{ .x = 0, .y = height + extensionHeight, .u = 0, .v = 0 }, + jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, }); jngl::setSpriteAlpha(255); jngl::popMatrix(); } bool Tetromino::Collided() const { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (field_.checkCollision(x_ + it->getX(), y_ + it->getY())) { return true; } } return false; } void Tetromino::drop() { - while (MoveDown()); + while (MoveDown()) + ; animationX_ = animationY_ = 0; } -void Tetromino::drawBlocks() const { +void Tetromino::drawBlocks(jngl::Mat3 modelview) const { const int blockSize = field_.getBlockSize(); if (rotation_ < 0) { // Clockwise - jngl::translate( rotationCenterX_.back() * blockSize, -rotationCenterY_.back() * blockSize); - jngl::rotate(rotation_); - jngl::translate(-rotationCenterX_.back() * blockSize, rotationCenterY_.back() * blockSize); + modelview + .translate( + { rotationCenterX_.back() * blockSize, -rotationCenterY_.back() * blockSize }) + .rotate(rotation_ * std::numbers::pi / 180) + .translate( + { -rotationCenterX_.back() * blockSize, rotationCenterY_.back() * blockSize }); } else { - jngl::translate( rotationCenterX_.front() * blockSize, -rotationCenterY_.front() * blockSize); - jngl::rotate(rotation_); - jngl::translate(-rotationCenterX_.front() * blockSize, rotationCenterY_.front() * blockSize); + modelview + .translate( + { rotationCenterX_.front() * blockSize, -rotationCenterY_.front() * blockSize }) + .rotate(rotation_ * std::numbers::pi / 180) + .translate( + { -rotationCenterX_.front() * blockSize, rotationCenterY_.front() * blockSize }); } for (auto& block : blocks_) { - block.draw(); + block.draw(modelview); } } diff --git a/src/tetromino.hpp b/src/tetromino.hpp index 44db93f..7d4bda3 100644 --- a/src/tetromino.hpp +++ b/src/tetromino.hpp @@ -1,45 +1,45 @@ #pragma once #include "Block.hpp" #include <deque> #include <jngl.hpp> #include <vector> class Field; class Tetromino { public: Tetromino(int type, Field&); void Step(); void draw(bool withShadow) const; void drawShadow() const; bool Collided() const; bool MoveDown(); void moveUp(int amount); void AttachToField(); /// \a ignoreCollision is used when creating the Tetromino void Rotate(Direction, bool ignoreCollision); void RandomRotate(); void SetX(int); void drop(); private: - void drawBlocks() const; + void drawBlocks(jngl::Mat3 modelview) const; void changeX(int); void changeY(int); std::vector<Block> blocks_; Field& field_; int x_, y_; double animationX_ = 0; double animationY_ = 0; double rotation_; std::deque<int> positionTweaksX_; // These values help correctly rotate the tetromino because std::deque<int> positionTweaksY_; // in nearly all Tetris versions it isn't a real rotation. std::deque<double> rotationCenterX_; std::deque<double> rotationCenterY_; mutable jngl::FrameBuffer shadow; };
jhasse/jntetri
029ceaa601546b21e5f0a4dbbc4757a3e9e75ca3
Rename Input::SetPassword to setPassword
diff --git a/src/gui/input.cpp b/src/gui/input.cpp index 2df7f3a..ad83ca3 100644 --- a/src/gui/input.cpp +++ b/src/gui/input.cpp @@ -1,89 +1,89 @@ #include "input.hpp" #include <jngl.hpp> -Input::Input(int x, int y) : password_(false), displayCursor_(0) { +Input::Input(int x, int y) : displayCursor_(0) { setPos(x, y); } void Input::setMaxWidth(unsigned int width) { maxWidth = width; } -void Input::SetPassword(bool password) { - password_ = password; +void Input::setPassword(bool password) { + this->password = password; } void Input::onFocusChanged() { displayCursor_ = 50; } void Input::step() { const auto mousePos = jngl::getMousePos(); if (mousePos.x > position.x && mousePos.y > position.y && mousePos.x < position.x + maxWidth && mousePos.y < position.y + 94 /* TODO: Do not hardcode */) { jngl::setCursor(jngl::Cursor::I); if (jngl::mousePressed()) { setFocus(true); } } if (!sensitive || !focus) { return; } --displayCursor_; if (displayCursor_ < -35 || !jngl::getTextInput().empty()) { displayCursor_ = 35; } text += jngl::getTextInput(); if (jngl::keyPressed(jngl::key::BackSpace) && !text.empty()) { removeLastCharacter(); } while (jngl::getTextWidth(text) > maxWidth) { removeLastCharacter(); } } void Input::draw() const { std::string temp; - if (password_) { + if (password) { temp = text; size_t size = jngl::utf8Length(text); text.clear(); for (size_t i = 0; i < size; ++i) { text += "●"; } } if (sensitive) { jngl::setFontColor(0, 0, 0); } else { jngl::setFontColor(150, 150, 150); } if (focus && displayCursor_ > 0) { jngl::print(text + "|", static_cast<int>(std::lround(position.x)), static_cast<int>(std::lround(position.y))); } else { jngl::print(text, static_cast<int>(std::lround(position.x)), static_cast<int>(std::lround(position.y))); } - if (password_) { + if (password) { text = temp; } } std::string Input::getText() const { return text; } void Input::setText(const std::string& text) { this->text = text; } void Input::removeLastCharacter() { displayCursor_ = 50; auto it = text.end(); --it; while (*it & 0x80 && !(*it & 0x40)) { // Unicode character? --it; } text.erase(it, text.end()); } diff --git a/src/gui/input.hpp b/src/gui/input.hpp index ab8beb8..360e877 100644 --- a/src/gui/input.hpp +++ b/src/gui/input.hpp @@ -1,31 +1,31 @@ #pragma once #include "widget.hpp" #include <string> #include <vector> class Input : public Widget { public: Input(int x, int y); void step() override; void draw() const override; std::string getText() const; void setText(const std::string&); void setMaxWidth(unsigned int); - void SetPassword(bool); + void setPassword(bool); void onFocusChanged() override; private: void removeLastCharacter(); mutable std::string text; - bool password_; + bool password = false; int displayCursor_; unsigned int maxWidth = 999; }; diff --git a/src/multiplayermenu.cpp b/src/multiplayermenu.cpp index cb8ccd2..411519f 100644 --- a/src/multiplayermenu.cpp +++ b/src/multiplayermenu.cpp @@ -1,57 +1,57 @@ #include "multiplayermenu.hpp" #include "Login.hpp" #include "engine/Options.hpp" #include "engine/fade.hpp" #include "menu.hpp" #include <jngl.hpp> MultiplayerMenu::MultiplayerMenu(const bool quickLogin) : name_(new Input(50, -240)), password_(new Input(50, -100)), quickLogin(quickLogin) { addWidget(name_); addWidget(password_); login_.reset(new Button("Login", [this]() { OnLogin(); })); addWidget(login_); back_.reset(new Button("Back", [this]() { OnBack(); })); addWidget(back_); back_->setCenter(-350, 280); login_->setCenter(350, 280); - password_->SetPassword(true); + password_->setPassword(true); name_->setText(getOptions().lastLoginName); if (name_->getText() != "") { FocusNext(); } } void MultiplayerMenu::step() { StepWidgets(); if (jngl::keyPressed(jngl::key::Return) || quickLogin) { OnLogin(); quickLogin = false; // if an error happens we will be reactivated } } void MultiplayerMenu::draw() const { jngl::setFontColor(0, 0, 0); jngl::print("Name:", -500, -240); jngl::print("Password:", -500, -100); DrawWidgets(); } void MultiplayerMenu::OnBack() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void MultiplayerMenu::OnLogin() { jngl::setWork(std::make_shared<Login>( std::dynamic_pointer_cast<MultiplayerMenu>(jngl::getWork()), quickLogin)); } std::string MultiplayerMenu::GetName() const { return name_->getText(); } std::string MultiplayerMenu::GetPassword() const { return password_->getText(); }
jhasse/jntetri
eb4b7ca9a52956b7a6874e6b4af6d23607f8aa49
Use jngl::utf8Length() for password
diff --git a/src/gui/input.cpp b/src/gui/input.cpp index 97cc49c..2df7f3a 100644 --- a/src/gui/input.cpp +++ b/src/gui/input.cpp @@ -1,89 +1,89 @@ #include "input.hpp" #include <jngl.hpp> Input::Input(int x, int y) : password_(false), displayCursor_(0) { setPos(x, y); } void Input::setMaxWidth(unsigned int width) { maxWidth = width; } void Input::SetPassword(bool password) { password_ = password; } void Input::onFocusChanged() { displayCursor_ = 50; } void Input::step() { const auto mousePos = jngl::getMousePos(); if (mousePos.x > position.x && mousePos.y > position.y && mousePos.x < position.x + maxWidth && mousePos.y < position.y + 94 /* TODO: Do not hardcode */) { jngl::setCursor(jngl::Cursor::I); if (jngl::mousePressed()) { setFocus(true); } } if (!sensitive || !focus) { return; } --displayCursor_; if (displayCursor_ < -35 || !jngl::getTextInput().empty()) { displayCursor_ = 35; } text += jngl::getTextInput(); if (jngl::keyPressed(jngl::key::BackSpace) && !text.empty()) { removeLastCharacter(); } while (jngl::getTextWidth(text) > maxWidth) { removeLastCharacter(); } } void Input::draw() const { std::string temp; if (password_) { temp = text; - size_t size = text.size(); + size_t size = jngl::utf8Length(text); text.clear(); for (size_t i = 0; i < size; ++i) { text += "●"; } } if (sensitive) { jngl::setFontColor(0, 0, 0); } else { jngl::setFontColor(150, 150, 150); } if (focus && displayCursor_ > 0) { jngl::print(text + "|", static_cast<int>(std::lround(position.x)), static_cast<int>(std::lround(position.y))); } else { jngl::print(text, static_cast<int>(std::lround(position.x)), static_cast<int>(std::lround(position.y))); } if (password_) { text = temp; } } std::string Input::getText() const { return text; } void Input::setText(const std::string& text) { this->text = text; } void Input::removeLastCharacter() { displayCursor_ = 50; auto it = text.end(); --it; while (*it & 0x80 && !(*it & 0x40)) { // Unicode character? --it; } text.erase(it, text.end()); } diff --git a/subprojects/jngl b/subprojects/jngl index d03d8e8..2698481 160000 --- a/subprojects/jngl +++ b/subprojects/jngl @@ -1 +1 @@ -Subproject commit d03d8e8636aca9c4895788f7fbc19f184876346f +Subproject commit 269848144916cc86500521ed042b3315fb53e1dc
jhasse/jntetri
b44895f3e20286c0d3ff754fd210c790761f42d9
Use new modelview function in MessageBox
diff --git a/src/gui/MessageBox.cpp b/src/gui/MessageBox.cpp index 8ed8a68..57d2147 100644 --- a/src/gui/MessageBox.cpp +++ b/src/gui/MessageBox.cpp @@ -1,28 +1,27 @@ #include "MessageBox.hpp" #include "../fonts.hpp" #include <jngl.hpp> MessageBox::MessageBox(const std::string& message, std::shared_ptr<jngl::Work> nextWork) : text(message), nextWork(std::move(nextWork)) { auto ok = std::make_shared<Button>("OK", [this]() { jngl::setWork(this->nextWork); }); ok->setCenter(0, 100); addWidget(std::move(ok)); text.setFont(fonts::label()); text.setCenter(0, -100); } void MessageBox::step() { StepWidgets(); } void MessageBox::draw() const { nextWork->draw(); - jngl::setColor(255, 255, 255, 220); - jngl::drawRect(-jngl::getScreenWidth() / 2, -jngl::getScreenHeight() / 2, - jngl::getScreenWidth(), jngl::getScreenHeight()); + jngl::drawRect(jngl::modelview().translate(-jngl::getScreenSize() / 2), jngl::getScreenSize(), + jngl::Rgba::u8(255, 255, 255, 220)); jngl::setFontColor(0, 0, 0); text.draw(); DrawWidgets(); }
jhasse/jntetri
af830a30d30b4bf1e57dc1fc913c3d89f7cf1e4d
Use Widget::position instead of x_, y_
diff --git a/src/gui/input.cpp b/src/gui/input.cpp index 4a558c6..97cc49c 100644 --- a/src/gui/input.cpp +++ b/src/gui/input.cpp @@ -1,86 +1,89 @@ #include "input.hpp" #include <jngl.hpp> -Input::Input(int x, int y) : x_(x), y_(y), password_(false), displayCursor_(0) { +Input::Input(int x, int y) : password_(false), displayCursor_(0) { + setPos(x, y); } void Input::setMaxWidth(unsigned int width) { maxWidth = width; } void Input::SetPassword(bool password) { password_ = password; } void Input::onFocusChanged() { displayCursor_ = 50; } void Input::step() { const auto mousePos = jngl::getMousePos(); - if (mousePos.x > x_ && mousePos.y > y_ && mousePos.x < x_ + maxWidth && - mousePos.y < y_ + 94 /* TODO: Do not hardcode */) { + if (mousePos.x > position.x && mousePos.y > position.y && mousePos.x < position.x + maxWidth && + mousePos.y < position.y + 94 /* TODO: Do not hardcode */) { jngl::setCursor(jngl::Cursor::I); if (jngl::mousePressed()) { setFocus(true); } } if (!sensitive || !focus) { return; } --displayCursor_; if (displayCursor_ < -35 || !jngl::getTextInput().empty()) { displayCursor_ = 35; } text += jngl::getTextInput(); if (jngl::keyPressed(jngl::key::BackSpace) && !text.empty()) { removeLastCharacter(); } while (jngl::getTextWidth(text) > maxWidth) { removeLastCharacter(); } } void Input::draw() const { std::string temp; if (password_) { temp = text; size_t size = text.size(); text.clear(); for (size_t i = 0; i < size; ++i) { text += "●"; } } if (sensitive) { jngl::setFontColor(0, 0, 0); } else { jngl::setFontColor(150, 150, 150); } if (focus && displayCursor_ > 0) { - jngl::print(text + "|", x_, y_); + jngl::print(text + "|", static_cast<int>(std::lround(position.x)), + static_cast<int>(std::lround(position.y))); } else { - jngl::print(text, x_, y_); + jngl::print(text, static_cast<int>(std::lround(position.x)), + static_cast<int>(std::lround(position.y))); } if (password_) { text = temp; } } std::string Input::getText() const { return text; } void Input::setText(const std::string& text) { this->text = text; } void Input::removeLastCharacter() { displayCursor_ = 50; auto it = text.end(); --it; while (*it & 0x80 && !(*it & 0x40)) { // Unicode character? --it; } text.erase(it, text.end()); } diff --git a/src/gui/input.hpp b/src/gui/input.hpp index 3971560..ab8beb8 100644 --- a/src/gui/input.hpp +++ b/src/gui/input.hpp @@ -1,32 +1,31 @@ #pragma once #include "widget.hpp" #include <string> #include <vector> class Input : public Widget { public: Input(int x, int y); void step() override; void draw() const override; std::string getText() const; void setText(const std::string&); void setMaxWidth(unsigned int); void SetPassword(bool); void onFocusChanged() override; private: void removeLastCharacter(); mutable std::string text; - int x_, y_; bool password_; int displayCursor_; unsigned int maxWidth = 999; };
jhasse/jntetri
fb07a6d06df8a7fce71682373c27bb32509fce80
Support holding-to-repeat with Gamepad
diff --git a/src/control.cpp b/src/control.cpp index f1c880e..3270c6d 100644 --- a/src/control.cpp +++ b/src/control.cpp @@ -1,143 +1,168 @@ #include "control.hpp" #include <jngl/Controller.hpp> #include <jngl/input.hpp> ControlBase::~ControlBase() { } bool ControlBase::step(const std::function<void(ControlType)>& set) { if (junkToAdd > 0) { --junkToAdd; set(ControlType::AddJunk); } return true; } void ControlBase::addJunk() { ++junkToAdd; } bool ControlBase::desync() const { return false; } Control::Control(std::initializer_list<std::shared_ptr<ControlBase>> l) : controls(l) { } Control::~Control() = default; bool Control::Check(ControlType e) { return bits_.test(static_cast<size_t>(e)); } void Control::forEach(const std::function<void(ControlType)>& f) { for (size_t i = 0; i < bits_.size(); ++i) { if (bits_.test(i)) { f(static_cast<ControlType>(i)); } } } void Control::addJunk() { for (const auto& control : controls) { control->addJunk(); } } bool Control::desync() const { for (const auto& control : controls) { if (control->desync()) { return true; } } return false; } bool Control::step() { bits_.reset(); bool success = false; for (auto& control : controls) { if (control->step([&](ControlType e) { bits_.set(static_cast<size_t>(e)); })) { success = true; } } return success; } bool KeyboardControl::step(const std::function<void(ControlType)>& Set) { if (jngl::keyPressed(jngl::key::Space) || jngl::keyPressed(jngl::key::Return)) { Set(ControlType::Drop); } if (jngl::keyDown(jngl::key::Down) || jngl::keyDown('k')) { Set(ControlType::Down); } if (jngl::keyPressed(jngl::key::Left) || jngl::keyPressed('j')) { Set(ControlType::Left); } if (jngl::keyPressed(jngl::key::Right) || jngl::keyPressed('l')) { Set(ControlType::Right); } if (jngl::keyPressed(jngl::key::Up) || jngl::keyPressed('i')) { Set(ControlType::Rotate); } if (jngl::keyPressed(jngl::key::ControlR) || jngl::keyPressed(jngl::key::AltR)) { Set(ControlType::RotateCounter); } return ControlBase::step(Set); } bool GamepadControl::step(const std::function<void(ControlType)>& Set) { if (!controller) { return false; } if (controller->pressed(jngl::controller::A)) { Set(ControlType::Drop); } if (controller->down(jngl::controller::RightTrigger)) { Set(ControlType::Down); } + if (controller->pressed(jngl::controller::DpadLeft)) { + stepsDownLeft = 1; Set(ControlType::Left); } + if (controller->down(jngl::controller::DpadLeft)) { + if (stepsDownLeft > 0) { + ++stepsDownLeft; + if (stepsDownLeft > repeatThreshold && stepsDownLeft % repeatRate == 0) { + Set(ControlType::Left); + } + } + } else { + stepsDownLeft = 0; + } + if (controller->pressed(jngl::controller::DpadRight)) { + stepsDownRight = 1; Set(ControlType::Right); } + if (controller->down(jngl::controller::DpadRight)) { + if (stepsDownRight > 0) { + ++stepsDownRight; + if (stepsDownRight > repeatThreshold && stepsDownRight % repeatRate == 0) { + Set(ControlType::Right); + } + } + } else { + stepsDownRight = 0; + } + if (controller->pressed(jngl::controller::X)) { Set(ControlType::Rotate); } if (controller->pressed(jngl::controller::B)) { Set(ControlType::RotateCounter); } // Bastian's Nintendo Steuerung (modern) // if (controller->pressed(jngl::controller::DpadUp)) { // Set(ControlType::Drop); // } // if (controller->down(jngl::controller::RightTrigger)) { // Set(ControlType::Down); // } // if (controller->pressed(jngl::controller::DpadLeft)) { // Set(ControlType::Left); // } // if (controller->pressed(jngl::controller::DpadRight)) { // Set(ControlType::Right); // } // if (controller->down(jngl::controller::DpadDown)) { // Set(ControlType::Down); // } // if (controller->pressed(jngl::controller::A)) { // Set(ControlType::RotateCounter); // } // if (controller->pressed(jngl::controller::B)) { // Set(ControlType::Rotate); // } return ControlBase::step(Set); } GamepadControl::GamepadControl(const size_t number) { const auto controllers = jngl::getConnectedControllers(); if (controllers.size() > number) { controller = controllers[number]; } } diff --git a/src/control.hpp b/src/control.hpp index a5c547f..3d02585 100644 --- a/src/control.hpp +++ b/src/control.hpp @@ -1,64 +1,68 @@ #pragma once #include "ControlType.hpp" #include <bitset> #include <functional> #include <memory> #include <vector> namespace jngl { class Controller; } // namespace jngl class ControlBase { public: virtual ~ControlBase(); /// Returns false when no new commands are coming in (e.g. network issues). virtual bool step(const std::function<void(ControlType)>&); /// step should set ControlType::AddJunk in the next frame virtual void addJunk(); /// Network issues? virtual bool desync() const; protected: int junkToAdd = 0; }; class Control { public: Control(std::initializer_list<std::shared_ptr<ControlBase>>); virtual ~Control(); bool Check(ControlType); /// Returns false when no new commands are coming in (e.g. network issues). virtual bool step(); void forEach(const std::function<void(ControlType)>&); /// Calls ControlBase::addJunk. Only really relevant when using NetworkControl void addJunk(); bool desync() const; protected: std::bitset<static_cast<size_t>(ControlType::LastValue)> bits_; std::vector<std::shared_ptr<ControlBase>> controls; }; class KeyboardControl : public ControlBase { public: bool step(const std::function<void(ControlType)>&) override; }; class GamepadControl : public ControlBase { public: explicit GamepadControl(size_t number); bool step(const std::function<void(ControlType)>&) override; private: std::shared_ptr<jngl::Controller> controller; + int stepsDownLeft = 0; + int stepsDownRight = 0; + constexpr static int repeatThreshold = 16; + constexpr static int repeatRate = 3; };
jhasse/jntetri
0fe8f9ef8906de9860241423606620fe5a70cad5
Trying to fix flickering in multiplayer
diff --git a/src/Field.cpp b/src/Field.cpp index c8aaa87..46397cf 100644 --- a/src/Field.cpp +++ b/src/Field.cpp @@ -1,375 +1,375 @@ #include "Field.hpp" #include <algorithm> #include <jngl.hpp> #include <map> #include <set> const int Field::width_ = 11; const int Field::height_ = 19; Field::Field(int seed, const int level, const uint32_t startJunks) : blockSize_(60), counter_(0), gameOver_(false), score_(0), level_(level), lines(0), maxY(0), pause_(false), control_(new Control{ std::make_shared<KeyboardControl>(), std::make_shared<GamepadControl>(0) }), randomSeed(seed), linesCleared(0) { random.seed(seed); NewTetromino(); NewTetromino(); score_ = 0; std::mt19937 colorRandom; std::uniform_int_distribution<int> colorDist(0, 255); for (unsigned int i = 0; i < startJunks; ++i) { int leaveOut = random() % (width_ - 1); for (int x = 0; x < width_; ++x) { if (x != leaveOut) { jngl::Color color(colorDist(colorRandom), colorDist(colorRandom), colorDist(colorRandom)); AddBlock(Block(x, i, color)); } } } } void Field::addJunk(int nr) { for (int i = 0; i < nr; ++i) { control_->addJunk(); } } double Field::getSecondsPlayed() const { return secondsPlayed; } void Field::ResetCounter() { counter_ = static_cast<int>(200 / (level_ * 1.5 + 1)); } void Field::step() { if (desyncInfo) { desyncInfo->step(); if (!checkDesync()) { desyncInfo = std::nullopt; } return; } if (pause_) { return; } if (checkDesync && checkDesync()) { // is our opponent having network issues? desyncInfo = DesyncInfo(onUserQuitCallback); } else { if (!control_->step()) { ++stepsWithoutPackage; return; } } if (gameOver_) { --counter_; if (counter_ <= 0 && !blocks_.empty()) { counter_ = 5; std::vector<Block>::iterator randomBlock = blocks_.size() == 1 ? blocks_.begin() : (blocks_.begin() + (random() % (blocks_.size() - 1))); explosions_.push_back(Explosion(*randomBlock, 1)); blocks_.erase(randomBlock); } } else { --counter_; stepsWithoutPackage = 0; secondsPlayed += 1. / double(jngl::getStepsPerSecond()); linesCleared = 0; if (counter_ <= 0) { ResetCounter(); if (!tetromino_->MoveDown()) { if (delay_) { NewTetromino(); delay_ = false; } else { counter_ = 30; // Wait 0.3 seconds so that it's possible to move blocks // below others delay_ = true; } } else { delay_ = false; } } tetromino_->Step(); if (control_->Check(ControlType::Drop)) { tetromino_->drop(); NewTetromino(); } if (control_->Check(ControlType::Down)) { if (downKeyReleased_ && counter_ > 7) { counter_ = 7; } } else { downKeyReleased_ = true; } if (control_->Check(ControlType::AddJunk)) { for (auto& block : blocks_) { block.setY(block.getY() + 1); block.setAnimationY(block.getAnimationY() - 1); } if (tetromino_) { tetromino_->moveUp(1); } std::mt19937 colorRandom; std::uniform_int_distribution<int> colorDist(0, 255); int leaveOut = random() % (width_ - 1); for (int x = 0; x < width_; ++x) { if (x != leaveOut) { jngl::Color color(colorDist(colorRandom), colorDist(colorRandom), colorDist(colorRandom)); Block block(x, 0, color); block.setAnimationY(-1); AddBlock(block); } } } } for (auto& b : blocks_) { b.step(); } if ((level_ + 1) * 10 <= lines) { ++level_; } for (auto& e : explosions_) { e.Step(); } explosions_.erase(std::remove_if(explosions_.begin(), explosions_.end(), [](const Explosion& e) { return e.isFinished(); }), explosions_.end()); } void Field::CheckLines() { std::set<int> linesToRemove; // We need to sort the lines so that they are removed from top to bottom std::map<int, int> blocksInLine; for (const auto& block : blocks_) { if (++blocksInLine[block.getY()] == width_) { linesToRemove.insert(block.getY()); } } linesCleared = linesToRemove.size(); score_ += linesCleared * linesCleared * (level_ + 1) * (level_ + 1); // Remove lines from top to bottom so that explosions will be placed correctly auto rend = linesToRemove.rend(); for (auto it = linesToRemove.rbegin(); it != rend; ++it) { removeLine(*it, static_cast<int>(linesToRemove.size())); } } void Field::NewTetromino() { downKeyReleased_ = false; ResetCounter(); score_ += level_; if (tetromino_) { tetromino_->AttachToField(); CheckLines(); } tetromino_ = nextTetromino_; nextTetromino_.reset(new Tetromino(random() % 7, *this)); if (tetromino_) { const int xPositions[] = { 5, 6, 4, 7, 3, 8, 2, 9, 1, 10, 0 }; for (int xPosition : xPositions) { tetromino_->SetX(xPosition); if (!tetromino_->Collided()) { return; } } tetromino_->SetX(xPositions[0]); gameOver_ = true; nextTetromino_ = tetromino_; counter_ = 10; } } bool Field::GameOver() const { return gameOver_; } jngl::Vec2 Field::indexToPixel(const double x, const double y) const { return { -double(width_ * blockSize_) / 2.0 + (x + 0.5) * blockSize_, height_ * blockSize_ - y * blockSize_ - 600 }; } double Field::getBottomY() const { return height_ * blockSize_; } int Field::GetNextPosition() const { int nextPosition = 300 - (maxY - 4) * blockSize_; if (nextPosition > 300) { return 300; } if (nextPosition < -425) { return -425; } return nextPosition; } void Field::drawNextTetromino() const { jngl::print("Next:", -100, -75); jngl::pushMatrix(); jngl::translate(0, 600); nextTetromino_->draw(false); jngl::popMatrix(); } void Field::draw() const { bg.draw(); - if (stepsWithoutPackage > 0) { + if (stepsWithoutPackage > 480) { jngl::setFontColor(0x000000_rgb); jngl::print(std::string((stepsWithoutPackage / 20) % 4, '.'), { -60, -100 }); return; } if (desyncInfo && desyncInfo->getStepsAlive() > 0.5 * jngl::getStepsPerSecond()) { desyncInfo->draw(); } else if (!pause_) { if (!gameOver_) { tetromino_->drawShadow(); } jngl::pushMatrix(); jngl::translate(indexToPixel(0, 0)); std::vector<Block>::const_iterator end = blocks_.end(); for (std::vector<Block>::const_iterator it = blocks_.begin(); it != end; ++it) { it->setSpriteColor(); it->draw(); } jngl::setSpriteColor(255, 255, 255); std::vector<Explosion>::const_iterator end2 = explosions_.end(); for (std::vector<Explosion>::const_iterator it = explosions_.begin(); it != end2; ++it) { it->Draw(); } jngl::popMatrix(); if (!gameOver_) { tetromino_->draw(true); } } } Block* Field::getBlock(int x, int y) { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (x == it->getX() && y == it->getY()) { return &(*it); } } return nullptr; } bool Field::checkCollision(const int x, const int y) const { if (x < 0 || x >= width_ || y < 0) { return true; } auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (x == it->getX() && y == it->getY()) { return true; } } return false; } void Field::AddBlock(const Block& block) { blocks_.push_back(block); if (blocks_.back().getY() > maxY) { maxY = blocks_.back().getY(); } // Copy the current animation for (const auto& block : blocks_) { if (block.getAnimationY() > 0.0001 || block.getAnimationY() < -0.0001) { blocks_.back().setAnimationY(block.getAnimationY()); } } } int Field::getBlockSize() const { return blockSize_; } void Field::removeLine(const int y, const int numberOfLines) { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (it->getY() == y) { explosions_.push_back(Explosion(*it, numberOfLines)); blocks_.erase(it); return removeLine(y, numberOfLines); } } for (auto it = blocks_.begin(); it != end; ++it) { if (it->getY() > y) { it->setY(it->getY() - 1); it->setAnimationY(it->getAnimationY() + 1); } } ++lines; --maxY; } int Field::GetScore() const { return score_; } int Field::GetLines() const { return lines; } int Field::GetLevel() const { return level_; } void Field::SetPause(bool pause) { pause_ = pause; jngl::setMouseVisible(pause); } bool Field::desync() const { return control_->desync(); } void Field::setCheckDesync(std::function<bool()> checkDesync) { this->checkDesync = std::move(checkDesync); } void Field::onUserQuit(std::function<void()> onUserQuitCallback) { this->onUserQuitCallback = std::move(onUserQuitCallback); } bool Field::GameOverAnimationFinished() const { return blocks_.empty(); } void Field::setGameOver(bool gameOver) { gameOver_ = gameOver; } void Field::setControl(Control* control) { control_.reset(control); } Control& Field::getControl() const { return *control_; } unsigned int Field::getRandom() { return random(); } int Field::getRandomSeed() const { return randomSeed; } int Field::getLinesCleared() const { return linesCleared; }
jhasse/jntetri
2b8c8623e7f4a369d4623f411ad3d61453d9b180
Rename Game::setRotateScreen
diff --git a/src/Game.cpp b/src/Game.cpp index b3d75dd..4ef4281 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -1,137 +1,137 @@ #include "Game.hpp" #include "ReplayRecorder.hpp" #include "engine/Options.hpp" #include "gameoverscreen.hpp" #include "pausemenu.hpp" #include <iomanip> #include <jngl.hpp> #include <sstream> Game::Game(const GameType type, const int seed, const bool replay) : field_(seed, getOptions().startLevel, getOptions().startJunks), type_(type), nextPosition_(field_.GetNextPosition()), oldNextPosition_(nextPosition_), rotateScreen_(false), rotateDegree_(0) { if (!replay) { // Don't record when we're playing back a replay replayRecorder = std::make_unique<ReplayRecorder>(field_, type); } jngl::setMouseVisible(false); } Game::~Game() { jngl::setMouseVisible(true); } -void Game::SetRotateScreen(bool rotateScreen) { +void Game::setRotateScreen(bool rotateScreen) { rotateScreen_ = rotateScreen; } void Game::step() { StepToRotateScreen(); if (field_.GameOver()) { pauseTime_ = jngl::getTime(); jngl::setWork(std::make_shared<GameOverScreen>(this)); } else { field_.step(); if (replayRecorder) { replayRecorder->Step(); } if (type_ == GameType::FIFTYLINES && field_.GetLines() >= 50) { field_.setGameOver(true); } } nextPosition_ = field_.GetNextPosition(); oldNextPosition_ = (nextPosition_ - oldNextPosition_) * 0.01 + oldNextPosition_; if (pauseTime_ > 0.0001 && !field_.GameOver()) { pauseTime_ = 0; } if (jngl::keyPressed('p')) { onQuitEvent(); // Pause } } void Game::onQuitEvent() { static double lastPauseTime = 0; if (jngl::getTime() - lastPauseTime > 1) { // Don't allow pausing the game more then one time per second lastPauseTime = pauseTime_ = jngl::getTime(); field_.SetPause(true); jngl::setWork(std::make_shared<PauseMenu>(shared_from_this())); jngl::cancelQuit(); } } void Game::DrawTime(const int x, const int y) const { jngl::print("Time: ", x, y); double time = GetTime(); int minutes = int(time / 60); int seconds = int(time - minutes * 60); std::stringstream sstream; sstream.fill('0'); sstream << minutes << ":" << std::setw(2) << seconds; jngl::print(sstream.str(), 450, y + 100); } void Game::StepToRotateScreen() { if (rotateScreen_ && rotateDegree_ < 90) { rotateDegree_ += (90 - rotateDegree_) * 0.05; } else { rotateDegree_ *= 0.95; } } void Game::draw() const { jngl::pushMatrix(); jngl::rotate(rotateDegree_); jngl::scale(1 + rotateDegree_ / 270); field_.draw(); if (!rotateScreen_) { jngl::setFontColor(0, 0, 0); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(-600, oldNextPosition_); field_.drawNextTetromino(); jngl::popMatrix(); if (type_ == GameType::FIFTYLINES) { DrawTime(450, -500); } else { jngl::print("Score: ", 450, -500); jngl::print(std::to_string(field_.GetScore()), 450, -400); DrawTime(450, 220); } jngl::print("Level: ", 450, -260); jngl::print(std::to_string(field_.GetLevel()), 450, -160); jngl::print("Lines: ", 450, -20); jngl::print(std::to_string(field_.GetLines()), 450, 80); } jngl::popMatrix(); } Field& Game::GetField() { return field_; } double Game::GetTime() const { return field_.getSecondsPlayed(); } bool Game::GameOverAnimationFinished() const { return field_.GameOverAnimationFinished(); } GameType Game::getType() const { return type_; } bool Game::gameOver() const { return field_.GameOver(); } bool Game::isReplay() const { return replayRecorder == nullptr; } void Game::onLoad() { field_.SetPause(false); } diff --git a/src/Game.hpp b/src/Game.hpp index 9369f58..0b1595d 100644 --- a/src/Game.hpp +++ b/src/Game.hpp @@ -1,39 +1,39 @@ #pragma once #include "engine/work.hpp" #include "Field.hpp" #include "gametype.hpp" class ReplayRecorder; class Game : public Work, public std::enable_shared_from_this<Game> { public: Game(GameType, int seed, bool replay); ~Game() override; void step() override; void draw() const override; Field& GetField(); double GetTime() const; bool GameOverAnimationFinished() const; GameType getType() const; void DrawTime(int x, int y) const; void StepToRotateScreen(); - void SetRotateScreen(bool); + void setRotateScreen(bool); bool gameOver() const; bool isReplay() const; protected: void onQuitEvent() override; void onLoad() override; Field field_; GameType type_; double nextPosition_; double oldNextPosition_; double pauseTime_ = 0; bool rotateScreen_; double rotateDegree_; /// If we're owned by a ReplayPlayer, this is nullptr std::unique_ptr<ReplayRecorder> replayRecorder; }; diff --git a/src/pausemenu.cpp b/src/pausemenu.cpp index a56d274..c3a7769 100644 --- a/src/pausemenu.cpp +++ b/src/pausemenu.cpp @@ -1,42 +1,43 @@ #include "pausemenu.hpp" #include "Game.hpp" #include "engine/fade.hpp" #include "gui/ButtonBox.hpp" #include "menu.hpp" PauseMenu::PauseMenu(std::shared_ptr<Game> game) : work(jngl::getWork()), buttonBox(new ButtonBox), game(std::move(game)) { - this->game->SetRotateScreen(false); // Don't rotate the screen so that the buttons work correctly + this->game->setRotateScreen( + false); // Don't rotate the screen so that the buttons work correctly buttonBox->add("Resume", [this] { Continue(); }); buttonBox->add("Menu", [this] { QuitToMenu(); }); if (jngl::canQuit()) { buttonBox->add("Quit", jngl::quit); } addWidget(buttonBox); } void PauseMenu::step() { if (jngl::keyPressed(jngl::key::Escape)) { jngl::setWork(work); } StepWidgets(); game->StepToRotateScreen(); } void PauseMenu::Continue() { jngl::setWork(work); } void PauseMenu::draw() const { game->draw(); DrawWidgets(); } void PauseMenu::QuitToMenu() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void PauseMenu::onQuitEvent() { // Do Nothing }
jhasse/jntetri
34a5bae5ccf276955629b99adc2b4b08ac2acbc4
Use JNGL instead of spdlog
diff --git a/CMakeLists.txt b/CMakeLists.txt index 55b21b7..55f99b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,64 +1,59 @@ cmake_minimum_required(VERSION 3.15) project(jntetri) if(NOT MSVC) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=implicit-function-declaration") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color -Wall -Wextra -Winit-self -Wpedantic -Wdelete-non-virtual-dtor") # -Wno-implicit-fallthrough', # cereal # -Wno-class-memaccess', # cereal") endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") set(USE_FLAGS "-s USE_SDL=2 -pthread -s USE_PTHREADS=1 -s USE_FREETYPE=1 -s USE_VORBIS=1 -s DISABLE_EXCEPTION_CATCHING=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${USE_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${USE_FLAGS}") string(APPEND CMAKE_EXE_LINKER_FLAGS " ${USE_FLAGS} -s WEBSOCKET_URL=wss://jntetri.boomshine.de -s ASSERTIONS=1 -s FULL_ES3=1 " "--pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/pre.js -lidbfs.js") set(CMAKE_EXECUTABLE_SUFFIX ".html") endif() if (TARGET_WASM) add_compile_options("SHELL:-s USE_PTHREADS") add_link_options("SHELL:-s USE_PTHREADS") endif() include(subprojects/jngl/cmake/CPM.cmake) CPMAddPackage( NAME nlohmann_json URL "https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz" ) include(FetchContent) -CPMAddPackage( - NAME spdlog - URL https://github.com/gabime/spdlog/archive/v1.13.0.tar.gz - URL_HASH SHA1=2042a47b2076cbdcd33e648b0df031cb03963097) - CPMAddPackage( NAME cereal URL https://github.com/USCiLab/cereal/archive/refs/tags/v1.3.2.tar.gz OPTIONS "SKIP_PORTABILITY_TEST ON" "JUST_INSTALL_CEREAL ON" ) add_subdirectory(subprojects/jngl) file(GLOB SRC src/*.cpp src/engine/*.cpp src/gui/*.cpp) add_executable(jntetri ${SRC}) # find_package(Boost COMPONENTS coroutine system thread) find_package(Boost REQUIRED) # find_package(Boost CONFIG REQUIRED) Can't get this to work with custom Boost (web) -target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json Boost::boost) +target_link_libraries(jntetri PRIVATE cereal jngl nlohmann_json::nlohmann_json Boost::boost) set_property(TARGET jntetri PROPERTY CXX_STANDARD 20) if(MSVC) target_compile_definitions(jntetri PRIVATE BOOST_ALL_NO_LIB _WIN32_WINNT=0x0601) elseif(WIN32) target_link_libraries(jntetri PRIVATE ws2_32) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") target_link_options(jntetri PRIVATE --preload-file data) endif() diff --git a/src/Login.cpp b/src/Login.cpp index 6c2093e..ddc4cfa 100644 --- a/src/Login.cpp +++ b/src/Login.cpp @@ -1,184 +1,183 @@ #include "Login.hpp" #include "../server/NetworkConstants.hpp" #include "engine/screen.hpp" #include "engine/fade.hpp" #include "engine/Options.hpp" #include "gui/Button.hpp" #include "lobby.hpp" #include <jngl.hpp> #include <boost/bind/bind.hpp> -#include <spdlog/spdlog.h> #ifdef __EMSCRIPTEN__ const std::string Login::server_("89.58.48.219"); // boomshine.de const int Login::port_ = 9999; #else // const std::string Login::server_("127.0.0.1"); const std::string Login::server_("89.58.48.219"); // boomshine.de // const std::string Login::server_("85.214.187.23"); // babynamensuche.de const int Login::port_ = 7070; #endif Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu, bool quickLogin) : menu(multiplayerMenu), text_("connecting ..."), cancel_("Cancel", [this]() { OnCancel(); }), socket_(new Socket), quickLogin(quickLogin) { - spdlog::info("Connecting to {}:{}", server_, port_); + jngl::info("Connecting to {}:{}", server_, port_); try { socket_->connect(server_, port_, [this]() { HandleConnect(); }); } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.setCenter(0, 200); } void Login::HandleConnect() { text_ = "sending ..."; - spdlog::info("Sending protocol version {}", PROTOCOL_VERSION); + jngl::info("Sending protocol version {}", PROTOCOL_VERSION); socket_->send(std::to_string(PROTOCOL_VERSION), [this]() { ProtocolCheck1(); }); } void Login::ProtocolCheck1() { text_ = "receiving ..."; - spdlog::info("Waiting for server accept connection"); + jngl::info("Waiting for server accept connection"); socket_->receive([this](json data) { ProtocolCheck2(std::move(data)); }); } void Login::ProtocolCheck2(json temp) { if (temp["type"] != "ok") { text_ = "Error: "; if (const std::string msg = temp["msg"]; !msg.empty()) { text_ += msg; } else { text_ += temp.dump(); } OnError(); } else { if (menu->GetName().empty()) { if (!menu->GetPassword().empty()) { text_ = "Name must not be empty!"; return OnError(); } socket_->send(json{ { "type", "login_anonymous" } }, [this]() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; }); } else { socket_->send(json{ { "type", "login" }, { "name", menu->GetName() }, { "password", menu->GetPassword() } }, [this]() { HandleLogin1(); }); } } } void Login::HandleLogin1() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; } void Login::HandleLogin2(json temp) { if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else if (temp["type"] == "unknown name") { text_ = "No user with this name found.\nDo you want to register yourself?"; cancel_.setCenter(-350, 280); cancel_.SetText("No"); Button* yes = new Button("Yes", boost::bind(&Login::Register, this)); yes->setCenter(350, 280); addWidget(std::shared_ptr<Widget>(yes)); } else if (temp["type"] == "wrong password") { text_ = "The password you've entered\nis wrong. Please try again."; OnError(); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::Register() { json j{ { "type", "register" }, { "name", menu->GetName() }, { "password", menu->GetPassword() } }; - spdlog::info("Sending: {}", j.dump()); + jngl::info("Sending: {}", j.dump()); socket_->send(j, boost::bind(&Login::HandleRegister1, this)); cancel_.setCenter(0, 200); cancel_.SetText("Cancel"); widgets_.clear(); // FIXME: Implement RemoveWidget function } void Login::HandleRegister1() { socket_->receive([this](json temp) { HandleRegister2(std::move(temp)); }); text_ = "please wait ..."; } void Login::HandleRegister2(json temp) { - spdlog::debug("HandleRegister2"); + jngl::debug("HandleRegister2"); if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::step() { try { if (socket_) { socket_->step(); } } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.step(); StepWidgets(); } void Login::GoToLobby(std::string username) { getOptions().lastLoginName = std::move(username); getOptions().Save(); jngl::setWork(std::make_shared<Fade>( std::make_shared<Lobby>(std::move(socket_), quickLogin))); } void Login::draw() const { menu->draw(); jngl::setColor(255, 255, 255, 220); jngl::drawRect(-jngl::getScreenWidth() / 2, -jngl::getScreenHeight() / 2, jngl::getScreenWidth(), jngl::getScreenHeight()); jngl::setFontColor(0, 0, 0); GetScreen().printCentered(text_, { 0, -150 }); cancel_.draw(); DrawWidgets(); } void Login::OnCancel() { jngl::setWork(menu); } void Login::OnError() { // hacked together algorithm to word wrap long error messages: size_t pos = 42; while (jngl::getTextWidth(text_) > jngl::getScreenWidth() && pos < text_.size()) { size_t i = pos; while (i > 0 && text_[i - 1] != ' ') { if (text_[i] == '\n') { i = pos; break; } --i; } text_.insert(text_.begin() + i, '\n'); pos += 42; } cancel_.SetText("OK"); cancel_.setFocus(true); } diff --git a/src/NetworkControl.cpp b/src/NetworkControl.cpp index a3c1f35..900cf50 100644 --- a/src/NetworkControl.cpp +++ b/src/NetworkControl.cpp @@ -1,115 +1,113 @@ #include "NetworkControl.hpp" #include "engine/socket.hpp" #include "gui/MessageBox.hpp" -#include "jngl/window.hpp" -#include "jngl/work.hpp" #include "lobby.hpp" #include "multiplayermenu.hpp" +#include <jngl.hpp> #include <nlohmann/json.hpp> -#include <spdlog/spdlog.h> NetworkControl::NetworkControl(std::shared_ptr<Socket> socket) : socket(std::move(socket)) { this->socket->receive([this](json buf) { handleReceive(std::move(buf)); }); } bool NetworkControl::step(const std::function<void(ControlType)>& set) { if (!sendQueue.empty() && !sendingInProgress) { sendingInProgress = true; nlohmann::json j = { { "type", "game" }, { "time", sendQueue.front().first }, { "control", sendQueue.front().second }, }; socket->send(j, [this]() { sendQueue.pop(); - // spdlog::info("sent package success. {} to go.", sendQueue.size()); + // jngl::info("sent package success. {} to go.", sendQueue.size()); sendingInProgress = false; }); } socket->step(); if (nullPackagesReceived < 1) { return false; } bool handledNullPackage = false; while ((time % BUFFER_LENGTH) == data.front().first) { if (data.front().second == ControlType::Null) { if (handledNullPackage) { break; // Don't skip ahead if there are no commands between two null packages } handledNullPackage = true; --nullPackagesReceived; } else { set(data.front().second); // execute command } data.pop(); if (data.empty()) { break; } } ++time; return true; } void NetworkControl::handleReceive(json j) { if (j["type"] == "game") { uint8_t time = j["time"].get<uint8_t>(); uint8_t control = j["control"].get<uint8_t>(); if (control >= static_cast<int>(ControlType::LastValue)) { - spdlog::error("invalid control type in package: {}", control); + jngl::error("invalid control type in package: {}", control); } else { if (control == static_cast<uint8_t>(ControlType::Null)) { - // spdlog::info("Null package received."); + // jngl::info("Null package received."); ++nullPackagesReceived; } data.push( std::pair<unsigned char, ControlType>(time, static_cast<ControlType>(control))); } } else if (j["type"] == "opponentQuit") { jngl::setWork<MessageBox>("Your opponent left.", std::make_shared<Lobby>(std::move(socket), false)); return; } else if (j["type"] == "disconnected") { jngl::setWork<MessageBox>("Your opponent disconnected.", std::make_shared<Lobby>(std::move(socket), false)); return; } else if (j["type"] == "error") { jngl::setWork<MessageBox>(j["msg"], std::make_shared<MultiplayerMenu>(false)); return; } else { - spdlog::error("Unknown package: {}", j.dump()); + jngl::error("Unknown package: {}", j.dump()); } socket->receive([this](json buf) { handleReceive(std::move(buf)); }); } void NetworkControl::stepSend(Control& control) { if (sendTime % BUFFER_LENGTH == 0) { sendQueue.push(std::pair<uint8_t, ControlType>(0, ControlType::Null)); } control.forEach([this](ControlType c) { sendQueue.push(std::pair<uint8_t, ControlType>(sendTime % BUFFER_LENGTH, c)); }); ++sendTime; } bool NetworkControl::desync() const { #ifndef NDEBUG std::stringstream sstream; sstream << "time: " << time << " sendTime: " << sendTime << " nullPackagesReceived: " << nullPackagesReceived << " sendQueue.size(): " << sendQueue.size(); jngl::setTitle(sstream.str()); #endif return std::abs(time - sendTime) > 1000; } void NetworkControl::sendQuit() { - socket->send(json{ { "type", "quit" } }, []() { spdlog::info("sent quit success."); }); + socket->send(json{ { "type", "quit" } }, []() { jngl::info("sent quit success."); }); } std::shared_ptr<Socket> NetworkControl::getSocket() { return socket; } diff --git a/src/engine/socket.cpp b/src/engine/socket.cpp index 2e83c96..fcc257a 100644 --- a/src/engine/socket.cpp +++ b/src/engine/socket.cpp @@ -1,80 +1,80 @@ #include "socket.hpp" #include "../../server/NetworkConstants.hpp" #include <boost/asio/co_spawn.hpp> -#include <spdlog/spdlog.h> +#include <jngl.hpp> Socket::Socket() : socket_(io_) { } void Socket::step() { io_.poll(); } void Socket::CallbackWrapper(const boost::system::error_code& err, std::function<void()> onSuccess) { if (err) { throw std::runtime_error("socket error"); } boost::asio::co_spawn(io_, [this]() -> boost::asio::awaitable<void> { while (true) { size_t pos = buffer.find('\n'); if (pos == std::string::npos) { std::array<char, 1024> receiveBuffer{}; size_t len = co_await socket_.async_receive(boost::asio::buffer(receiveBuffer), 0, boost::asio::use_awaitable); buffer.append(receiveBuffer.data(), len); continue; } auto package = buffer.substr(0, pos); - // spdlog::trace("received `{}`", package); + // jngl::trace("received `{}`", package); buffer = buffer.substr(pos + 1); onReceiveSuccess(json::parse(package)); } }, boost::asio::detached); onSuccess(); } void Socket::connect(const std::string& server, int port, std::function<void()> onSuccess) { using boost::asio::ip::tcp; #ifndef __EMSCRIPTEN__ auto resolver = std::make_shared<tcp::resolver>(io_); tcp::resolver::query query(server, "http"); resolver->async_resolve(query, [this, port, resolver, onSuccess](const boost::system::error_code& err, tcp::resolver::iterator endpointIterator) { if (err) { std::ostringstream sstream; sstream << "resolve error " << err.value() << " [" << err.category().name() << "]"; throw std::runtime_error(sstream.str()); } tcp::endpoint endpoint(endpointIterator->endpoint().address(), port); socket_.async_connect(endpoint, [this, onSuccess](const boost::system::error_code& err) { CallbackWrapper(err, onSuccess); }); }); #else tcp::endpoint endpoint(boost::asio::ip::address::from_string(server), port); socket_.async_connect(endpoint, [this, onSuccess](const boost::system::error_code& err) { CallbackWrapper(err, onSuccess); }); #endif } void Socket::send(const std::string& data, std::function<void()> onSuccess) { - spdlog::trace("sending {}", data); + jngl::trace("sending {}", data); auto buf = std::make_unique<std::string>(data + "\n"); auto mutableBuf = boost::asio::buffer(*buf); socket_.async_send(mutableBuf, [this, buf = std::move(buf), onSuccess = std::move(onSuccess)]( const boost::system::error_code& err, size_t) { CallbackWrapper(err, std::move(onSuccess)); }); } void Socket::send(const json& data, std::function<void()> onSuccess) { send(data.dump(), std::move(onSuccess)); } void Socket::receive(std::function<void(json)> onSuccess) { onReceiveSuccess = std::move(onSuccess); } diff --git a/src/lobby.cpp b/src/lobby.cpp index f5f5416..05b7d16 100644 --- a/src/lobby.cpp +++ b/src/lobby.cpp @@ -1,100 +1,101 @@ #include "lobby.hpp" #include "NetworkControl.hpp" #include "SplitScreen.hpp" #include "engine/fade.hpp" #include "gui/MessageBox.hpp" #include "multiplayermenu.hpp" #include <jngl.hpp> #include <nlohmann/json.hpp> -#include <spdlog/spdlog.h> Lobby::Lobby(std::shared_ptr<Socket> socket, bool quickLogin) : socket_(socket), chatText_(""), input_(new Input(-700, 500)) { logout_.reset(new Button("Logout", [this]() { OnLogout(); })); play_.reset(new Button("Play!™", [this]() { OnPlay(); })); startReceiving(); input_->setMaxWidth(2500); addWidget(input_); addWidget(logout_); addWidget(play_); logout_->setCenter(-450, -450); play_->setCenter(450, -450); if (quickLogin) { OnPlay(); } } void Lobby::OnLogout() { jngl::setWork(std::make_shared<Fade>(std::make_shared<MultiplayerMenu>(false))); } void Lobby::OnPlay() { play_->setSensitive(false); - socket_->send(json{ { "type", "play" } }, []() { spdlog::info("Successfully sent 'play'."); }); + socket_->send(json{ { "type", "play" } }, []() { jngl::info("Successfully sent 'play'."); }); } void Lobby::step() { try { socket_->step(); } catch (std::exception& e) { jngl::setWork(std::make_shared<Fade>( std::make_shared<MessageBox>(e.what(), std::make_shared<MultiplayerMenu>(false)))); } if (jngl::keyPressed(jngl::key::Return)) { nlohmann::json j = { { "type", "chat" }, { "text", input_->getText() }, }; - spdlog::debug("Sending: {}", j.dump()); + jngl::debug("Sending: {}", j.dump()); socket_->send(j, [this]() { OnMessageSent(); }); input_->setSensitive(false); } StepWidgets(); } void Lobby::OnMessageSent() { input_->setText(""); input_->setSensitive(true); } void Lobby::draw() const { jngl::setFontColor(0, 0, 0); jngl::setFontSize(35); jngl::print(chatText_, -700, -250); DrawWidgets(); } void Lobby::handleReceive(json buf) { if (buf["type"] == "chat") { chatText_ += buf["text"]; chatText_ += '\n'; int lineCount = 0; size_t pos = 0; while ((pos = chatText_.find_first_of("\n", pos + 1)) != std::string::npos) { ++lineCount; } if (lineCount > 13) { pos = chatText_.find_first_of("\n"); chatText_ = chatText_.substr(pos + 1); } } else if (buf["type"] == "play") { // Matchmaking was successful and an opponent found. Let's start the game. - spdlog::debug("Starting match making"); + jngl::debug("Starting match making"); auto control = std::make_shared<NetworkControl>(socket_); jngl::setWork(std::make_shared<Fade>( std::make_shared<SplitScreen>(control, buf["seed"].get<int32_t>()))); return; // move out of Lobby loop } else if (buf["type"] == "error") { jngl::setWork<MessageBox>(buf["msg"], std::make_shared<MultiplayerMenu>(false)); return; } else { - spdlog::warn("Received unknown type: {}", buf); + std::ostringstream tmp; + tmp << buf; + jngl::warn("Received unknown type: {}", tmp.str()); } startReceiving(); } void Lobby::startReceiving() { socket_->receive([this](json buf) { handleReceive(std::move(buf)); }); } diff --git a/src/main.cpp b/src/main.cpp index 8fe572a..9cc2d01 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,25 +1,21 @@ #include "Intro.hpp" #include "engine/debugoverlay.hpp" #include "constants.hpp" -#include <spdlog/spdlog.h> #include <jngl.hpp> #include <jngl/init.hpp> jngl::AppParameters jnglInit() { jngl::AppParameters params; -#ifndef NDEBUG - spdlog::set_level(spdlog::level::trace); -#endif params.displayName = programDisplayName; params.screenSize = { 1280, 720 }; params.start = []() { jngl::setAntiAliasing(true); jngl::setIcon("icon"); jngl::setFont("Inter-ExtraLight.ttf"); jngl::setFontSize(jngl::getScaleFactor() * 13); jngl::addJob(std::make_shared<DebugOverlay>()); return std::make_shared<Intro>(); }; return params; } diff --git a/subprojects/jngl b/subprojects/jngl index 6e17a89..a50a2b4 160000 --- a/subprojects/jngl +++ b/subprojects/jngl @@ -1 +1 @@ -Subproject commit 6e17a89f9df2d9d12703b4d2c8ef3d88bbf1e0ff +Subproject commit a50a2b4cad85e3c2e2b89bf45a6c1c8b74839b07
jhasse/jntetri
ad242db9195c982fa21f7022e2bb9b3233be4a4f
Simplify Fade
diff --git a/src/engine/fade.cpp b/src/engine/fade.cpp index 6a3fae8..0fcf477 100644 --- a/src/engine/fade.cpp +++ b/src/engine/fade.cpp @@ -1,42 +1,40 @@ #include "fade.hpp" #include <jngl.hpp> Fade::Fade(std::shared_ptr<Work> work, int speed) : work_(std::move(work)), oldWork_(jngl::getWork()), fadeCount_(0), speed_(speed) { } void Fade::step() { #ifdef NDEBUG const int maxAlpha = 255; #endif fadeCount_ += speed_; #ifdef NDEBUG if (fadeCount_ >= 2 * maxAlpha) // Finished? #endif { jngl::setWork(work_); } } void Fade::draw() const { const int maxAlpha = 255; if(fadeCount_ < maxAlpha) { if(!dynamic_cast<Fade*>(oldWork_.get())) { oldWork_->draw(); } } else { work_->draw(); } const int alpha = static_cast<int>(fadeCount_ > maxAlpha ? 2 * maxAlpha - fadeCount_ : fadeCount_); - jngl::setColor(0, 0, 0, alpha); - jngl::drawRect(-jngl::getScreenWidth() / 2.0 - 1, -jngl::getScreenHeight() / 2.0 - 1, - jngl::getScreenWidth() + 2, jngl::getScreenHeight() + 2); - jngl::setColor(255, 255, 255, 255); + jngl::drawRect(jngl::modelview().translate(-jngl::getScreenSize() / 2), jngl::getScreenSize(), + jngl::Rgba::u8(0, 0, 0, alpha)); }
jhasse/jntetri
b08e1ee084ee53e350e781f1602ff04a84c611f8
GitLab CI: FIx deploy
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e817628..2f02faa 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,79 +1,78 @@ image: fedora:39 linux: stage: build script: - dnf install -y git gcc-c++ fontconfig-devel freetype-devel libvorbis-devel libepoxy-devel libwebp-devel boost-python3-devel python3-devel cmake ninja-build SDL2-devel libatomic - cmake -Bbuild -GNinja - ninja -C build server: image: ubuntu:20.04 stage: build script: - apt-get update && apt-get install -y cmake ninja-build libsoci-dev libsqlite3-dev g++ git libboost-system-dev libboost-coroutine-dev - cd server - cmake -Bbuild -GNinja - cmake --build build web: image: emscripten/emsdk:3.1.61 stage: build script: - apt-get update && apt-get install -y ninja-build - cd /tmp - curl --silent -O -L https://archives.boost.io/release/1.85.0/source/boost_1_85_0.tar.bz2 - tar --wildcards -xf *.tar.bz2 'boost_1_*_0/boost' - cd - - emcmake cmake -GNinja -Bbuild-web -DCMAKE_BUILD_TYPE=Release -DJNGL_VIDEO=0 -DBoost_INCLUDE_DIR=/tmp/boost_1_85_0 - mv data/ build-web/ - cd build-web - ninja jntetri - mkdir ../public - mv jntetri.data ../public/ - mv jntetri.js ../public/ - mv jntetri.wasm ../public/ - mv jntetri.worker.js ../public/ - cp ../web/index.html ../public/ artifacts: paths: - public/ docker-build: image: docker:latest stage: build services: - docker:dind before_script: - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY # Default branch leaves tag empty (= latest tag) # All other branches are tagged with the escaped branch name (commit ref slug) script: - | if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then tag="" echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'" else tag=":$CI_COMMIT_REF_SLUG" echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag" fi - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" web - docker push "$CI_REGISTRY_IMAGE${tag}" pages: stage: deploy dependencies: - web script: - - mv build-web public - - mv web/index.html public/ + - echo artifacts: paths: - public only: - master variables: CLICOLOR_FORCE: "1" GIT_SUBMODULE_STRATEGY: recursive DEBIAN_FRONTEND: noninteractive
jhasse/jntetri
94fac7661965985f25264284bf92daaaf952f14b
GitLab CI: Package web build
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 7d30c9b..e817628 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,72 +1,79 @@ image: fedora:39 linux: stage: build script: - dnf install -y git gcc-c++ fontconfig-devel freetype-devel libvorbis-devel libepoxy-devel libwebp-devel boost-python3-devel python3-devel cmake ninja-build SDL2-devel libatomic - cmake -Bbuild -GNinja - ninja -C build server: image: ubuntu:20.04 stage: build script: - apt-get update && apt-get install -y cmake ninja-build libsoci-dev libsqlite3-dev g++ git libboost-system-dev libboost-coroutine-dev - cd server - cmake -Bbuild -GNinja - cmake --build build web: image: emscripten/emsdk:3.1.61 stage: build script: - apt-get update && apt-get install -y ninja-build - cd /tmp - - curl --silent -O -L https://archives.boost.io/release/1.82.0/source/boost_1_82_0.tar.bz2 + - curl --silent -O -L https://archives.boost.io/release/1.85.0/source/boost_1_85_0.tar.bz2 - tar --wildcards -xf *.tar.bz2 'boost_1_*_0/boost' - cd - - - emcmake cmake -GNinja -Bbuild-web -DCMAKE_BUILD_TYPE=Release -DJNGL_VIDEO=0 -DBoost_INCLUDE_DIR=/tmp/boost_1_82_0 + - emcmake cmake -GNinja -Bbuild-web -DCMAKE_BUILD_TYPE=Release -DJNGL_VIDEO=0 -DBoost_INCLUDE_DIR=/tmp/boost_1_85_0 - mv data/ build-web/ - - ninja -Cbuild-web jntetri + - cd build-web + - ninja jntetri + - mkdir ../public + - mv jntetri.data ../public/ + - mv jntetri.js ../public/ + - mv jntetri.wasm ../public/ + - mv jntetri.worker.js ../public/ + - cp ../web/index.html ../public/ artifacts: paths: - - build-web/ + - public/ docker-build: image: docker:latest stage: build services: - docker:dind before_script: - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY # Default branch leaves tag empty (= latest tag) # All other branches are tagged with the escaped branch name (commit ref slug) script: - | if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then tag="" echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'" else tag=":$CI_COMMIT_REF_SLUG" echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag" fi - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" web - docker push "$CI_REGISTRY_IMAGE${tag}" pages: stage: deploy dependencies: - web script: - mv build-web public - mv web/index.html public/ artifacts: paths: - public only: - master variables: CLICOLOR_FORCE: "1" GIT_SUBMODULE_STRATEGY: recursive DEBIAN_FRONTEND: noninteractive
jhasse/jntetri
c4598240f3c34d3d7f06f8cfd439a7446c457db1
GitLab CI: Use new boost download URL
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 918a353..7d30c9b 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,72 +1,72 @@ image: fedora:39 linux: stage: build script: - dnf install -y git gcc-c++ fontconfig-devel freetype-devel libvorbis-devel libepoxy-devel libwebp-devel boost-python3-devel python3-devel cmake ninja-build SDL2-devel libatomic - cmake -Bbuild -GNinja - ninja -C build server: image: ubuntu:20.04 stage: build script: - apt-get update && apt-get install -y cmake ninja-build libsoci-dev libsqlite3-dev g++ git libboost-system-dev libboost-coroutine-dev - cd server - cmake -Bbuild -GNinja - cmake --build build web: image: emscripten/emsdk:3.1.61 stage: build script: - apt-get update && apt-get install -y ninja-build - cd /tmp - - curl --silent -O -L https://boostorg.jfrog.io/artifactory/main/release/1.82.0/source/boost_1_82_0.tar.bz2 + - curl --silent -O -L https://archives.boost.io/release/1.82.0/source/boost_1_82_0.tar.bz2 - tar --wildcards -xf *.tar.bz2 'boost_1_*_0/boost' - cd - - emcmake cmake -GNinja -Bbuild-web -DCMAKE_BUILD_TYPE=Release -DJNGL_VIDEO=0 -DBoost_INCLUDE_DIR=/tmp/boost_1_82_0 - mv data/ build-web/ - ninja -Cbuild-web jntetri artifacts: paths: - build-web/ docker-build: image: docker:latest stage: build services: - docker:dind before_script: - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY # Default branch leaves tag empty (= latest tag) # All other branches are tagged with the escaped branch name (commit ref slug) script: - | if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then tag="" echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'" else tag=":$CI_COMMIT_REF_SLUG" echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag" fi - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" web - docker push "$CI_REGISTRY_IMAGE${tag}" pages: stage: deploy dependencies: - web script: - mv build-web public - mv web/index.html public/ artifacts: paths: - public only: - master variables: CLICOLOR_FORCE: "1" GIT_SUBMODULE_STRATEGY: recursive DEBIAN_FRONTEND: noninteractive
jhasse/jntetri
167c074d57fe4d4783bb4ad75e02dc3a219ef060
Use jngl::Sprite to draw Field background
diff --git a/src/Field.cpp b/src/Field.cpp index cf24394..c8aaa87 100644 --- a/src/Field.cpp +++ b/src/Field.cpp @@ -1,377 +1,375 @@ #include "Field.hpp" -#include "engine/screen.hpp" - #include <algorithm> +#include <jngl.hpp> #include <map> #include <set> -#include <jngl.hpp> const int Field::width_ = 11; const int Field::height_ = 19; Field::Field(int seed, const int level, const uint32_t startJunks) : blockSize_(60), counter_(0), gameOver_(false), score_(0), level_(level), lines(0), maxY(0), pause_(false), control_(new Control{ std::make_shared<KeyboardControl>(), std::make_shared<GamepadControl>(0) }), randomSeed(seed), linesCleared(0) { random.seed(seed); NewTetromino(); NewTetromino(); score_ = 0; std::mt19937 colorRandom; std::uniform_int_distribution<int> colorDist(0, 255); for (unsigned int i = 0; i < startJunks; ++i) { int leaveOut = random() % (width_ - 1); for (int x = 0; x < width_; ++x) { if (x != leaveOut) { jngl::Color color(colorDist(colorRandom), colorDist(colorRandom), colorDist(colorRandom)); AddBlock(Block(x, i, color)); } } } } void Field::addJunk(int nr) { for (int i = 0; i < nr; ++i) { control_->addJunk(); } } double Field::getSecondsPlayed() const { return secondsPlayed; } void Field::ResetCounter() { counter_ = static_cast<int>(200 / (level_ * 1.5 + 1)); } void Field::step() { if (desyncInfo) { desyncInfo->step(); if (!checkDesync()) { desyncInfo = std::nullopt; } return; } if (pause_) { return; } if (checkDesync && checkDesync()) { // is our opponent having network issues? desyncInfo = DesyncInfo(onUserQuitCallback); } else { if (!control_->step()) { ++stepsWithoutPackage; return; } } if (gameOver_) { --counter_; if (counter_ <= 0 && !blocks_.empty()) { counter_ = 5; std::vector<Block>::iterator randomBlock = blocks_.size() == 1 ? blocks_.begin() : (blocks_.begin() + (random() % (blocks_.size() - 1))); explosions_.push_back(Explosion(*randomBlock, 1)); blocks_.erase(randomBlock); } } else { --counter_; stepsWithoutPackage = 0; secondsPlayed += 1. / double(jngl::getStepsPerSecond()); linesCleared = 0; if (counter_ <= 0) { ResetCounter(); if (!tetromino_->MoveDown()) { if (delay_) { NewTetromino(); delay_ = false; } else { counter_ = 30; // Wait 0.3 seconds so that it's possible to move blocks // below others delay_ = true; } } else { delay_ = false; } } tetromino_->Step(); if (control_->Check(ControlType::Drop)) { tetromino_->drop(); NewTetromino(); } if (control_->Check(ControlType::Down)) { if (downKeyReleased_ && counter_ > 7) { counter_ = 7; } } else { downKeyReleased_ = true; } if (control_->Check(ControlType::AddJunk)) { for (auto& block : blocks_) { block.setY(block.getY() + 1); block.setAnimationY(block.getAnimationY() - 1); } if (tetromino_) { tetromino_->moveUp(1); } std::mt19937 colorRandom; std::uniform_int_distribution<int> colorDist(0, 255); int leaveOut = random() % (width_ - 1); for (int x = 0; x < width_; ++x) { if (x != leaveOut) { jngl::Color color(colorDist(colorRandom), colorDist(colorRandom), colorDist(colorRandom)); Block block(x, 0, color); block.setAnimationY(-1); AddBlock(block); } } } } for (auto& b : blocks_) { b.step(); } if ((level_ + 1) * 10 <= lines) { ++level_; } for (auto& e : explosions_) { e.Step(); } explosions_.erase(std::remove_if(explosions_.begin(), explosions_.end(), [](const Explosion& e) { return e.isFinished(); }), explosions_.end()); } void Field::CheckLines() { std::set<int> linesToRemove; // We need to sort the lines so that they are removed from top to bottom std::map<int, int> blocksInLine; for (const auto& block : blocks_) { if (++blocksInLine[block.getY()] == width_) { linesToRemove.insert(block.getY()); } } linesCleared = linesToRemove.size(); score_ += linesCleared * linesCleared * (level_ + 1) * (level_ + 1); // Remove lines from top to bottom so that explosions will be placed correctly auto rend = linesToRemove.rend(); for (auto it = linesToRemove.rbegin(); it != rend; ++it) { removeLine(*it, static_cast<int>(linesToRemove.size())); } } void Field::NewTetromino() { downKeyReleased_ = false; ResetCounter(); score_ += level_; if (tetromino_) { tetromino_->AttachToField(); CheckLines(); } tetromino_ = nextTetromino_; nextTetromino_.reset(new Tetromino(random() % 7, *this)); if (tetromino_) { const int xPositions[] = { 5, 6, 4, 7, 3, 8, 2, 9, 1, 10, 0 }; - for (int i = 0; i < 11; ++i) { - tetromino_->SetX(xPositions[i]); + for (int xPosition : xPositions) { + tetromino_->SetX(xPosition); if (!tetromino_->Collided()) { return; } } tetromino_->SetX(xPositions[0]); gameOver_ = true; nextTetromino_ = tetromino_; counter_ = 10; } } bool Field::GameOver() const { return gameOver_; } jngl::Vec2 Field::indexToPixel(const double x, const double y) const { return { -double(width_ * blockSize_) / 2.0 + (x + 0.5) * blockSize_, height_ * blockSize_ - y * blockSize_ - 600 }; } double Field::getBottomY() const { return height_ * blockSize_; } int Field::GetNextPosition() const { int nextPosition = 300 - (maxY - 4) * blockSize_; if (nextPosition > 300) { return 300; } if (nextPosition < -425) { return -425; } return nextPosition; } void Field::drawNextTetromino() const { jngl::print("Next:", -100, -75); jngl::pushMatrix(); jngl::translate(0, 600); nextTetromino_->draw(false); jngl::popMatrix(); } void Field::draw() const { - GetScreen().DrawCentered("field", 0, 0); + bg.draw(); if (stepsWithoutPackage > 0) { jngl::setFontColor(0x000000_rgb); jngl::print(std::string((stepsWithoutPackage / 20) % 4, '.'), { -60, -100 }); return; } if (desyncInfo && desyncInfo->getStepsAlive() > 0.5 * jngl::getStepsPerSecond()) { desyncInfo->draw(); } else if (!pause_) { if (!gameOver_) { tetromino_->drawShadow(); } jngl::pushMatrix(); jngl::translate(indexToPixel(0, 0)); std::vector<Block>::const_iterator end = blocks_.end(); for (std::vector<Block>::const_iterator it = blocks_.begin(); it != end; ++it) { it->setSpriteColor(); it->draw(); } jngl::setSpriteColor(255, 255, 255); std::vector<Explosion>::const_iterator end2 = explosions_.end(); for (std::vector<Explosion>::const_iterator it = explosions_.begin(); it != end2; ++it) { it->Draw(); } jngl::popMatrix(); if (!gameOver_) { tetromino_->draw(true); } } } Block* Field::getBlock(int x, int y) { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (x == it->getX() && y == it->getY()) { return &(*it); } } return nullptr; } bool Field::checkCollision(const int x, const int y) const { if (x < 0 || x >= width_ || y < 0) { return true; } auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (x == it->getX() && y == it->getY()) { return true; } } return false; } void Field::AddBlock(const Block& block) { blocks_.push_back(block); if (blocks_.back().getY() > maxY) { maxY = blocks_.back().getY(); } // Copy the current animation for (const auto& block : blocks_) { if (block.getAnimationY() > 0.0001 || block.getAnimationY() < -0.0001) { blocks_.back().setAnimationY(block.getAnimationY()); } } } int Field::getBlockSize() const { return blockSize_; } void Field::removeLine(const int y, const int numberOfLines) { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (it->getY() == y) { explosions_.push_back(Explosion(*it, numberOfLines)); blocks_.erase(it); return removeLine(y, numberOfLines); } } for (auto it = blocks_.begin(); it != end; ++it) { if (it->getY() > y) { it->setY(it->getY() - 1); it->setAnimationY(it->getAnimationY() + 1); } } ++lines; --maxY; } int Field::GetScore() const { return score_; } int Field::GetLines() const { return lines; } int Field::GetLevel() const { return level_; } void Field::SetPause(bool pause) { pause_ = pause; jngl::setMouseVisible(pause); } bool Field::desync() const { return control_->desync(); } void Field::setCheckDesync(std::function<bool()> checkDesync) { this->checkDesync = std::move(checkDesync); } void Field::onUserQuit(std::function<void()> onUserQuitCallback) { this->onUserQuitCallback = std::move(onUserQuitCallback); } bool Field::GameOverAnimationFinished() const { return blocks_.empty(); } void Field::setGameOver(bool gameOver) { gameOver_ = gameOver; } void Field::setControl(Control* control) { control_.reset(control); } Control& Field::getControl() const { return *control_; } unsigned int Field::getRandom() { return random(); } int Field::getRandomSeed() const { return randomSeed; } int Field::getLinesCleared() const { return linesCleared; } diff --git a/src/Field.hpp b/src/Field.hpp index 3dd30a9..caa67ca 100644 --- a/src/Field.hpp +++ b/src/Field.hpp @@ -1,97 +1,99 @@ #pragma once #include "Block.hpp" #include "DesyncInfo.hpp" -#include "tetromino.hpp" -#include "explosion.hpp" #include "control.hpp" +#include "explosion.hpp" +#include "tetromino.hpp" #include <vector> #include <random> #include <ctime> #include <memory> #include <optional> class Field { public: Field(int seed, int level, uint32_t startJunks); Field(const Field&) = delete; Field(Field&&) = delete; Field& operator=(const Field&) = delete; Field& operator=(Field&&) = delete; void step(); void draw() const; void DrawBlock(int x, int y) const; void AddBlock(const Block&); [[nodiscard]] jngl::Vec2 indexToPixel(double x, double y) const; /// y coordinate in dp of the bottom double getBottomY() const; int getBlockSize() const; Block* getBlock(int x, int y); bool checkCollision(int x, int y) const; void NewTetromino(); void removeLine(int y, int numberOfLines); void setGameOver(bool); bool GameOver() const; int GetScore() const; int GetLines() const; int GetLevel() const; int GetNextPosition() const; void drawNextTetromino() const; void SetPause(bool pause); /// returns true when there are network issues bool desync() const; /// the function will be called to check if there's a network desync and the game should be /// paused void setCheckDesync(std::function<bool()>); void onUserQuit(std::function<void()>); bool GameOverAnimationFinished() const; void setControl(Control*); Control& getControl() const; unsigned int getRandom(); int getRandomSeed() const; int getLinesCleared() const; void addJunk(int nr); double getSecondsPlayed() const; private: void CheckLines(); void ResetCounter(); std::vector<Block> blocks_; std::vector<Explosion> explosions_; std::shared_ptr<Tetromino> nextTetromino_; std::shared_ptr<Tetromino> tetromino_; const static int width_; const static int height_; const int blockSize_; int counter_; bool gameOver_; int score_; int level_; int lines; int maxY; bool pause_; /// >0 when there are network issues i.e. control_->step() hasn't returned any data int stepsWithoutPackage = 0; bool delay_; std::shared_ptr<Control> control_; bool downKeyReleased_; std::mt19937 random; int randomSeed; int linesCleared; double secondsPlayed = 0; /// If set, we force-pause the game when it returns true std::function<bool()> checkDesync; std::optional<DesyncInfo> desyncInfo; std::function<void()> onUserQuitCallback; + + jngl::Sprite bg{ "gfx/field" }; }; diff --git a/src/Game.cpp b/src/Game.cpp index c87b60a..b3d75dd 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -1,138 +1,137 @@ #include "Game.hpp" -#include "engine/screen.hpp" +#include "ReplayRecorder.hpp" #include "engine/Options.hpp" #include "gameoverscreen.hpp" #include "pausemenu.hpp" -#include "ReplayRecorder.hpp" +#include <iomanip> #include <jngl.hpp> #include <sstream> -#include <iomanip> Game::Game(const GameType type, const int seed, const bool replay) : field_(seed, getOptions().startLevel, getOptions().startJunks), type_(type), nextPosition_(field_.GetNextPosition()), oldNextPosition_(nextPosition_), rotateScreen_(false), rotateDegree_(0) { if (!replay) { // Don't record when we're playing back a replay replayRecorder = std::make_unique<ReplayRecorder>(field_, type); } jngl::setMouseVisible(false); } Game::~Game() { jngl::setMouseVisible(true); } void Game::SetRotateScreen(bool rotateScreen) { rotateScreen_ = rotateScreen; } void Game::step() { StepToRotateScreen(); if (field_.GameOver()) { pauseTime_ = jngl::getTime(); jngl::setWork(std::make_shared<GameOverScreen>(this)); } else { field_.step(); if (replayRecorder) { replayRecorder->Step(); } if (type_ == GameType::FIFTYLINES && field_.GetLines() >= 50) { field_.setGameOver(true); } } nextPosition_ = field_.GetNextPosition(); oldNextPosition_ = (nextPosition_ - oldNextPosition_) * 0.01 + oldNextPosition_; if (pauseTime_ > 0.0001 && !field_.GameOver()) { pauseTime_ = 0; } if (jngl::keyPressed('p')) { onQuitEvent(); // Pause } } void Game::onQuitEvent() { static double lastPauseTime = 0; if (jngl::getTime() - lastPauseTime > 1) { // Don't allow pausing the game more then one time per second lastPauseTime = pauseTime_ = jngl::getTime(); field_.SetPause(true); jngl::setWork(std::make_shared<PauseMenu>(shared_from_this())); jngl::cancelQuit(); } } void Game::DrawTime(const int x, const int y) const { jngl::print("Time: ", x, y); double time = GetTime(); int minutes = int(time / 60); int seconds = int(time - minutes * 60); std::stringstream sstream; sstream.fill('0'); sstream << minutes << ":" << std::setw(2) << seconds; jngl::print(sstream.str(), 450, y + 100); } void Game::StepToRotateScreen() { if (rotateScreen_ && rotateDegree_ < 90) { rotateDegree_ += (90 - rotateDegree_) * 0.05; } else { rotateDegree_ *= 0.95; } } void Game::draw() const { jngl::pushMatrix(); jngl::rotate(rotateDegree_); jngl::scale(1 + rotateDegree_ / 270); field_.draw(); if (!rotateScreen_) { jngl::setFontColor(0, 0, 0); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(-600, oldNextPosition_); field_.drawNextTetromino(); jngl::popMatrix(); if (type_ == GameType::FIFTYLINES) { DrawTime(450, -500); } else { jngl::print("Score: ", 450, -500); jngl::print(std::to_string(field_.GetScore()), 450, -400); DrawTime(450, 220); } jngl::print("Level: ", 450, -260); jngl::print(std::to_string(field_.GetLevel()), 450, -160); jngl::print("Lines: ", 450, -20); jngl::print(std::to_string(field_.GetLines()), 450, 80); } jngl::popMatrix(); } Field& Game::GetField() { return field_; } double Game::GetTime() const { return field_.getSecondsPlayed(); } bool Game::GameOverAnimationFinished() const { return field_.GameOverAnimationFinished(); } GameType Game::getType() const { return type_; } bool Game::gameOver() const { return field_.GameOver(); } bool Game::isReplay() const { return replayRecorder == nullptr; } void Game::onLoad() { field_.SetPause(false); } diff --git a/src/ReplayRecorder.hpp b/src/ReplayRecorder.hpp index 78edb8a..19f2c15 100644 --- a/src/ReplayRecorder.hpp +++ b/src/ReplayRecorder.hpp @@ -1,21 +1,21 @@ #pragma once -#include "control.hpp" +#include "ControlType.hpp" #include "gametype.hpp" #include <fstream> class Field; class ReplayRecorder { public: ReplayRecorder(Field&, GameType); void Step(); private: void write(ControlType); std::ofstream fout; Field& field_; unsigned char time_; }; diff --git a/src/SplitScreen.cpp b/src/SplitScreen.cpp index 818fdb3..e91e341 100644 --- a/src/SplitScreen.cpp +++ b/src/SplitScreen.cpp @@ -1,98 +1,99 @@ #include "SplitScreen.hpp" -#include "engine/fade.hpp" -#include "engine/screen.hpp" #include "Field.hpp" #include "NetworkControl.hpp" #include "NetworkRecorder.hpp" +#include "engine/fade.hpp" +#include "engine/screen.hpp" #include "lobby.hpp" -#include <jngl/matrix.hpp> #include <jngl/font.hpp> +#include <jngl/matrix.hpp> #include <memory> #include <sstream> +#include <utility> SplitScreen::SplitScreen(std::shared_ptr<ControlBase> opponentControl, const int32_t seed) -: opponentControl(opponentControl) { +: opponentControl(std::move(opponentControl)) { reset(seed); } SplitScreen::~SplitScreen() = default; void SplitScreen::reset(const int32_t seed) { freezeCountdown = 0; field1.reset(new Field(seed, wins1, 0)); // FIXME: We shouldn't know about NetworkControl here if (const auto networkControl = std::dynamic_pointer_cast<NetworkControl>(opponentControl)) { field1->setControl(new NetworkRecorder( { std::make_shared<KeyboardControl>(), std::make_shared<GamepadControl>(0) }, networkControl)); field1->onUserQuit([networkControl]() { networkControl->sendQuit(); jngl::setWork<Fade>(std::make_shared<Lobby>(networkControl->getSocket(), false)); }); } field2.reset(new Field(seed, wins2, 0)); field2->setControl(new Control{ opponentControl }); field1->setCheckDesync([this]() { return field2->desync(); }); } void SplitScreen::step() { field1->step(); field2->step(); if (freezeCountdown > 0) { --freezeCountdown; if (freezeCountdown == 1) { if (const auto networkControl = std::dynamic_pointer_cast<NetworkControl>(opponentControl)) { jngl::setWork<Lobby>(networkControl->getSocket(), false); } else { reset(123); // TODO: Decide on next seed } } } else { const auto penalty = [](const int cleared) { switch(cleared) { case 2: return 1; case 3: return 2; case 4: return 4; } return 0; }; field2->addJunk(penalty(field1->getLinesCleared())); field1->addJunk(penalty(field2->getLinesCleared())); if (field1->GameOver()) { ++wins2; freezeCountdown = 200; } if (field2->GameOver()) { ++wins1; freezeCountdown = 200; } } } void SplitScreen::draw() const { jngl::pushMatrix(); jngl::translate(-660, 0); field1->draw(); jngl::translate(1320, 0); field2->draw(); jngl::popMatrix(); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(-180, -500); field1->drawNextTetromino(); jngl::translate(330, 0); jngl::setFontColor(0, 0, 0, 150); jngl::setSpriteAlpha(150); field2->drawNextTetromino(); jngl::setFontColor(0, 0, 0, 255); jngl::setSpriteAlpha(255); jngl::popMatrix(); std::stringstream sstream; sstream << wins1 << " : " << wins2; jngl::setFontSize(140); GetScreen().printCentered(sstream.str(), { 0, 0 }); } diff --git a/src/control.hpp b/src/control.hpp index 213d536..a5c547f 100644 --- a/src/control.hpp +++ b/src/control.hpp @@ -1,64 +1,64 @@ #pragma once #include "ControlType.hpp" #include <bitset> #include <functional> #include <memory> #include <vector> namespace jngl { class Controller; -} +} // namespace jngl class ControlBase { public: virtual ~ControlBase(); /// Returns false when no new commands are coming in (e.g. network issues). virtual bool step(const std::function<void(ControlType)>&); /// step should set ControlType::AddJunk in the next frame virtual void addJunk(); /// Network issues? virtual bool desync() const; protected: int junkToAdd = 0; }; class Control { public: Control(std::initializer_list<std::shared_ptr<ControlBase>>); virtual ~Control(); bool Check(ControlType); /// Returns false when no new commands are coming in (e.g. network issues). virtual bool step(); void forEach(const std::function<void(ControlType)>&); /// Calls ControlBase::addJunk. Only really relevant when using NetworkControl void addJunk(); bool desync() const; protected: std::bitset<static_cast<size_t>(ControlType::LastValue)> bits_; std::vector<std::shared_ptr<ControlBase>> controls; }; class KeyboardControl : public ControlBase { public: bool step(const std::function<void(ControlType)>&) override; }; class GamepadControl : public ControlBase { public: - GamepadControl(size_t number); + explicit GamepadControl(size_t number); bool step(const std::function<void(ControlType)>&) override; private: std::shared_ptr<jngl::Controller> controller; }; diff --git a/src/gameoverscreen.cpp b/src/gameoverscreen.cpp index 34402fc..1d22183 100644 --- a/src/gameoverscreen.cpp +++ b/src/gameoverscreen.cpp @@ -1,82 +1,82 @@ #include "gameoverscreen.hpp" -#include "engine/screen.hpp" -#include "engine/fade.hpp" -#include "engine/Options.hpp" #include "Game.hpp" +#include "engine/Options.hpp" +#include "engine/fade.hpp" +#include "engine/screen.hpp" #include "menu.hpp" #include <jngl.hpp> GameOverScreen::GameOverScreen(Game* game) : game_(game), blink_(0), highscore_(game_->getType()), input_(new Input(-160, 200)), work_(jngl::getWork()) { data_.score = game_->GetField().GetScore(); data_.time = game_->GetTime(); input_->setText(getOptions().lastHighscoreName); input_->setMaxWidth(400); addWidget(input_); } bool GameOverScreen::isHighscore() const { return !game_->isReplay() && highscore_.isHighscore(data_) && (game_->getType() == GameType::NORMAL || game_->GetField().GetLines() >= 50); } void GameOverScreen::step() { game_->GetField().step(); // Show GameOver animation game_->StepToRotateScreen(); if (game_->GameOverAnimationFinished()) { if (isHighscore()) { StepWidgets(); if (jngl::keyPressed(jngl::key::Return)) { data_.name = input_->getText(); getOptions().lastHighscoreName = data_.name; highscore_.Add(data_); highscore_.save(); auto menu = std::make_shared<Menu>(); menu->BlinkHighscore(data_); jngl::setWork(std::make_shared<Fade>(std::move(menu))); } } else { blink_ += 4; if (blink_ > 2 * 255) { blink_ = 0; } if (jngl::mousePressed() || jngl::keyPressed(jngl::key::Any)) { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } } } else if (jngl::keyPressed(jngl::key::Escape)) { while (!game_->GameOverAnimationFinished()) { game_->GetField().step(); } } } void GameOverScreen::onQuitEvent() { while (!game_->GameOverAnimationFinished()) { game_->GetField().step(); } if (!isHighscore()) { jngl::quit(); } } void GameOverScreen::draw() const { game_->draw(); jngl::setFontSize(80); jngl::setFontColor(0, 0, 0); GetScreen().printCentered("GAMEOVER", { 0, -100 }); if (game_->GameOverAnimationFinished()) { jngl::setFontSize(50); if (isHighscore()) { jngl::setFontColor(0, 0, 0); GetScreen().printCentered("You entered the top!", { 0, 50 }); GetScreen().printCentered("Enter your name:", { 0, 130 }); DrawWidgets(); } else { jngl::setFontColor(0, 0, 0, blink_ > 255 ? 510 - blink_ : blink_); GetScreen().printCentered("Press any key", { 0, 100 }); } } } diff --git a/src/multiplayermenu.cpp b/src/multiplayermenu.cpp index 381d731..cb8ccd2 100644 --- a/src/multiplayermenu.cpp +++ b/src/multiplayermenu.cpp @@ -1,58 +1,57 @@ #include "multiplayermenu.hpp" -#include "engine/screen.hpp" -#include "engine/fade.hpp" +#include "Login.hpp" #include "engine/Options.hpp" +#include "engine/fade.hpp" #include "menu.hpp" -#include "Login.hpp" #include <jngl.hpp> MultiplayerMenu::MultiplayerMenu(const bool quickLogin) : name_(new Input(50, -240)), password_(new Input(50, -100)), quickLogin(quickLogin) { addWidget(name_); addWidget(password_); login_.reset(new Button("Login", [this]() { OnLogin(); })); addWidget(login_); back_.reset(new Button("Back", [this]() { OnBack(); })); addWidget(back_); back_->setCenter(-350, 280); login_->setCenter(350, 280); password_->SetPassword(true); name_->setText(getOptions().lastLoginName); if (name_->getText() != "") { FocusNext(); } } void MultiplayerMenu::step() { StepWidgets(); if (jngl::keyPressed(jngl::key::Return) || quickLogin) { OnLogin(); quickLogin = false; // if an error happens we will be reactivated } } void MultiplayerMenu::draw() const { jngl::setFontColor(0, 0, 0); jngl::print("Name:", -500, -240); jngl::print("Password:", -500, -100); DrawWidgets(); } void MultiplayerMenu::OnBack() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void MultiplayerMenu::OnLogin() { jngl::setWork(std::make_shared<Login>( std::dynamic_pointer_cast<MultiplayerMenu>(jngl::getWork()), quickLogin)); } std::string MultiplayerMenu::GetName() const { return name_->getText(); } std::string MultiplayerMenu::GetPassword() const { return password_->getText(); }
jhasse/jntetri
40bd94430bd1bb78cbb4099d6ccedfa3567404b6
Use FindBoost again to fix web
diff --git a/CMakeLists.txt b/CMakeLists.txt index baeb153..55b21b7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,63 +1,64 @@ cmake_minimum_required(VERSION 3.15) project(jntetri) if(NOT MSVC) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=implicit-function-declaration") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color -Wall -Wextra -Winit-self -Wpedantic -Wdelete-non-virtual-dtor") # -Wno-implicit-fallthrough', # cereal # -Wno-class-memaccess', # cereal") endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") set(USE_FLAGS "-s USE_SDL=2 -pthread -s USE_PTHREADS=1 -s USE_FREETYPE=1 -s USE_VORBIS=1 -s DISABLE_EXCEPTION_CATCHING=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${USE_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${USE_FLAGS}") string(APPEND CMAKE_EXE_LINKER_FLAGS " ${USE_FLAGS} -s WEBSOCKET_URL=wss://jntetri.boomshine.de -s ASSERTIONS=1 -s FULL_ES3=1 " "--pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/pre.js -lidbfs.js") set(CMAKE_EXECUTABLE_SUFFIX ".html") endif() if (TARGET_WASM) add_compile_options("SHELL:-s USE_PTHREADS") add_link_options("SHELL:-s USE_PTHREADS") endif() include(subprojects/jngl/cmake/CPM.cmake) CPMAddPackage( NAME nlohmann_json URL "https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz" ) include(FetchContent) CPMAddPackage( NAME spdlog URL https://github.com/gabime/spdlog/archive/v1.13.0.tar.gz URL_HASH SHA1=2042a47b2076cbdcd33e648b0df031cb03963097) CPMAddPackage( NAME cereal URL https://github.com/USCiLab/cereal/archive/refs/tags/v1.3.2.tar.gz OPTIONS "SKIP_PORTABILITY_TEST ON" "JUST_INSTALL_CEREAL ON" ) add_subdirectory(subprojects/jngl) file(GLOB SRC src/*.cpp src/engine/*.cpp src/gui/*.cpp) add_executable(jntetri ${SRC}) # find_package(Boost COMPONENTS coroutine system thread) -find_package(Boost CONFIG REQUIRED) +find_package(Boost REQUIRED) +# find_package(Boost CONFIG REQUIRED) Can't get this to work with custom Boost (web) target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json Boost::boost) set_property(TARGET jntetri PROPERTY CXX_STANDARD 20) if(MSVC) target_compile_definitions(jntetri PRIVATE BOOST_ALL_NO_LIB _WIN32_WINNT=0x0601) elseif(WIN32) target_link_libraries(jntetri PRIVATE ws2_32) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") target_link_options(jntetri PRIVATE --preload-file data) endif()
jhasse/jntetri
239b8ac9472d9c6520782d8709fb16f9fcc89ec5
Fix clang warnings
diff --git a/.clang-tidy b/.clang-tidy index df8803d..7f9acec 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,70 +1,71 @@ --- Checks: ' ,*, ,-altera-id-dependent-backward-branch, ,-altera-struct-pack-align, ,-altera-unroll-loops, ,-android-cloexec-fopen, ,-bugprone-easily-swappable-parameters, ,-cert-err52-cpp, ,-cert-err58-cpp, ,-cert-flp30-c, ,-clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, ,-clang-diagnostic-unused-command-line-argument, ,-cppcoreguidelines-avoid-c-arrays, + ,-cppcoreguidelines-avoid-const-or-ref-data-members, ,-cppcoreguidelines-avoid-magic-numbers, ,-cppcoreguidelines-avoid-non-const-global-variables, ,-cppcoreguidelines-init-variables, ,-cppcoreguidelines-non-private-member-variables-in-classes, ,-cppcoreguidelines-owning-memory, ,-cppcoreguidelines-pro-bounds-array-to-pointer-decay, ,-cppcoreguidelines-pro-bounds-constant-array-index, ,-cppcoreguidelines-pro-bounds-pointer-arithmetic, ,-cppcoreguidelines-pro-type-vararg, ,-cppcoreguidelines-special-member-functions, ,-fuchsia-default-arguments-calls, ,-fuchsia-default-arguments-declarations, ,-fuchsia-default-arguments, ,-fuchsia-multiple-inheritance, ,-fuchsia-overloaded-operator, ,-fuchsia-statically-constructed-objects, ,-google-global-names-in-headers, ,-google-readability-todo, ,-google-runtime-int, ,-google-runtime-references, ,-hicpp-avoid-c-arrays, ,-hicpp-named-parameter, ,-hicpp-no-array-decay, ,-hicpp-signed-bitwise, ,-hicpp-special-member-functions, ,-hicpp-uppercase-literal-suffix, ,-hicpp-vararg, ,-llvm-header-guard, ,-llvm-qualified-auto, ,-llvmlibc-callee-namespace, ,-llvmlibc-implementation-in-namespace, ,-llvmlibc-inline-function-decl, ,-llvmlibc-restrict-system-libc-headers, ,-misc-no-recursion, ,-misc-non-private-member-variables-in-classes, ,-modernize-avoid-c-arrays, ,-modernize-use-nodiscard, ,-modernize-use-trailing-return-type, ,-readability-function-cognitive-complexity, ,-readability-identifier-length, ,-readability-magic-numbers, ,-readability-named-parameter, ,-readability-qualified-auto, ,-readability-uppercase-literal-suffix, ,-readability-use-anyofallof, ' WarningsAsErrors: 'hicpp-use-override,modernize-avoid-bind,llvm-namespace-comment,modernize-use-nullptr,modernize-pass-by-value,hicpp-noexcept-move,boost-use-to-string,google-readability-namespace-comments,modernize-use-default-member-init,modernize-loop-convert,hicpp-use-nullptr,google-readability-braces-around-statements,cert-dcl03-c,readability-else-after-return,bugprone-macro-parentheses,readability-redundant-declaration,google-explicit-constructor,readability-avoid-const-params-in-decls' CheckOptions: - key: readability-implicit-bool-conversion.AllowPointerConditions value: '1' - key: readability-implicit-bool-conversion.AllowIntegerConditions value: '1' - key: bugprone-narrowing-conversions.WarnOnFloatingPointNarrowingConversion value: '0' - key: cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion value: '0' diff --git a/src/Game.hpp b/src/Game.hpp index 0fb6295..9369f58 100644 --- a/src/Game.hpp +++ b/src/Game.hpp @@ -1,39 +1,39 @@ #pragma once #include "engine/work.hpp" #include "Field.hpp" #include "gametype.hpp" class ReplayRecorder; class Game : public Work, public std::enable_shared_from_this<Game> { public: Game(GameType, int seed, bool replay); - virtual ~Game(); - virtual void step(); - virtual void draw() const; - void onQuitEvent(); + ~Game() override; + void step() override; + void draw() const override; Field& GetField(); double GetTime() const; bool GameOverAnimationFinished() const; GameType getType() const; void DrawTime(int x, int y) const; void StepToRotateScreen(); void SetRotateScreen(bool); bool gameOver() const; bool isReplay() const; protected: + void onQuitEvent() override; void onLoad() override; Field field_; GameType type_; double nextPosition_; double oldNextPosition_; double pauseTime_ = 0; bool rotateScreen_; double rotateDegree_; /// If we're owned by a ReplayPlayer, this is nullptr std::unique_ptr<ReplayRecorder> replayRecorder; }; diff --git a/src/NetworkControl.cpp b/src/NetworkControl.cpp index 21fe66b..a3c1f35 100644 --- a/src/NetworkControl.cpp +++ b/src/NetworkControl.cpp @@ -1,115 +1,115 @@ #include "NetworkControl.hpp" #include "engine/socket.hpp" #include "gui/MessageBox.hpp" #include "jngl/window.hpp" #include "jngl/work.hpp" #include "lobby.hpp" #include "multiplayermenu.hpp" #include <nlohmann/json.hpp> #include <spdlog/spdlog.h> NetworkControl::NetworkControl(std::shared_ptr<Socket> socket) : socket(std::move(socket)) { this->socket->receive([this](json buf) { handleReceive(std::move(buf)); }); } bool NetworkControl::step(const std::function<void(ControlType)>& set) { if (!sendQueue.empty() && !sendingInProgress) { sendingInProgress = true; nlohmann::json j = { { "type", "game" }, { "time", sendQueue.front().first }, { "control", sendQueue.front().second }, }; socket->send(j, [this]() { sendQueue.pop(); // spdlog::info("sent package success. {} to go.", sendQueue.size()); sendingInProgress = false; }); } socket->step(); if (nullPackagesReceived < 1) { return false; } bool handledNullPackage = false; while ((time % BUFFER_LENGTH) == data.front().first) { if (data.front().second == ControlType::Null) { if (handledNullPackage) { break; // Don't skip ahead if there are no commands between two null packages } handledNullPackage = true; --nullPackagesReceived; } else { set(data.front().second); // execute command } data.pop(); if (data.empty()) { break; } } ++time; return true; } void NetworkControl::handleReceive(json j) { if (j["type"] == "game") { uint8_t time = j["time"].get<uint8_t>(); uint8_t control = j["control"].get<uint8_t>(); if (control >= static_cast<int>(ControlType::LastValue)) { spdlog::error("invalid control type in package: {}", control); } else { if (control == static_cast<uint8_t>(ControlType::Null)) { // spdlog::info("Null package received."); ++nullPackagesReceived; } data.push( std::pair<unsigned char, ControlType>(time, static_cast<ControlType>(control))); } } else if (j["type"] == "opponentQuit") { jngl::setWork<MessageBox>("Your opponent left.", std::make_shared<Lobby>(std::move(socket), false)); return; } else if (j["type"] == "disconnected") { jngl::setWork<MessageBox>("Your opponent disconnected.", std::make_shared<Lobby>(std::move(socket), false)); return; } else if (j["type"] == "error") { jngl::setWork<MessageBox>(j["msg"], std::make_shared<MultiplayerMenu>(false)); return; } else { spdlog::error("Unknown package: {}", j.dump()); } socket->receive([this](json buf) { handleReceive(std::move(buf)); }); } void NetworkControl::stepSend(Control& control) { if (sendTime % BUFFER_LENGTH == 0) { sendQueue.push(std::pair<uint8_t, ControlType>(0, ControlType::Null)); } control.forEach([this](ControlType c) { sendQueue.push(std::pair<uint8_t, ControlType>(sendTime % BUFFER_LENGTH, c)); }); ++sendTime; } bool NetworkControl::desync() const { #ifndef NDEBUG std::stringstream sstream; sstream << "time: " << time << " sendTime: " << sendTime << " nullPackagesReceived: " << nullPackagesReceived << " sendQueue.size(): " << sendQueue.size(); jngl::setTitle(sstream.str()); #endif return std::abs(time - sendTime) > 1000; } void NetworkControl::sendQuit() { - socket->send(json{ { "type", "quit" } }, [this]() { spdlog::info("sent quit success."); }); + socket->send(json{ { "type", "quit" } }, []() { spdlog::info("sent quit success."); }); } std::shared_ptr<Socket> NetworkControl::getSocket() { return socket; } diff --git a/src/engine/socket.hpp b/src/engine/socket.hpp index 3efad7d..d58bb40 100644 --- a/src/engine/socket.hpp +++ b/src/engine/socket.hpp @@ -1,30 +1,29 @@ #pragma once #include <boost/asio.hpp> #include <functional> #include <nlohmann/json.hpp> using nlohmann::json; class Socket { public: Socket(); Socket(const Socket&) = delete; Socket(Socket&&) = delete; Socket& operator=(const Socket&) = delete; Socket& operator=(Socket&&) = delete; void connect(const std::string& server, int port, std::function<void()> onSuccess); void send(const std::string& data, std::function<void()> onSuccess); void send(const json& data, std::function<void()> onSuccess); void receive(std::function<void(json)> onSuccess); void step(); private: boost::asio::io_service io_; boost::asio::ip::tcp::socket socket_; void CallbackWrapper(const boost::system::error_code& err, std::function<void()> onSuccess); std::string buffer; - std::array<char, 1024> receiveBuffer; std::function<void(json)> onReceiveSuccess; }; diff --git a/subprojects/jngl b/subprojects/jngl index ab1728b..3c8e398 160000 --- a/subprojects/jngl +++ b/subprojects/jngl @@ -1 +1 @@ -Subproject commit ab1728b82a448a57e610e92e15400be08f6fcfa5 +Subproject commit 3c8e398045ac9907a20bdfba23ec6fcb6fe203cc
jhasse/jntetri
9cde286496ba73f2910455b1027b050661019497
Fix CMake FindBoost warning
diff --git a/CMakeLists.txt b/CMakeLists.txt index d7e6a97..7a2190b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,63 +1,63 @@ cmake_minimum_required(VERSION 3.15) project(jntetri) if(NOT MSVC) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=implicit-function-declaration") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color -Wall -Wextra -Winit-self -Wpedantic -Wdelete-non-virtual-dtor") # -Wno-implicit-fallthrough', # cereal # -Wno-class-memaccess', # cereal") endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") set(USE_FLAGS "-s USE_SDL=2 -pthread -s USE_PTHREADS=1 -s USE_FREETYPE=1 -s USE_VORBIS=1 -s DISABLE_EXCEPTION_CATCHING=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${USE_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${USE_FLAGS}") string(APPEND CMAKE_EXE_LINKER_FLAGS " ${USE_FLAGS} -s WEBSOCKET_URL=wss://jntetri.boomshine.de -s ASSERTIONS=1 -s FULL_ES3=1 " "--pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/pre.js -lidbfs.js") set(CMAKE_EXECUTABLE_SUFFIX ".html") endif() if (TARGET_WASM) add_compile_options("SHELL:-s USE_PTHREADS") add_link_options("SHELL:-s USE_PTHREADS") endif() include(subprojects/jngl/cmake/CPM.cmake) CPMAddPackage( NAME nlohmann_json URL "https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz" ) include(FetchContent) FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/v1.8.0.tar.gz URL_HASH SHA1=9b4302c3d77d7f84ab1a6547d9bcc2f849672e11) FetchContent_MakeAvailable(spdlog) CPMAddPackage( NAME cereal URL https://github.com/USCiLab/cereal/archive/refs/tags/v1.3.2.tar.gz OPTIONS "SKIP_PORTABILITY_TEST ON" "JUST_INSTALL_CEREAL ON" ) add_subdirectory(subprojects/jngl) file(GLOB SRC src/*.cpp src/engine/*.cpp src/gui/*.cpp) add_executable(jntetri ${SRC}) # find_package(Boost COMPONENTS coroutine system thread) -find_package(Boost REQUIRED) +find_package(Boost CONFIG REQUIRED) target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json Boost::boost) set_property(TARGET jntetri PROPERTY CXX_STANDARD 20) if(MSVC) target_compile_definitions(jntetri PRIVATE BOOST_ALL_NO_LIB _WIN32_WINNT=0x0601) elseif(WIN32) target_link_libraries(jntetri PRIVATE ws2_32) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") target_link_options(jntetri PRIVATE --preload-file data) endif()
jhasse/jntetri
a659e085192ef4a37b3b2bc660734824dac8fc87
Remove some warnings unsupported by older compilers (e.g. emscripten)
diff --git a/CMakeLists.txt b/CMakeLists.txt index a5e4acd..d7e6a97 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,63 +1,63 @@ cmake_minimum_required(VERSION 3.15) project(jntetri) if(NOT MSVC) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=implicit-function-declaration") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color -Wall -Wextra -Winit-self -Wpedantic -Wdelete-non-virtual-dtor -Wlogical-op -Wduplicated-cond -Wduplicated-branches") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color -Wall -Wextra -Winit-self -Wpedantic -Wdelete-non-virtual-dtor") # -Wno-implicit-fallthrough', # cereal # -Wno-class-memaccess', # cereal") endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") set(USE_FLAGS "-s USE_SDL=2 -pthread -s USE_PTHREADS=1 -s USE_FREETYPE=1 -s USE_VORBIS=1 -s DISABLE_EXCEPTION_CATCHING=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${USE_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${USE_FLAGS}") string(APPEND CMAKE_EXE_LINKER_FLAGS " ${USE_FLAGS} -s WEBSOCKET_URL=wss://jntetri.boomshine.de -s ASSERTIONS=1 -s FULL_ES3=1 " "--pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/pre.js -lidbfs.js") set(CMAKE_EXECUTABLE_SUFFIX ".html") endif() if (TARGET_WASM) add_compile_options("SHELL:-s USE_PTHREADS") add_link_options("SHELL:-s USE_PTHREADS") endif() include(subprojects/jngl/cmake/CPM.cmake) CPMAddPackage( NAME nlohmann_json URL "https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz" ) include(FetchContent) FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/v1.8.0.tar.gz URL_HASH SHA1=9b4302c3d77d7f84ab1a6547d9bcc2f849672e11) FetchContent_MakeAvailable(spdlog) CPMAddPackage( NAME cereal URL https://github.com/USCiLab/cereal/archive/refs/tags/v1.3.2.tar.gz OPTIONS "SKIP_PORTABILITY_TEST ON" "JUST_INSTALL_CEREAL ON" ) add_subdirectory(subprojects/jngl) file(GLOB SRC src/*.cpp src/engine/*.cpp src/gui/*.cpp) add_executable(jntetri ${SRC}) # find_package(Boost COMPONENTS coroutine system thread) find_package(Boost REQUIRED) target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json Boost::boost) set_property(TARGET jntetri PROPERTY CXX_STANDARD 20) if(MSVC) target_compile_definitions(jntetri PRIVATE BOOST_ALL_NO_LIB _WIN32_WINNT=0x0601) elseif(WIN32) target_link_libraries(jntetri PRIVATE ws2_32) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") target_link_options(jntetri PRIVATE --preload-file data) endif()
jhasse/jntetri
09f1d63ed10247bdc46b057203edfc6dcbea7377
Fix web build: Boost libraries are not really required (yet)
diff --git a/CMakeLists.txt b/CMakeLists.txt index 7793e37..a5e4acd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,62 +1,63 @@ cmake_minimum_required(VERSION 3.15) project(jntetri) if(NOT MSVC) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=implicit-function-declaration") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color -Wall -Wextra -Winit-self -Wpedantic -Wdelete-non-virtual-dtor -Wlogical-op -Wduplicated-cond -Wduplicated-branches") # -Wno-implicit-fallthrough', # cereal # -Wno-class-memaccess', # cereal") endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") set(USE_FLAGS "-s USE_SDL=2 -pthread -s USE_PTHREADS=1 -s USE_FREETYPE=1 -s USE_VORBIS=1 -s DISABLE_EXCEPTION_CATCHING=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${USE_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${USE_FLAGS}") string(APPEND CMAKE_EXE_LINKER_FLAGS " ${USE_FLAGS} -s WEBSOCKET_URL=wss://jntetri.boomshine.de -s ASSERTIONS=1 -s FULL_ES3=1 " "--pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/pre.js -lidbfs.js") set(CMAKE_EXECUTABLE_SUFFIX ".html") endif() if (TARGET_WASM) add_compile_options("SHELL:-s USE_PTHREADS") add_link_options("SHELL:-s USE_PTHREADS") endif() include(subprojects/jngl/cmake/CPM.cmake) CPMAddPackage( NAME nlohmann_json URL "https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz" ) include(FetchContent) FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/v1.8.0.tar.gz URL_HASH SHA1=9b4302c3d77d7f84ab1a6547d9bcc2f849672e11) FetchContent_MakeAvailable(spdlog) CPMAddPackage( NAME cereal URL https://github.com/USCiLab/cereal/archive/refs/tags/v1.3.2.tar.gz OPTIONS "SKIP_PORTABILITY_TEST ON" "JUST_INSTALL_CEREAL ON" ) add_subdirectory(subprojects/jngl) file(GLOB SRC src/*.cpp src/engine/*.cpp src/gui/*.cpp) add_executable(jntetri ${SRC}) -find_package(Boost COMPONENTS coroutine system thread) +# find_package(Boost COMPONENTS coroutine system thread) +find_package(Boost REQUIRED) target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json Boost::boost) set_property(TARGET jntetri PROPERTY CXX_STANDARD 20) if(MSVC) target_compile_definitions(jntetri PRIVATE BOOST_ALL_NO_LIB _WIN32_WINNT=0x0601) elseif(WIN32) target_link_libraries(jntetri PRIVATE ws2_32) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") target_link_options(jntetri PRIVATE --preload-file data) endif()
jhasse/jntetri
f8ece2fc4804204f7d5e17800c106a429810fec6
Support older CMake versions
diff --git a/CMakeLists.txt b/CMakeLists.txt index eeaae7b..7793e37 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,60 +1,62 @@ cmake_minimum_required(VERSION 3.15) project(jntetri) if(NOT MSVC) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=implicit-function-declaration") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color -Wall -Wextra -Winit-self -Wpedantic -Wdelete-non-virtual-dtor -Wlogical-op -Wduplicated-cond -Wduplicated-branches") + # -Wno-implicit-fallthrough', # cereal + # -Wno-class-memaccess', # cereal") endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") set(USE_FLAGS "-s USE_SDL=2 -pthread -s USE_PTHREADS=1 -s USE_FREETYPE=1 -s USE_VORBIS=1 -s DISABLE_EXCEPTION_CATCHING=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${USE_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${USE_FLAGS}") string(APPEND CMAKE_EXE_LINKER_FLAGS " ${USE_FLAGS} -s WEBSOCKET_URL=wss://jntetri.boomshine.de -s ASSERTIONS=1 -s FULL_ES3=1 " - "-s INITIAL_MEMORY=1024MB --pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/pre.js -lidbfs.js") + "--pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/pre.js -lidbfs.js") set(CMAKE_EXECUTABLE_SUFFIX ".html") endif() if (TARGET_WASM) add_compile_options("SHELL:-s USE_PTHREADS") add_link_options("SHELL:-s USE_PTHREADS") endif() include(subprojects/jngl/cmake/CPM.cmake) CPMAddPackage( NAME nlohmann_json URL "https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz" ) include(FetchContent) FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/v1.8.0.tar.gz URL_HASH SHA1=9b4302c3d77d7f84ab1a6547d9bcc2f849672e11) FetchContent_MakeAvailable(spdlog) CPMAddPackage( NAME cereal URL https://github.com/USCiLab/cereal/archive/refs/tags/v1.3.2.tar.gz OPTIONS "SKIP_PORTABILITY_TEST ON" "JUST_INSTALL_CEREAL ON" ) add_subdirectory(subprojects/jngl) file(GLOB SRC src/*.cpp src/engine/*.cpp src/gui/*.cpp) add_executable(jntetri ${SRC}) find_package(Boost COMPONENTS coroutine system thread) -target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json Boost::headers) +target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json Boost::boost) set_property(TARGET jntetri PROPERTY CXX_STANDARD 20) if(MSVC) target_compile_definitions(jntetri PRIVATE BOOST_ALL_NO_LIB _WIN32_WINNT=0x0601) elseif(WIN32) target_link_libraries(jntetri PRIVATE ws2_32) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") target_link_options(jntetri PRIVATE --preload-file data) endif()
jhasse/jntetri
8105e790048a0e54b4c685dc775cb81f346ceba2
Socket::connect: Use lambda instead of boost::bind
diff --git a/src/engine/socket.cpp b/src/engine/socket.cpp index 07c2571..2e83c96 100644 --- a/src/engine/socket.cpp +++ b/src/engine/socket.cpp @@ -1,80 +1,80 @@ #include "socket.hpp" #include "../../server/NetworkConstants.hpp" -#include <iostream> -#include <boost/bind/bind.hpp> #include <boost/asio/co_spawn.hpp> #include <spdlog/spdlog.h> Socket::Socket() : socket_(io_) { } void Socket::step() { io_.poll(); } void Socket::CallbackWrapper(const boost::system::error_code& err, std::function<void()> onSuccess) { if (err) { throw std::runtime_error("socket error"); } boost::asio::co_spawn(io_, [this]() -> boost::asio::awaitable<void> { while (true) { size_t pos = buffer.find('\n'); if (pos == std::string::npos) { std::array<char, 1024> receiveBuffer{}; size_t len = co_await socket_.async_receive(boost::asio::buffer(receiveBuffer), 0, boost::asio::use_awaitable); buffer.append(receiveBuffer.data(), len); continue; } auto package = buffer.substr(0, pos); // spdlog::trace("received `{}`", package); buffer = buffer.substr(pos + 1); onReceiveSuccess(json::parse(package)); } }, boost::asio::detached); onSuccess(); } void Socket::connect(const std::string& server, int port, std::function<void()> onSuccess) { using boost::asio::ip::tcp; #ifndef __EMSCRIPTEN__ auto resolver = std::make_shared<tcp::resolver>(io_); tcp::resolver::query query(server, "http"); resolver->async_resolve(query, [this, port, resolver, onSuccess](const boost::system::error_code& err, tcp::resolver::iterator endpointIterator) { if (err) { std::ostringstream sstream; sstream << "resolve error " << err.value() << " [" << err.category().name() << "]"; throw std::runtime_error(sstream.str()); } tcp::endpoint endpoint(endpointIterator->endpoint().address(), port); - socket_.async_connect( - endpoint, boost::bind(&Socket::CallbackWrapper, this, boost::asio::placeholders::error, onSuccess)); + socket_.async_connect(endpoint, [this, onSuccess](const boost::system::error_code& err) { + CallbackWrapper(err, onSuccess); + }); }); #else tcp::endpoint endpoint(boost::asio::ip::address::from_string(server), port); - socket_.async_connect(endpoint, boost::bind(&Socket::CallbackWrapper, this, - boost::asio::placeholders::error, onSuccess)); + socket_.async_connect(endpoint, [this, onSuccess](const boost::system::error_code& err) { + CallbackWrapper(err, onSuccess); + }); #endif } void Socket::send(const std::string& data, std::function<void()> onSuccess) { spdlog::trace("sending {}", data); auto buf = std::make_unique<std::string>(data + "\n"); auto mutableBuf = boost::asio::buffer(*buf); socket_.async_send(mutableBuf, [this, buf = std::move(buf), onSuccess = std::move(onSuccess)]( const boost::system::error_code& err, size_t) { CallbackWrapper(err, std::move(onSuccess)); }); } void Socket::send(const json& data, std::function<void()> onSuccess) { send(data.dump(), std::move(onSuccess)); } void Socket::receive(std::function<void(json)> onSuccess) { onReceiveSuccess = std::move(onSuccess); }
jhasse/jntetri
3b07d0a982ff16364a4a294ab8f1cf669d5b448a
Clean up PauseMenu a bit
diff --git a/src/pausemenu.cpp b/src/pausemenu.cpp index 6f548aa..a56d274 100644 --- a/src/pausemenu.cpp +++ b/src/pausemenu.cpp @@ -1,42 +1,42 @@ #include "pausemenu.hpp" #include "Game.hpp" #include "engine/fade.hpp" #include "gui/ButtonBox.hpp" #include "menu.hpp" PauseMenu::PauseMenu(std::shared_ptr<Game> game) : work(jngl::getWork()), buttonBox(new ButtonBox), game(std::move(game)) { this->game->SetRotateScreen(false); // Don't rotate the screen so that the buttons work correctly - buttonBox->add("Resume", std::bind(&PauseMenu::Continue, this)); - buttonBox->add("Menu", std::bind(&PauseMenu::QuitToMenu, this)); + buttonBox->add("Resume", [this] { Continue(); }); + buttonBox->add("Menu", [this] { QuitToMenu(); }); if (jngl::canQuit()) { buttonBox->add("Quit", jngl::quit); } addWidget(buttonBox); } void PauseMenu::step() { if (jngl::keyPressed(jngl::key::Escape)) { jngl::setWork(work); } StepWidgets(); game->StepToRotateScreen(); } void PauseMenu::Continue() { jngl::setWork(work); } void PauseMenu::draw() const { game->draw(); DrawWidgets(); } void PauseMenu::QuitToMenu() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void PauseMenu::onQuitEvent() { // Do Nothing } diff --git a/src/pausemenu.hpp b/src/pausemenu.hpp index 7ccdd96..008c9a2 100644 --- a/src/pausemenu.hpp +++ b/src/pausemenu.hpp @@ -1,21 +1,22 @@ #pragma once #include "engine/work.hpp" class ButtonBox; class Game; class PauseMenu : public Work { public: - PauseMenu(std::shared_ptr<Game>); - virtual void step(); - virtual void draw() const; + explicit PauseMenu(std::shared_ptr<Game>); void Continue(); void QuitToMenu() const; - void onQuitEvent(); private: + void step() override; + void draw() const override; + void onQuitEvent() override; + std::shared_ptr<jngl::Work> work; std::shared_ptr<ButtonBox> buttonBox; std::shared_ptr<Game> game; };
jhasse/jntetri
9c9e49a7c97461790e89fbdc59c62be0568297c6
Fix mouse being visible when going to PauseMenu via Escape
diff --git a/src/Game.cpp b/src/Game.cpp index 045ca02..c87b60a 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -1,135 +1,138 @@ #include "Game.hpp" #include "engine/screen.hpp" #include "engine/Options.hpp" #include "gameoverscreen.hpp" #include "pausemenu.hpp" #include "ReplayRecorder.hpp" #include <jngl.hpp> #include <sstream> #include <iomanip> Game::Game(const GameType type, const int seed, const bool replay) : field_(seed, getOptions().startLevel, getOptions().startJunks), type_(type), nextPosition_(field_.GetNextPosition()), oldNextPosition_(nextPosition_), rotateScreen_(false), rotateDegree_(0) { if (!replay) { // Don't record when we're playing back a replay replayRecorder = std::make_unique<ReplayRecorder>(field_, type); } jngl::setMouseVisible(false); } Game::~Game() { jngl::setMouseVisible(true); } void Game::SetRotateScreen(bool rotateScreen) { rotateScreen_ = rotateScreen; } void Game::step() { StepToRotateScreen(); if (field_.GameOver()) { pauseTime_ = jngl::getTime(); jngl::setWork(std::make_shared<GameOverScreen>(this)); } else { - field_.SetPause(false); field_.step(); if (replayRecorder) { replayRecorder->Step(); } if (type_ == GameType::FIFTYLINES && field_.GetLines() >= 50) { field_.setGameOver(true); } } nextPosition_ = field_.GetNextPosition(); oldNextPosition_ = (nextPosition_ - oldNextPosition_) * 0.01 + oldNextPosition_; if (pauseTime_ > 0.0001 && !field_.GameOver()) { pauseTime_ = 0; } - if (jngl::keyPressed('p') || jngl::keyPressed(jngl::key::Escape)) { + if (jngl::keyPressed('p')) { onQuitEvent(); // Pause } } void Game::onQuitEvent() { static double lastPauseTime = 0; if (jngl::getTime() - lastPauseTime > 1) { // Don't allow pausing the game more then one time per second lastPauseTime = pauseTime_ = jngl::getTime(); field_.SetPause(true); jngl::setWork(std::make_shared<PauseMenu>(shared_from_this())); jngl::cancelQuit(); } } void Game::DrawTime(const int x, const int y) const { jngl::print("Time: ", x, y); double time = GetTime(); int minutes = int(time / 60); int seconds = int(time - minutes * 60); std::stringstream sstream; sstream.fill('0'); sstream << minutes << ":" << std::setw(2) << seconds; jngl::print(sstream.str(), 450, y + 100); } void Game::StepToRotateScreen() { if (rotateScreen_ && rotateDegree_ < 90) { rotateDegree_ += (90 - rotateDegree_) * 0.05; } else { rotateDegree_ *= 0.95; } } void Game::draw() const { jngl::pushMatrix(); jngl::rotate(rotateDegree_); jngl::scale(1 + rotateDegree_ / 270); field_.draw(); if (!rotateScreen_) { jngl::setFontColor(0, 0, 0); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(-600, oldNextPosition_); field_.drawNextTetromino(); jngl::popMatrix(); if (type_ == GameType::FIFTYLINES) { DrawTime(450, -500); } else { jngl::print("Score: ", 450, -500); jngl::print(std::to_string(field_.GetScore()), 450, -400); DrawTime(450, 220); } jngl::print("Level: ", 450, -260); jngl::print(std::to_string(field_.GetLevel()), 450, -160); jngl::print("Lines: ", 450, -20); jngl::print(std::to_string(field_.GetLines()), 450, 80); } jngl::popMatrix(); } Field& Game::GetField() { return field_; } double Game::GetTime() const { return field_.getSecondsPlayed(); } bool Game::GameOverAnimationFinished() const { return field_.GameOverAnimationFinished(); } GameType Game::getType() const { return type_; } bool Game::gameOver() const { return field_.GameOver(); } bool Game::isReplay() const { return replayRecorder == nullptr; } + +void Game::onLoad() { + field_.SetPause(false); +} diff --git a/src/Game.hpp b/src/Game.hpp index 3379160..0fb6295 100644 --- a/src/Game.hpp +++ b/src/Game.hpp @@ -1,37 +1,39 @@ #pragma once #include "engine/work.hpp" #include "Field.hpp" #include "gametype.hpp" class ReplayRecorder; class Game : public Work, public std::enable_shared_from_this<Game> { public: Game(GameType, int seed, bool replay); virtual ~Game(); virtual void step(); virtual void draw() const; void onQuitEvent(); Field& GetField(); double GetTime() const; bool GameOverAnimationFinished() const; GameType getType() const; void DrawTime(int x, int y) const; void StepToRotateScreen(); void SetRotateScreen(bool); bool gameOver() const; bool isReplay() const; protected: + void onLoad() override; + Field field_; GameType type_; double nextPosition_; double oldNextPosition_; double pauseTime_ = 0; bool rotateScreen_; double rotateDegree_; /// If we're owned by a ReplayPlayer, this is nullptr std::unique_ptr<ReplayRecorder> replayRecorder; };
jhasse/jntetri
30890356abb8a26d3e3f5bdc34d277a35995bb35
VSCode: Use MSVC and Ninja on Windows
diff --git a/.vscode/build.bat b/.vscode/build.bat new file mode 100644 index 0000000..42f06f2 --- /dev/null +++ b/.vscode/build.bat @@ -0,0 +1,18 @@ +@echo off + +:: see https://blog.pcitron.fr/2022/01/04/dont-use-vcvarsall-vsdevcmd/ +set VSCMD_ARG_HOST_ARCH=x64 +set VSCMD_ARG_TGT_ARCH=x64 +set VSCMD_ARG_APP_PLAT=Desktop +set VSINSTALLDIR=C:\Program Files\Microsoft Visual Studio\2022\Community\ +call "%VSINSTALLDIR%\Common7\Tools\vsdevcmd\core\winsdk.bat" +call "%VSINSTALLDIR%\Common7\Tools\vsdevcmd\ext\cmake.bat" +call "%VSINSTALLDIR%\Common7\Tools\vsdevcmd\ext\vcvars.bat" +if not defined INCLUDE set INCLUDE=%__VSCMD_VCVARS_INCLUDE%%__VSCMD_WINSDK_INCLUDE%%__VSCMD_NETFX_INCLUDE%%INCLUDE% + +if exist build\build.ninja ( + rem file exists +) else ( + cmake -Bbuild -G"Ninja Multi-Config" -DJNGL_VIDEO=0 +) +cmake --build build diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 87a1fe5..6787471 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,54 +1,53 @@ { "version": "2.0.0", "windows": { - "command": "C:\\msys64\\usr\\bin\\bash.exe", - "args": ["-lc", "clear && cd \"${workspaceRoot}\" && ([ -d build ] || cmake -Bbuild -G\"Ninja Multi-Config\" -DCMAKE_BUILD_TYPE=Debug) && ninja -C build | cat"], + "command": ".vscode/build.bat", }, "linux": { "args": ["-lc", "clear && cd \"\"${workspaceRoot}\"\" && ([ -d build ] || cmake -Bbuild -G\"Ninja Multi-Config\" -DCMAKE_BUILD_TYPE=Debug) && ninja -C build && $@"], "command": "/bin/bash" }, "osx": { "args": ["-lc", "clear && cd \"\"${workspaceRoot}\"\" && ([ -d build ] || cmake -Bbuild -G\"Ninja Multi-Config\" -DCMAKE_BUILD_TYPE=Debug) && ninja -C build && $@"], "command": "/bin/bash" }, "options": { "env": { "LANG": "C.UTF-8", "PYTHONUNBUFFERD": "1", "MSYSTEM": "MINGW64" } }, "tasks": [ { "label": "build", "problemMatcher": { "owner": "cpp", "fileLocation": [ "autoDetect", "${workspaceRoot}/build" ], "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error|fatal error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5 } }, "group": { "kind": "build", "isDefault": true } } ], "presentation": { "echo": true, "focus": false, "panel": "shared", "showReuseMessage": true, "clear": false, "revealProblems": "never" } }
jhasse/jntetri
0a1ce3642a676b04274a5b444bebfdde399bd92d
Remove some boost includes
diff --git a/server/Server.cpp b/server/Server.cpp index 3a9109e..b4ca92b 100644 --- a/server/Server.cpp +++ b/server/Server.cpp @@ -1,160 +1,159 @@ #include "Server.hpp" #include "Client.hpp" #include "NetworkConstants.hpp" -#include <boost/bind/bind.hpp> #include <iostream> #include <soci/sqlite3/soci-sqlite3.h> #include <spdlog/spdlog.h> #include <optional> using boost::asio::ip::tcp; Server::Server() : socket(context), acceptor(context, tcp::endpoint(tcp::v4(), JNTETRI_PORT)), timer(context, boost::posix_time::seconds(15)), sql(soci::sqlite3, "jntetri.sqlite") { sql << "CREATE TABLE IF NOT EXISTS users (" "username VARCHAR(80) UNIQUE NOT NULL," "password VARCHAR(256) NOT NULL)"; timer.async_wait([this](const auto& e) { printStats(e); }); } Server::~Server() { socket.close(); } void Server::run() { boost::asio::spawn(context, [this](boost::asio::yield_context yield) { doAccept(yield); }); spdlog::info("start"); context.run(); } void Server::doAccept(boost::asio::yield_context yield) { while (true) { boost::asio::ip::tcp::socket socket(context); acceptor.async_accept(socket, yield); auto client = std::make_shared<Client>(*this, std::move(socket)); spdlog::info("new connection"); clients.emplace_back(client); boost::asio::spawn(context, [this, client](boost::asio::yield_context yield) { try { client->run(yield); } catch (std::exception& e) { client->log().error(e.what()); } client->log().info("disconnected"); { std::lock_guard<std::mutex> lock(matchmakingMutex); if (const auto it = std::find(matchmaking.begin(), matchmaking.end(), client); it != matchmaking.end()) { matchmaking.erase(it); } } clients.erase(std::find(clients.begin(), clients.end(), client)); if (client->isLoggedIn()) { addChatLine(yield, fmt::format("{} left.", client->getUsername())); } }); } } void Server::addChatLine(boost::asio::yield_context yield, std::string line) { chatText += line; for (const auto& client : clients) { if (client->isLoggedIn()) { client->sendChatLine(yield, line); } } } LoginState Server::checkLogin(std::string username, std::string password) { soci::rowset<soci::row> rs = (sql.prepare << "select password from users where username = :username", soci::use(username, "username")); std::optional<std::string> realPassword; for (const auto& row : rs) { assert(!realPassword); realPassword = row.get<std::string>(0); } if (realPassword) { if (*realPassword == password) { // kick all other devices of this user: for (const auto& client : clients) { if (client->isLoggedIn() && client->getUsername() == username) { client->kick("Someone logged in from another device."); } } return LoginState::PasswordOK; } return LoginState::PasswordWrong; } return LoginState::UserDoesNotExist; } bool Server::registerUser(std::string username, std::string password) { try { sql << "insert into users (username, password) values(:username, :password)", soci::use(username), soci::use(password); } catch (soci::soci_error& e) { spdlog::error(e.what()); return false; } return true; } std::string Server::createAnonymousUser() { for (int i = 0; i < 10; ++i) { std::string name = "user" + std::to_string(rand() % 999999); if (registerUser(name, "")) { return name; } // already exists? Maybe we can login without a password: switch (checkLogin(name, "")) { case LoginState::PasswordWrong: break; case LoginState::UserDoesNotExist: assert(false); break; case LoginState::PasswordOK: return name; } } throw std::runtime_error("Couldn't generate a random username!"); } void Server::startMatchmaking(boost::asio::yield_context yield, std::shared_ptr<Client> client) { std::lock_guard<std::mutex> lock(matchmakingMutex); if (matchmaking.empty()) { matchmaking.emplace_back(client); addChatLine(yield, client->getUsername() + " started matchmaking."); } else { for (const auto& existingClient : matchmaking) { if (existingClient == client) { return; // somehow matchmaking was requested twice } } // Found opponent. Let's send p back to both clients so that the game starts. matchmaking.back()->setOpponent(client); client->setOpponent(matchmaking.back()); spdlog::info("matching '{}' and '{}'", matchmaking.back()->getUsername(), client->getUsername()); const int32_t seed = rand(); matchmaking.back()->sendStartGame(yield, seed); client->sendStartGame(yield, seed); matchmaking.pop_back(); } } std::string Server::loginAndGetWelcomeMessage(boost::asio::yield_context yield, const std::string& username) { addChatLine(yield, fmt::format("{} joined.", username)); size_t loggedIn = std::count_if(clients.begin(), clients.end(), [](const auto& client) { return client->isLoggedIn(); }) + 1 /* the current user doesn't count yet*/; return fmt::format("{} user{} online.", loggedIn, loggedIn == 1 ? "" : "s"); } void Server::printStats(const boost::system::error_code&) { spdlog::trace("connected clients: {}", clients.size()); timer.expires_from_now(boost::posix_time::seconds(15)); timer.async_wait([this](const auto& e) { printStats(e); }); } diff --git a/src/Login.cpp b/src/Login.cpp index 79e5374..6c2093e 100644 --- a/src/Login.cpp +++ b/src/Login.cpp @@ -1,185 +1,184 @@ #include "Login.hpp" #include "../server/NetworkConstants.hpp" #include "engine/screen.hpp" #include "engine/fade.hpp" #include "engine/Options.hpp" #include "gui/Button.hpp" #include "lobby.hpp" #include <jngl.hpp> #include <boost/bind/bind.hpp> -#include <boost/lexical_cast.hpp> #include <spdlog/spdlog.h> #ifdef __EMSCRIPTEN__ const std::string Login::server_("89.58.48.219"); // boomshine.de const int Login::port_ = 9999; #else // const std::string Login::server_("127.0.0.1"); const std::string Login::server_("89.58.48.219"); // boomshine.de // const std::string Login::server_("85.214.187.23"); // babynamensuche.de const int Login::port_ = 7070; #endif Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu, bool quickLogin) : menu(multiplayerMenu), text_("connecting ..."), cancel_("Cancel", [this]() { OnCancel(); }), socket_(new Socket), quickLogin(quickLogin) { spdlog::info("Connecting to {}:{}", server_, port_); try { socket_->connect(server_, port_, [this]() { HandleConnect(); }); } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.setCenter(0, 200); } void Login::HandleConnect() { text_ = "sending ..."; spdlog::info("Sending protocol version {}", PROTOCOL_VERSION); socket_->send(std::to_string(PROTOCOL_VERSION), [this]() { ProtocolCheck1(); }); } void Login::ProtocolCheck1() { text_ = "receiving ..."; spdlog::info("Waiting for server accept connection"); socket_->receive([this](json data) { ProtocolCheck2(std::move(data)); }); } void Login::ProtocolCheck2(json temp) { if (temp["type"] != "ok") { text_ = "Error: "; if (const std::string msg = temp["msg"]; !msg.empty()) { text_ += msg; } else { text_ += temp.dump(); } OnError(); } else { if (menu->GetName().empty()) { if (!menu->GetPassword().empty()) { text_ = "Name must not be empty!"; return OnError(); } socket_->send(json{ { "type", "login_anonymous" } }, [this]() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; }); } else { socket_->send(json{ { "type", "login" }, { "name", menu->GetName() }, { "password", menu->GetPassword() } }, [this]() { HandleLogin1(); }); } } } void Login::HandleLogin1() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; } void Login::HandleLogin2(json temp) { if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else if (temp["type"] == "unknown name") { text_ = "No user with this name found.\nDo you want to register yourself?"; cancel_.setCenter(-350, 280); cancel_.SetText("No"); Button* yes = new Button("Yes", boost::bind(&Login::Register, this)); yes->setCenter(350, 280); addWidget(std::shared_ptr<Widget>(yes)); } else if (temp["type"] == "wrong password") { text_ = "The password you've entered\nis wrong. Please try again."; OnError(); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::Register() { json j{ { "type", "register" }, { "name", menu->GetName() }, { "password", menu->GetPassword() } }; spdlog::info("Sending: {}", j.dump()); socket_->send(j, boost::bind(&Login::HandleRegister1, this)); cancel_.setCenter(0, 200); cancel_.SetText("Cancel"); widgets_.clear(); // FIXME: Implement RemoveWidget function } void Login::HandleRegister1() { socket_->receive([this](json temp) { HandleRegister2(std::move(temp)); }); text_ = "please wait ..."; } void Login::HandleRegister2(json temp) { spdlog::debug("HandleRegister2"); if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::step() { try { if (socket_) { socket_->step(); } } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.step(); StepWidgets(); } void Login::GoToLobby(std::string username) { getOptions().lastLoginName = std::move(username); getOptions().Save(); jngl::setWork(std::make_shared<Fade>( std::make_shared<Lobby>(std::move(socket_), quickLogin))); } void Login::draw() const { menu->draw(); jngl::setColor(255, 255, 255, 220); jngl::drawRect(-jngl::getScreenWidth() / 2, -jngl::getScreenHeight() / 2, jngl::getScreenWidth(), jngl::getScreenHeight()); jngl::setFontColor(0, 0, 0); GetScreen().printCentered(text_, { 0, -150 }); cancel_.draw(); DrawWidgets(); } void Login::OnCancel() { jngl::setWork(menu); } void Login::OnError() { // hacked together algorithm to word wrap long error messages: size_t pos = 42; while (jngl::getTextWidth(text_) > jngl::getScreenWidth() && pos < text_.size()) { size_t i = pos; while (i > 0 && text_[i - 1] != ' ') { if (text_[i] == '\n') { i = pos; break; } --i; } text_.insert(text_.begin() + i, '\n'); pos += 42; } cancel_.SetText("OK"); cancel_.setFocus(true); } diff --git a/src/engine/socket.hpp b/src/engine/socket.hpp index 46188b8..3efad7d 100644 --- a/src/engine/socket.hpp +++ b/src/engine/socket.hpp @@ -1,31 +1,30 @@ #pragma once -#include <boost/array.hpp> #include <boost/asio.hpp> #include <functional> #include <nlohmann/json.hpp> using nlohmann::json; class Socket { public: Socket(); Socket(const Socket&) = delete; Socket(Socket&&) = delete; Socket& operator=(const Socket&) = delete; Socket& operator=(Socket&&) = delete; void connect(const std::string& server, int port, std::function<void()> onSuccess); void send(const std::string& data, std::function<void()> onSuccess); void send(const json& data, std::function<void()> onSuccess); void receive(std::function<void(json)> onSuccess); void step(); private: boost::asio::io_service io_; boost::asio::ip::tcp::socket socket_; void CallbackWrapper(const boost::system::error_code& err, std::function<void()> onSuccess); std::string buffer; std::array<char, 1024> receiveBuffer; std::function<void(json)> onReceiveSuccess; };
jhasse/jntetri
b07e8540227d42a44f63c094ca837da0a740e1da
CMake: Add Boost::headers
diff --git a/CMakeLists.txt b/CMakeLists.txt index 3c8df75..eeaae7b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,60 +1,60 @@ cmake_minimum_required(VERSION 3.15) project(jntetri) if(NOT MSVC) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=implicit-function-declaration") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color") endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") set(USE_FLAGS "-s USE_SDL=2 -pthread -s USE_PTHREADS=1 -s USE_FREETYPE=1 -s USE_VORBIS=1 -s DISABLE_EXCEPTION_CATCHING=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${USE_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${USE_FLAGS}") string(APPEND CMAKE_EXE_LINKER_FLAGS " ${USE_FLAGS} -s WEBSOCKET_URL=wss://jntetri.boomshine.de -s ASSERTIONS=1 -s FULL_ES3=1 " "-s INITIAL_MEMORY=1024MB --pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/pre.js -lidbfs.js") set(CMAKE_EXECUTABLE_SUFFIX ".html") endif() if (TARGET_WASM) add_compile_options("SHELL:-s USE_PTHREADS") add_link_options("SHELL:-s USE_PTHREADS") endif() include(subprojects/jngl/cmake/CPM.cmake) CPMAddPackage( NAME nlohmann_json URL "https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz" ) include(FetchContent) FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/v1.8.0.tar.gz URL_HASH SHA1=9b4302c3d77d7f84ab1a6547d9bcc2f849672e11) FetchContent_MakeAvailable(spdlog) CPMAddPackage( NAME cereal URL https://github.com/USCiLab/cereal/archive/refs/tags/v1.3.2.tar.gz OPTIONS "SKIP_PORTABILITY_TEST ON" "JUST_INSTALL_CEREAL ON" ) add_subdirectory(subprojects/jngl) file(GLOB SRC src/*.cpp src/engine/*.cpp src/gui/*.cpp) add_executable(jntetri ${SRC}) find_package(Boost COMPONENTS coroutine system thread) -target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json) +target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json Boost::headers) set_property(TARGET jntetri PROPERTY CXX_STANDARD 20) if(MSVC) target_compile_definitions(jntetri PRIVATE BOOST_ALL_NO_LIB _WIN32_WINNT=0x0601) elseif(WIN32) target_link_libraries(jntetri PRIVATE ws2_32) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") target_link_options(jntetri PRIVATE --preload-file data) endif()
jhasse/jntetri
dfc2a014ec67523b3ddf102bcded9f46deeb21e5
VSCode: Use Ninja Multi-Config
diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 9ed181a..87a1fe5 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,54 +1,54 @@ { "version": "2.0.0", "windows": { "command": "C:\\msys64\\usr\\bin\\bash.exe", - "args": ["-lc", "clear && cd \"${workspaceRoot}\" && ([ -d build ] || cmake -Bbuild -GNinja -DCMAKE_BUILD_TYPE=Debug) && ninja -C build | cat"], + "args": ["-lc", "clear && cd \"${workspaceRoot}\" && ([ -d build ] || cmake -Bbuild -G\"Ninja Multi-Config\" -DCMAKE_BUILD_TYPE=Debug) && ninja -C build | cat"], }, "linux": { - "args": ["-lc", "clear && cd \"\"${workspaceRoot}\"\" && ([ -d build ] || cmake -Bbuild -GNinja -DCMAKE_BUILD_TYPE=Debug) && ninja -C build && $@"], + "args": ["-lc", "clear && cd \"\"${workspaceRoot}\"\" && ([ -d build ] || cmake -Bbuild -G\"Ninja Multi-Config\" -DCMAKE_BUILD_TYPE=Debug) && ninja -C build && $@"], "command": "/bin/bash" }, "osx": { - "args": ["-lc", "clear && cd \"\"${workspaceRoot}\"\" && ([ -d build ] || cmake -Bbuild -GNinja -DCMAKE_BUILD_TYPE=Debug) && ninja -C build && $@"], + "args": ["-lc", "clear && cd \"\"${workspaceRoot}\"\" && ([ -d build ] || cmake -Bbuild -G\"Ninja Multi-Config\" -DCMAKE_BUILD_TYPE=Debug) && ninja -C build && $@"], "command": "/bin/bash" }, "options": { "env": { "LANG": "C.UTF-8", "PYTHONUNBUFFERD": "1", "MSYSTEM": "MINGW64" } }, "tasks": [ { "label": "build", "problemMatcher": { "owner": "cpp", "fileLocation": [ "autoDetect", "${workspaceRoot}/build" ], "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error|fatal error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5 } }, "group": { "kind": "build", "isDefault": true } } ], "presentation": { "echo": true, "focus": false, "panel": "shared", "showReuseMessage": true, "clear": false, "revealProblems": "never" } }
jhasse/jntetri
fac30417722b040b8e12ad098babad296ac67841
Reduce boost usage
diff --git a/src/Field.hpp b/src/Field.hpp index 095cbca..3dd30a9 100644 --- a/src/Field.hpp +++ b/src/Field.hpp @@ -1,94 +1,97 @@ #pragma once #include "Block.hpp" #include "DesyncInfo.hpp" #include "tetromino.hpp" #include "explosion.hpp" #include "control.hpp" #include <vector> #include <random> #include <ctime> -#include <boost/noncopyable.hpp> #include <memory> #include <optional> -class Field : boost::noncopyable { +class Field { public: Field(int seed, int level, uint32_t startJunks); + Field(const Field&) = delete; + Field(Field&&) = delete; + Field& operator=(const Field&) = delete; + Field& operator=(Field&&) = delete; void step(); void draw() const; void DrawBlock(int x, int y) const; void AddBlock(const Block&); [[nodiscard]] jngl::Vec2 indexToPixel(double x, double y) const; /// y coordinate in dp of the bottom double getBottomY() const; int getBlockSize() const; Block* getBlock(int x, int y); bool checkCollision(int x, int y) const; void NewTetromino(); void removeLine(int y, int numberOfLines); void setGameOver(bool); bool GameOver() const; int GetScore() const; int GetLines() const; int GetLevel() const; int GetNextPosition() const; void drawNextTetromino() const; void SetPause(bool pause); /// returns true when there are network issues bool desync() const; /// the function will be called to check if there's a network desync and the game should be /// paused void setCheckDesync(std::function<bool()>); void onUserQuit(std::function<void()>); bool GameOverAnimationFinished() const; void setControl(Control*); Control& getControl() const; unsigned int getRandom(); int getRandomSeed() const; int getLinesCleared() const; void addJunk(int nr); double getSecondsPlayed() const; private: void CheckLines(); void ResetCounter(); std::vector<Block> blocks_; std::vector<Explosion> explosions_; std::shared_ptr<Tetromino> nextTetromino_; std::shared_ptr<Tetromino> tetromino_; const static int width_; const static int height_; const int blockSize_; int counter_; bool gameOver_; int score_; int level_; int lines; int maxY; bool pause_; /// >0 when there are network issues i.e. control_->step() hasn't returned any data int stepsWithoutPackage = 0; bool delay_; std::shared_ptr<Control> control_; bool downKeyReleased_; std::mt19937 random; int randomSeed; int linesCleared; double secondsPlayed = 0; /// If set, we force-pause the game when it returns true std::function<bool()> checkDesync; std::optional<DesyncInfo> desyncInfo; std::function<void()> onUserQuitCallback; }; diff --git a/src/Game.cpp b/src/Game.cpp index ccc7b8d..045ca02 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -1,136 +1,135 @@ #include "Game.hpp" #include "engine/screen.hpp" #include "engine/Options.hpp" #include "gameoverscreen.hpp" #include "pausemenu.hpp" #include "ReplayRecorder.hpp" #include <jngl.hpp> #include <sstream> #include <iomanip> -#include <boost/lexical_cast.hpp> Game::Game(const GameType type, const int seed, const bool replay) : field_(seed, getOptions().startLevel, getOptions().startJunks), type_(type), nextPosition_(field_.GetNextPosition()), oldNextPosition_(nextPosition_), rotateScreen_(false), rotateDegree_(0) { if (!replay) { // Don't record when we're playing back a replay replayRecorder = std::make_unique<ReplayRecorder>(field_, type); } jngl::setMouseVisible(false); } Game::~Game() { jngl::setMouseVisible(true); } void Game::SetRotateScreen(bool rotateScreen) { rotateScreen_ = rotateScreen; } void Game::step() { StepToRotateScreen(); if (field_.GameOver()) { pauseTime_ = jngl::getTime(); jngl::setWork(std::make_shared<GameOverScreen>(this)); } else { field_.SetPause(false); field_.step(); if (replayRecorder) { replayRecorder->Step(); } if (type_ == GameType::FIFTYLINES && field_.GetLines() >= 50) { field_.setGameOver(true); } } nextPosition_ = field_.GetNextPosition(); oldNextPosition_ = (nextPosition_ - oldNextPosition_) * 0.01 + oldNextPosition_; if (pauseTime_ > 0.0001 && !field_.GameOver()) { pauseTime_ = 0; } if (jngl::keyPressed('p') || jngl::keyPressed(jngl::key::Escape)) { onQuitEvent(); // Pause } } void Game::onQuitEvent() { static double lastPauseTime = 0; if (jngl::getTime() - lastPauseTime > 1) { // Don't allow pausing the game more then one time per second lastPauseTime = pauseTime_ = jngl::getTime(); field_.SetPause(true); jngl::setWork(std::make_shared<PauseMenu>(shared_from_this())); jngl::cancelQuit(); } } void Game::DrawTime(const int x, const int y) const { jngl::print("Time: ", x, y); double time = GetTime(); int minutes = int(time / 60); int seconds = int(time - minutes * 60); std::stringstream sstream; sstream.fill('0'); sstream << minutes << ":" << std::setw(2) << seconds; jngl::print(sstream.str(), 450, y + 100); } void Game::StepToRotateScreen() { if (rotateScreen_ && rotateDegree_ < 90) { rotateDegree_ += (90 - rotateDegree_) * 0.05; } else { rotateDegree_ *= 0.95; } } void Game::draw() const { jngl::pushMatrix(); jngl::rotate(rotateDegree_); jngl::scale(1 + rotateDegree_ / 270); field_.draw(); if (!rotateScreen_) { jngl::setFontColor(0, 0, 0); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(-600, oldNextPosition_); field_.drawNextTetromino(); jngl::popMatrix(); if (type_ == GameType::FIFTYLINES) { DrawTime(450, -500); } else { jngl::print("Score: ", 450, -500); jngl::print(std::to_string(field_.GetScore()), 450, -400); DrawTime(450, 220); } jngl::print("Level: ", 450, -260); jngl::print(std::to_string(field_.GetLevel()), 450, -160); jngl::print("Lines: ", 450, -20); jngl::print(std::to_string(field_.GetLines()), 450, 80); } jngl::popMatrix(); } Field& Game::GetField() { return field_; } double Game::GetTime() const { return field_.getSecondsPlayed(); } bool Game::GameOverAnimationFinished() const { return field_.GameOverAnimationFinished(); } GameType Game::getType() const { return type_; } bool Game::gameOver() const { return field_.GameOver(); } bool Game::isReplay() const { return replayRecorder == nullptr; } diff --git a/src/ReplayPlayer.hpp b/src/ReplayPlayer.hpp index 4759dce..af1e31b 100644 --- a/src/ReplayPlayer.hpp +++ b/src/ReplayPlayer.hpp @@ -1,21 +1,24 @@ #pragma once #include "engine/work.hpp" #include <memory> -#include <boost/noncopyable.hpp> #include <fstream> class Game; -class ReplayPlayer : public Work, boost::noncopyable { +class ReplayPlayer : public Work { public: ReplayPlayer(const std::string& filename); + ReplayPlayer(const ReplayPlayer&) = delete; + ReplayPlayer(ReplayPlayer&&) = delete; + ReplayPlayer& operator=(const ReplayPlayer&) = delete; + ReplayPlayer& operator=(ReplayPlayer&&) = delete; ~ReplayPlayer(); void step(); void draw() const; private: std::ifstream fin_; std::shared_ptr<Game> game_; int oldStartLevel, oldStartJunk; }; diff --git a/src/engine/resizegraphics.cpp b/src/engine/resizegraphics.cpp index ee96d7b..4a68b6f 100644 --- a/src/engine/resizegraphics.cpp +++ b/src/engine/resizegraphics.cpp @@ -1,50 +1,49 @@ #include "resizegraphics.hpp" #include "paths.hpp" #include <jngl.hpp> -#include <boost/lexical_cast.hpp> void ScanPath(fs::path path, std::deque<std::string>& filesToResize) { fs::directory_iterator end; for (fs::directory_iterator it(path); it != end; ++it) { if (fs::is_directory(it->status())) { ScanPath(it->path(), filesToResize); } else { std::string file = it->path().string(); const std::string extension = ".webp"; if (file.substr(file.size() - extension.size()) == extension) { filesToResize.push_back(std::string(it->path().string()).erase(0, jngl::getPrefix().size())); } } } } ResizeGraphics::ResizeGraphics() { jngl::setScaleFactor(static_cast<double>(jngl::getWindowHeight()) / 1200.); ScanPath(jngl::getPrefix() + "gfx", filesToResize_); } ResizeGraphics::~ResizeGraphics() { } bool ResizeGraphics::isFinished(float& percentage) { if (filesToResize_.empty()) { return true; } static size_t numberOfImages = filesToResize_.size(); percentage = float(100 - filesToResize_.size() * 100 / numberOfImages); // Don't do anything in the first frame in order to draw the loading screen for the first time static bool firstFrame = true; if (firstFrame) { firstFrame = false; return false; } std::string newFilename = filesToResize_[0]; jngl::load(newFilename.substr(0, newFilename.size()-5)); filesToResize_.pop_front(); return false; } diff --git a/src/engine/socket.hpp b/src/engine/socket.hpp index 99345b6..46188b8 100644 --- a/src/engine/socket.hpp +++ b/src/engine/socket.hpp @@ -1,28 +1,31 @@ #pragma once -#include <boost/noncopyable.hpp> -#include <boost/asio.hpp> #include <boost/array.hpp> +#include <boost/asio.hpp> #include <functional> #include <nlohmann/json.hpp> using nlohmann::json; -class Socket : boost::noncopyable { +class Socket { public: Socket(); + Socket(const Socket&) = delete; + Socket(Socket&&) = delete; + Socket& operator=(const Socket&) = delete; + Socket& operator=(Socket&&) = delete; void connect(const std::string& server, int port, std::function<void()> onSuccess); void send(const std::string& data, std::function<void()> onSuccess); void send(const json& data, std::function<void()> onSuccess); void receive(std::function<void(json)> onSuccess); void step(); private: boost::asio::io_service io_; boost::asio::ip::tcp::socket socket_; void CallbackWrapper(const boost::system::error_code& err, std::function<void()> onSuccess); std::string buffer; std::array<char, 1024> receiveBuffer; std::function<void(json)> onReceiveSuccess; }; diff --git a/src/gameoverscreen.hpp b/src/gameoverscreen.hpp index 36cb7d6..b859a8b 100644 --- a/src/gameoverscreen.hpp +++ b/src/gameoverscreen.hpp @@ -1,29 +1,27 @@ #pragma once #include "engine/work.hpp" #include "gui/input.hpp" #include "highscore.hpp" -#include <boost/shared_ptr.hpp> - namespace jngl { class Work; } class Game; class GameOverScreen : public Work { public: GameOverScreen(Game*); void step(); void draw() const; void onQuitEvent(); private: bool isHighscore() const; Game* const game_; int blink_; Data data_; Highscore highscore_; std::shared_ptr<Input> input_; std::shared_ptr<jngl::Work> work_; }; diff --git a/src/highscore.hpp b/src/highscore.hpp index e3dba4d..3c2f50a 100644 --- a/src/highscore.hpp +++ b/src/highscore.hpp @@ -1,31 +1,31 @@ #pragma once #include "gametype.hpp" #include <list> +#include <memory> #include <string> -#include <boost/shared_ptr.hpp> struct Data { Data(); int score; double time; std::string name; }; bool operator==(const Data& a, const Data& b); class Highscore { public: Highscore(GameType type); bool isHighscore(Data data) const; void draw() const; void Add(Data); void save() const; void Blink(Data); private: std::list<Data> highscores_; GameType type_; std::string filename_; std::shared_ptr<Data> blink_; };
jhasse/jntetri
714b898569d12687822ff0a42da92125d29db309
Use CPM.cmake for cereal
diff --git a/CMakeLists.txt b/CMakeLists.txt index 15db393..3c8df75 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,62 +1,60 @@ cmake_minimum_required(VERSION 3.15) project(jntetri) if(NOT MSVC) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=implicit-function-declaration") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color") endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") set(USE_FLAGS "-s USE_SDL=2 -pthread -s USE_PTHREADS=1 -s USE_FREETYPE=1 -s USE_VORBIS=1 -s DISABLE_EXCEPTION_CATCHING=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${USE_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${USE_FLAGS}") string(APPEND CMAKE_EXE_LINKER_FLAGS " ${USE_FLAGS} -s WEBSOCKET_URL=wss://jntetri.boomshine.de -s ASSERTIONS=1 -s FULL_ES3=1 " "-s INITIAL_MEMORY=1024MB --pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/pre.js -lidbfs.js") set(CMAKE_EXECUTABLE_SUFFIX ".html") endif() if (TARGET_WASM) add_compile_options("SHELL:-s USE_PTHREADS") add_link_options("SHELL:-s USE_PTHREADS") endif() include(subprojects/jngl/cmake/CPM.cmake) CPMAddPackage( NAME nlohmann_json URL "https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz" ) include(FetchContent) FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/v1.8.0.tar.gz URL_HASH SHA1=9b4302c3d77d7f84ab1a6547d9bcc2f849672e11) FetchContent_MakeAvailable(spdlog) -FetchContent_Declare(cereal - GIT_REPOSITORY https://github.com/USCiLab/cereal.git - GIT_TAG 64f50dbd5cecdaba785217e2b0aeea3a4f1cdfab) -set(SKIP_PERFORMANCE_COMPARISON ON CACHE BOOL "Skip building performance comparison (requires boost)" FORCE) -set(SKIP_PORTABILITY_TEST ON CACHE BOOL "Skip portability (32 bit) tests" FORCE) -set(WITH_WERROR OFF CACHE BOOL "Compile with '-Werror' C++ compiler flag" FORCE) -FetchContent_MakeAvailable(cereal) +CPMAddPackage( + NAME cereal + URL https://github.com/USCiLab/cereal/archive/refs/tags/v1.3.2.tar.gz + OPTIONS "SKIP_PORTABILITY_TEST ON" "JUST_INSTALL_CEREAL ON" +) add_subdirectory(subprojects/jngl) file(GLOB SRC src/*.cpp src/engine/*.cpp src/gui/*.cpp) add_executable(jntetri ${SRC}) find_package(Boost COMPONENTS coroutine system thread) target_link_libraries(jntetri PRIVATE cereal jngl spdlog nlohmann_json::nlohmann_json) set_property(TARGET jntetri PROPERTY CXX_STANDARD 20) if(MSVC) target_compile_definitions(jntetri PRIVATE BOOST_ALL_NO_LIB _WIN32_WINNT=0x0601) elseif(WIN32) target_link_libraries(jntetri PRIVATE ws2_32) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") target_link_options(jntetri PRIVATE --preload-file data) endif()
jhasse/jntetri
ec34f2bb1847bc95e84f641282ef142a00216dcf
GitLab CI: Use the latest working version of emsdk
diff --git a/.gitignore b/.gitignore index 4af6ab9..98d0f9b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,28 +1,31 @@ /build*/ .DS_Store .sconsign.dblite bin/ *.sublime-workspace obj/ msi/*.wixobj msi/*.wixpdb msi/JNTETRI.msi msi/data.wxs /JNTETRI.opensdf /.cache/ # Visual Studio *.sdf *.v12.suo .vs/ Debug/ Release/ packages/ # Visual Studio Code .browse.VC.db /.vscode/cquery* /.ccls-cache/ /compile_commands.json /.clangd/ + +# GitLab CI +/.gitlab-ci-local/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 779403f..918a353 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,72 +1,72 @@ image: fedora:39 linux: stage: build script: - dnf install -y git gcc-c++ fontconfig-devel freetype-devel libvorbis-devel libepoxy-devel libwebp-devel boost-python3-devel python3-devel cmake ninja-build SDL2-devel libatomic - cmake -Bbuild -GNinja - ninja -C build server: image: ubuntu:20.04 stage: build script: - apt-get update && apt-get install -y cmake ninja-build libsoci-dev libsqlite3-dev g++ git libboost-system-dev libboost-coroutine-dev - cd server - cmake -Bbuild -GNinja - cmake --build build web: - image: emscripten/emsdk + image: emscripten/emsdk:3.1.61 stage: build script: - apt-get update && apt-get install -y ninja-build - cd /tmp - curl --silent -O -L https://boostorg.jfrog.io/artifactory/main/release/1.82.0/source/boost_1_82_0.tar.bz2 - tar --wildcards -xf *.tar.bz2 'boost_1_*_0/boost' - cd - - emcmake cmake -GNinja -Bbuild-web -DCMAKE_BUILD_TYPE=Release -DJNGL_VIDEO=0 -DBoost_INCLUDE_DIR=/tmp/boost_1_82_0 - mv data/ build-web/ - ninja -Cbuild-web jntetri artifacts: paths: - build-web/ docker-build: image: docker:latest stage: build services: - docker:dind before_script: - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY # Default branch leaves tag empty (= latest tag) # All other branches are tagged with the escaped branch name (commit ref slug) script: - | if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then tag="" echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'" else tag=":$CI_COMMIT_REF_SLUG" echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag" fi - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" web - docker push "$CI_REGISTRY_IMAGE${tag}" pages: stage: deploy dependencies: - web script: - mv build-web public - mv web/index.html public/ artifacts: paths: - public only: - master variables: CLICOLOR_FORCE: "1" GIT_SUBMODULE_STRATEGY: recursive DEBIAN_FRONTEND: noninteractive
jhasse/jntetri
6ab4695313f452011bef65a218046f76a10271f6
Remove unused Screen::DrawCentered(const std::string& filename, const Vector2d& position)
diff --git a/src/engine/screen.cpp b/src/engine/screen.cpp index 3b7bcaa..0b53551 100644 --- a/src/engine/screen.cpp +++ b/src/engine/screen.cpp @@ -1,27 +1,22 @@ #include "screen.hpp" #include "paths.hpp" #include <jngl.hpp> void Screen::DrawCentered(const std::string& filename, const double x, const double y) { const std::string filepath = "gfx/" + filename; jngl::draw(filepath, x - jngl::getWidth(filepath) / 2.0, y - jngl::getHeight(filepath) / 2.0); } -void Screen::DrawCentered(const std::string& filename, const Vector2d& position) -{ - GetScreen().DrawCentered(filename, position.X(), position.Y()); -} - Screen& GetScreen() { return *Screen::handle(); } void Screen::printCentered(const std::string& text, const jngl::Vec2 center) { jngl::print(text, static_cast<int>((center.x - jngl::getTextWidth(text) / 2)), static_cast<int>(center.y) - jngl::getFontSize() / 2); } diff --git a/src/engine/screen.hpp b/src/engine/screen.hpp index 0f23af8..fd24ecb 100644 --- a/src/engine/screen.hpp +++ b/src/engine/screen.hpp @@ -1,16 +1,14 @@ #pragma once #include "singleton.hpp" -#include "vector2d.hpp" #include <jngl/Vec2.hpp> #include <string> class Screen : public Singleton<Screen> { public: void DrawCentered(const std::string& filename, double x, double y); - void DrawCentered(const std::string& filename, const Vector2d& position); void printCentered(const std::string& text, jngl::Vec2); }; Screen& GetScreen(); diff --git a/src/gui/chooser.hpp b/src/gui/chooser.hpp index f6fef5a..404eece 100644 --- a/src/gui/chooser.hpp +++ b/src/gui/chooser.hpp @@ -1,24 +1,24 @@ #pragma once #include "Button.hpp" #include "widget.hpp" #include <list> class Chooser : public Widget { public: Chooser(int x, int y); void step() override; void draw() const override; int GetValue() const; void AddValue(int); void Previous(); void Next(); private: - typedef std::list<int> ArrayType; + using ArrayType = std::list<int>; ArrayType values_; ArrayType::const_iterator activeValue_; Button previous_; Button next_; std::string sprite_; };
jhasse/jntetri
2f329040ec1b6fffe09c3455b4c21389f974e637
Simplify sprite loading mechanism
diff --git a/data/gfx/x1200/block.webp b/data/gfx/block.webp similarity index 100% rename from data/gfx/x1200/block.webp rename to data/gfx/block.webp diff --git a/data/gfx/x1200/box.webp b/data/gfx/box.webp similarity index 100% rename from data/gfx/x1200/box.webp rename to data/gfx/box.webp diff --git a/data/gfx/x1200/button.webp b/data/gfx/button.webp similarity index 100% rename from data/gfx/x1200/button.webp rename to data/gfx/button.webp diff --git a/data/gfx/x1200/button_clicked.webp b/data/gfx/button_clicked.webp similarity index 100% rename from data/gfx/x1200/button_clicked.webp rename to data/gfx/button_clicked.webp diff --git a/data/gfx/x1200/button_over.webp b/data/gfx/button_over.webp similarity index 100% rename from data/gfx/x1200/button_over.webp rename to data/gfx/button_over.webp diff --git a/data/gfx/x1200/chooser.webp b/data/gfx/chooser.webp similarity index 100% rename from data/gfx/x1200/chooser.webp rename to data/gfx/chooser.webp diff --git a/data/gfx/x1200/chooser_left.webp b/data/gfx/chooser_left.webp similarity index 100% rename from data/gfx/x1200/chooser_left.webp rename to data/gfx/chooser_left.webp diff --git a/data/gfx/x1200/chooser_left_over.webp b/data/gfx/chooser_left_over.webp similarity index 100% rename from data/gfx/x1200/chooser_left_over.webp rename to data/gfx/chooser_left_over.webp diff --git a/data/gfx/x1200/chooser_right.webp b/data/gfx/chooser_right.webp similarity index 100% rename from data/gfx/x1200/chooser_right.webp rename to data/gfx/chooser_right.webp diff --git a/data/gfx/x1200/chooser_right_over.webp b/data/gfx/chooser_right_over.webp similarity index 100% rename from data/gfx/x1200/chooser_right_over.webp rename to data/gfx/chooser_right_over.webp diff --git a/data/gfx/x1200/explosion.webp b/data/gfx/explosion.webp similarity index 100% rename from data/gfx/x1200/explosion.webp rename to data/gfx/explosion.webp diff --git a/data/gfx/x1200/explosion4.webp b/data/gfx/explosion4.webp similarity index 100% rename from data/gfx/x1200/explosion4.webp rename to data/gfx/explosion4.webp diff --git a/data/gfx/x1200/field.webp b/data/gfx/field.webp similarity index 100% rename from data/gfx/x1200/field.webp rename to data/gfx/field.webp diff --git a/data/gfx/x1200/radio.webp b/data/gfx/radio.webp similarity index 100% rename from data/gfx/x1200/radio.webp rename to data/gfx/radio.webp diff --git a/data/gfx/x1200/radio_active.webp b/data/gfx/radio_active.webp similarity index 100% rename from data/gfx/x1200/radio_active.webp rename to data/gfx/radio_active.webp diff --git a/data/gfx/x1200/shadow.webp b/data/gfx/shadow.webp similarity index 100% rename from data/gfx/x1200/shadow.webp rename to data/gfx/shadow.webp diff --git a/src/engine/paths.cpp b/src/engine/paths.cpp deleted file mode 100644 index d14e7e2..0000000 --- a/src/engine/paths.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include "paths.hpp" -#include "../constants.hpp" - -#include <jngl.hpp> - -Paths::Paths() { -} - -std::string Paths::getGraphics() { - return graphics; -} - -void Paths::setGraphics(const std::string& g) { - graphics = g; -} - -void Paths::setOriginalGfx(const std::string& o) { - originalGfx = o; -} - -Paths& getPaths() { - return *Paths::handle(); -} diff --git a/src/engine/paths.hpp b/src/engine/paths.hpp deleted file mode 100644 index c52b347..0000000 --- a/src/engine/paths.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include "singleton.hpp" - -#include <string> - -class Paths : public Singleton<Paths> { -public: - Paths(); - - std::string getGraphics(); - void setGraphics(const std::string&); - - void setOriginalGfx(const std::string&); - -private: - std::string graphics; - std::string originalGfx; -}; - -Paths& getPaths(); diff --git a/src/engine/resizegraphics.cpp b/src/engine/resizegraphics.cpp index 6b3b2e4..ee96d7b 100644 --- a/src/engine/resizegraphics.cpp +++ b/src/engine/resizegraphics.cpp @@ -1,55 +1,50 @@ #include "resizegraphics.hpp" #include "paths.hpp" #include <jngl.hpp> #include <boost/lexical_cast.hpp> void ScanPath(fs::path path, std::deque<std::string>& filesToResize) { fs::directory_iterator end; for (fs::directory_iterator it(path); it != end; ++it) { if (fs::is_directory(it->status())) { ScanPath(it->path(), filesToResize); } else { std::string file = it->path().string(); const std::string extension = ".webp"; if (file.substr(file.size() - extension.size()) == extension) { filesToResize.push_back(std::string(it->path().string()).erase(0, jngl::getPrefix().size())); } } } } -ResizeGraphics::ResizeGraphics() : originalSize_(1200) { - const std::string origGfx = "gfx/x" + std::to_string(originalSize_) + "/"; - getPaths().setOriginalGfx("gfx/x1200"); - jngl::setScaleFactor(double(jngl::getWindowHeight()) / double(originalSize_)); - getPaths().setGraphics(origGfx); - ScanPath(jngl::getPrefix() + "gfx/x" + std::to_string(originalSize_), filesToResize_); +ResizeGraphics::ResizeGraphics() { + jngl::setScaleFactor(static_cast<double>(jngl::getWindowHeight()) / 1200.); + ScanPath(jngl::getPrefix() + "gfx", filesToResize_); } ResizeGraphics::~ResizeGraphics() { } bool ResizeGraphics::isFinished(float& percentage) { if (filesToResize_.empty()) { return true; } static size_t numberOfImages = filesToResize_.size(); percentage = float(100 - filesToResize_.size() * 100 / numberOfImages); // Don't do anything in the first frame in order to draw the loading screen for the first time static bool firstFrame = true; if (firstFrame) { firstFrame = false; return false; } - std::string basedir = "gfx/x" + std::to_string(originalSize_); - std::string relativeFilename(filesToResize_[0].substr(basedir.size() + 1)); - std::string newFilename = getPaths().getGraphics() + relativeFilename; + std::string newFilename = filesToResize_[0]; jngl::load(newFilename.substr(0, newFilename.size()-5)); filesToResize_.pop_front(); return false; } diff --git a/src/engine/resizegraphics.hpp b/src/engine/resizegraphics.hpp index 1a44ea9..538d41f 100644 --- a/src/engine/resizegraphics.hpp +++ b/src/engine/resizegraphics.hpp @@ -1,18 +1,17 @@ #pragma once #include <deque> #include <filesystem> namespace fs = std::filesystem; class ResizeGraphics { public: ResizeGraphics(); ~ResizeGraphics(); bool isFinished(float& percentage); private: std::deque<std::string> filesToResize_; - int originalSize_; }; void ScanPath(fs::path path, std::deque<std::string>& filesToResize); diff --git a/src/engine/screen.cpp b/src/engine/screen.cpp index 877b540..3b7bcaa 100644 --- a/src/engine/screen.cpp +++ b/src/engine/screen.cpp @@ -1,27 +1,27 @@ #include "screen.hpp" #include "paths.hpp" #include <jngl.hpp> void Screen::DrawCentered(const std::string& filename, const double x, const double y) { - const std::string filepath = getPaths().getGraphics() + filename; + const std::string filepath = "gfx/" + filename; jngl::draw(filepath, x - jngl::getWidth(filepath) / 2.0, y - jngl::getHeight(filepath) / 2.0); } void Screen::DrawCentered(const std::string& filename, const Vector2d& position) { GetScreen().DrawCentered(filename, position.X(), position.Y()); } Screen& GetScreen() { return *Screen::handle(); } void Screen::printCentered(const std::string& text, const jngl::Vec2 center) { jngl::print(text, static_cast<int>((center.x - jngl::getTextWidth(text) / 2)), static_cast<int>(center.y) - jngl::getFontSize() / 2); } diff --git a/src/explosion.cpp b/src/explosion.cpp index 596ed07..d83977c 100644 --- a/src/explosion.cpp +++ b/src/explosion.cpp @@ -1,30 +1,27 @@ #include "explosion.hpp" -#include "engine/paths.hpp" -#include "engine/screen.hpp" - #include <jngl.hpp> Explosion::Explosion(const Block& block, const int numberOfLines) : block_(block), countdown_(255), numberOfLines_(numberOfLines), - sprite(getPaths().getGraphics() + (numberOfLines == 4 ? "explosion4" : "explosion")) { + sprite(std::string("gfx/") + (numberOfLines == 4 ? "explosion4" : "explosion")) { } void Explosion::Step() { countdown_ -= 5; } bool Explosion::isFinished() const { return countdown_ < 0; } void Explosion::Draw() const { jngl::setSpriteAlpha(countdown_); sprite.draw( jngl::modelview() .translate({ double(block_.getX() * block_.getSize()), -(block_.getY() - double(255 - countdown_) / 510 * numberOfLines_) * block_.getSize() }) .scale(float(510 - countdown_) / 510)); jngl::setSpriteAlpha(255); } diff --git a/src/gui/Button.cpp b/src/gui/Button.cpp index aff8637..910c235 100644 --- a/src/gui/Button.cpp +++ b/src/gui/Button.cpp @@ -1,80 +1,78 @@ #include "Button.hpp" -#include "../engine/paths.hpp" #include "../engine/screen.hpp" #include "jngl/matrix.hpp" #include <jngl.hpp> #include <string> const int Button::fontSize = 70; Button::Button(const std::string& text, std::function<void()> callback, const std::string& normal, const std::string& mouseOver, const std::string& clicked) -: text_(text), mouseoverAlpha(0), callback(callback), clicked(false), - sprite(getPaths().getGraphics() + normal), spriteMouseOver(getPaths().getGraphics() + mouseOver), - spriteClicked(getPaths().getGraphics() + clicked) { +: text_(text), mouseoverAlpha(0), callback(callback), clicked(false), sprite("gfx/" + normal), + spriteMouseOver("gfx/" + mouseOver), spriteClicked("gfx/" + clicked) { width = sprite.getWidth() * jngl::getScaleFactor(); height = sprite.getHeight() * jngl::getScaleFactor(); } void Button::SetText(const std::string& text) { text_ = text; } void Button::draw() const { int alpha = mouseoverAlpha; if (clicked) { alpha -= 100; } auto mv = jngl::modelview().translate(getCenter()); sprite.draw(mv.scale(1.0f + (alpha / 6000.0f))); if (focus) { spriteMouseOver.draw(mv); } jngl::setSpriteColor(255, 255, 255, alpha); jngl::pushMatrix(); spriteMouseOver.draw(mv.scale(1.0f + (alpha / 6000.0f))); jngl::popMatrix(); jngl::setSpriteColor(255, 255, 255, 255); if (clicked) { spriteClicked.draw(mv.scale(1.0f + (alpha / 6000.0f))); } jngl::setFontColor(255, 255, 255); jngl::setFontSize(fontSize); if (!clicked) { GetScreen().printCentered(text_, getCenter()); } else { GetScreen().printCentered(text_, { getCenter().x + 5, getCenter().y + 5 }); } } void Button::step() { if (!jngl::mouseDown()) { clicked = false; } const int alphaSpeed = 20; if (focus) { if (jngl::keyPressed(jngl::key::Space) || jngl::keyPressed(jngl::key::Return)) { clicked = true; callback(); } } if (sensitive && contains(jngl::getMousePos())) { if (mouseoverAlpha < 255) { mouseoverAlpha += alphaSpeed; } if (jngl::mousePressed()) { clicked = true; callback(); } } else if (mouseoverAlpha > 0) { mouseoverAlpha -= alphaSpeed; } if (mouseoverAlpha > 255) { mouseoverAlpha = 255; } if (mouseoverAlpha < 0) { mouseoverAlpha = 0; } } diff --git a/src/gui/chooser.cpp b/src/gui/chooser.cpp index 0992a1b..1c74b93 100644 --- a/src/gui/chooser.cpp +++ b/src/gui/chooser.cpp @@ -1,67 +1,66 @@ #include "chooser.hpp" #include "../engine/screen.hpp" -#include "../engine/paths.hpp" #include <jngl.hpp> Chooser::Chooser(const int x, const int y) : previous_( "", [this]() { Previous(); }, "chooser_left", "chooser_left_over", "chooser_left_over"), next_( "", [this]() { Next(); }, "chooser_right", "chooser_right_over", "chooser_right_over"), - sprite_(getPaths().getGraphics() + "chooser") { + sprite_("gfx/chooser") { width = jngl::getWidth(sprite_) * jngl::getScaleFactor(); height = jngl::getHeight(sprite_) * jngl::getScaleFactor(); setCenter(x, y); previous_.setCenter( x - static_cast<double>(jngl::getWidth(sprite_)) / 2 - previous_.getWidth() / 2, y); next_.setCenter(x + static_cast<double>(jngl::getWidth(sprite_)) / 2 + next_.getWidth() / 2, y); } void Chooser::AddValue(int v) { values_.push_back(v); activeValue_ = values_.begin(); } void Chooser::step() { previous_.setFocus(focus); next_.setFocus(focus); previous_.step(); next_.step(); if (focus) { if (jngl::keyPressed(jngl::key::Left)) { Previous(); } if (jngl::keyPressed(jngl::key::Right)) { Next(); } } } void Chooser::draw() const { jngl::draw(sprite_, getX(), getY()); jngl::setFontSize(70); jngl::setFontColor(255, 255, 255); GetScreen().printCentered(std::to_string(*activeValue_), getCenter()); previous_.draw(); next_.draw(); } int Chooser::GetValue() const { return *activeValue_; } void Chooser::Next() { ++activeValue_; if (activeValue_ == values_.end()) { activeValue_ = values_.begin(); } } void Chooser::Previous() { if (activeValue_ == values_.begin()) { activeValue_ = values_.end(); } --activeValue_; } diff --git a/src/highscore.cpp b/src/highscore.cpp index fff33e7..6cb93bc 100644 --- a/src/highscore.cpp +++ b/src/highscore.cpp @@ -1,128 +1,126 @@ #include "highscore.hpp" -#include "engine/paths.hpp" -#include "engine/screen.hpp" #include <fstream> #include <stdexcept> #include <cassert> #include <cmath> #include <iomanip> #include <jngl.hpp> Data::Data() : score(0), time(0) { } bool operator==(const Data& a, const Data& b) { return a.score == b.score && std::lround(a.time * 1000) == std::lround(b.time * 1000) && a.name == b.name; } Highscore::Highscore(GameType type) : type_(type), blink_(nullptr) { switch (type) { case GameType::NORMAL: filename_ = "normal.txt"; break; case GameType::FIFTYLINES: filename_ = "fiftylines.txt"; break; } const auto value = jngl::readConfig(filename_); if (!value.empty()) { std::istringstream fin(value); for(int i = 0; i < 5; ++i) { Data temp; std::getline(fin, temp.name); fin >> (temp.score) >> (temp.time); highscores_.push_back(temp); fin.ignore(3, '\n'); // Read till next \n } } else { for(int i = 0; i < 5; ++i) { Data temp; temp.name = "Jan-Nik"; temp.score = 0; temp.time = 13 * 60 + 37; highscores_.push_back(temp); } } } void Highscore::draw() const { assert(highscores_.size() == 5); jngl::pushMatrix(); jngl::setFontSize(50); auto end = highscores_.end(); int n = 1; bool foundEntryToBlink = false; for (auto it = highscores_.begin(); it != end; ++it) { std::string score; if (type_ == GameType::NORMAL) { score = std::to_string(it->score); } else { int minutes = int(it->time / 60); int seconds = int(it->time - minutes * 60); int tenthOfASecond = int((it->time - seconds - minutes * 60) * 10); std::stringstream sstream; sstream.fill('0'); sstream << minutes << ":" << std::setw(2) << seconds << "." << tenthOfASecond; score = sstream.str(); } jngl::setFontColor(0, 0, 0); if (!foundEntryToBlink && blink_) { Data a = *blink_; Data b = *it; if (a == b) { foundEntryToBlink = true; int alpha = int(jngl::getTime() * 300) % 510; jngl::setFontColor(0, 0, 0, alpha > 255 ? 510 - alpha : alpha); } } jngl::print(score, 700 - static_cast<int>(jngl::getTextWidth(score)), 0); jngl::print(std::to_string(n) + ". " + it->name, 0, 0); jngl::translate(0, 80); ++n; } jngl::popMatrix(); } void Highscore::Add(Data data) { highscores_.push_back(data); if (type_ == GameType::NORMAL) { highscores_.sort([](const Data& lhs, const Data& rhs) { return lhs.score > rhs.score; }); } else { highscores_.sort([](const Data& lhs, const Data& rhs) { return lhs.time < rhs.time; }); } highscores_.pop_back(); } bool Highscore::isHighscore(Data data) const { if (type_ == GameType::NORMAL) { return data.score > highscores_.back().score; } else { return data.time < highscores_.back().time; } } void Highscore::save() const { std::ostringstream fout; auto end = highscores_.end(); for (auto it = highscores_.begin(); it != end; ++it) { fout << it->name << std::endl << it->score << " " << it->time << std::endl; } jngl::writeConfig(filename_, fout.str()); } void Highscore::Blink(Data d) { blink_.reset(new Data(d)); }
jhasse/jntetri
b1cf55b96d3ca9c3f50a74139162147e873b54f9
VSCode: Use Ninja Multi-Config
diff --git a/.vscode/launch.json b/.vscode/launch.json index 04459dd..1e9ecbe 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,23 +1,23 @@ { "version": "0.2.0", "configurations": [ { "type": "gdb", "request": "launch", "name": "jntetri (GDB)", - "target": "./build/jntetri", + "target": "./build/Debug/jntetri", "cwd": "${workspaceRoot}", "valuesFormatting": "prettyPrinters", "preLaunchTask": "build" }, { "type": "lldb", "request": "launch", "name": "jntetri (lldb)", - "program": "${workspaceRoot}/build/jntetri", + "program": "${workspaceRoot}/build/Debug/jntetri", "args": [], "cwd": "${workspaceRoot}", "preLaunchTask": "build" } ] }
jhasse/jntetri
4c69ffd7c5048803830153bdfb1374a399cd684f
Remove Meson build support
diff --git a/.gitignore b/.gitignore index a3885fd..4af6ab9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,32 +1,28 @@ /build*/ .DS_Store .sconsign.dblite bin/ *.sublime-workspace obj/ msi/*.wixobj msi/*.wixpdb msi/JNTETRI.msi msi/data.wxs /JNTETRI.opensdf /.cache/ # Visual Studio *.sdf *.v12.suo .vs/ Debug/ Release/ packages/ # Visual Studio Code .browse.VC.db /.vscode/cquery* /.ccls-cache/ /compile_commands.json /.clangd/ - -# Meson -/subprojects/*-* -/subprojects/packagecache/ diff --git a/README.md b/README.md index c9987ea..e42bb29 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,3 @@ # JNTETRI Make sure you clone recursively or check out the submodules using `git submodule update --init`. - -## Windows - -``` -pacman -S mingw-w64-x86_64-SDL2 -``` - -## Linux - -On Ubuntu you can install all the dependencies using: - -``` -sudo apt install libboost-filesystem-dev libboost-serialization-dev meson -``` - -## Building Using Meson - -```sh -meson build -ninja -C build -./build/jntetri -``` diff --git a/meson.build b/meson.build deleted file mode 100644 index 41bcb46..0000000 --- a/meson.build +++ /dev/null @@ -1,100 +0,0 @@ -project('jntetri', ['c', 'cpp'], default_options : ['cpp_std=c++17']) - -cxx = meson.get_compiler('cpp') -add_project_arguments(cxx.get_supported_arguments([ - '-Wall', '-Wextra', - '-Winit-self', - '-Winconsistent-missing-override', - # '-Wpedantic', spdlog - # '-Wfloat-equal', spdlog - '-Wdelete-non-virtual-dtor', - '-Wlogical-op', - '-Wduplicated-cond', - '-Wduplicated-branches', - '-Wno-implicit-fallthrough', # cereal - '-Wno-class-memaccess', # cereal -]), language : 'cpp') - -if cxx.get_id() == 'clang' - add_global_arguments(['-stdlib=libc++'], language : 'cpp') - add_global_link_arguments(['-lc++', '-lc++abi'], language : 'cpp') -endif - -if host_machine.system() == 'windows' and cxx.get_argument_syntax() != 'msvc' - boost_dep = [ - cxx.find_library('ws2_32'), - ] -else - boost_dep = dependency('boost', modules : ['system', 'filesystem']) -endif - -if host_machine.system() == 'linux' - add_global_link_arguments(['-lstdc++fs'], language : 'cpp') -endif - -if get_option('buildtype') == 'release' - add_global_arguments('-DNDEBUG', language : 'cpp') -endif - -jngl = subproject('jngl') -spdlog_dep = subproject('spdlog', default_options : ['tests=false']).get_variable('spdlog_dep') - -src = [ - 'src/explosion.cpp', - 'src/Intro.cpp', - 'src/lobby.cpp', - 'src/control.cpp', - 'src/multiplayermenu.cpp', - 'src/highscore.cpp', - 'src/Field.cpp', - 'src/replayrecorder.cpp', - 'src/Login.cpp', - 'src/main.cpp', - 'src/ReplayPlayer.cpp', - 'src/block.cpp', - 'src/Game.cpp', - 'src/optionsmenu.cpp', - 'src/SplitScreen.cpp', - 'src/NetworkControl.cpp', - 'src/NetworkRecorder.cpp', - 'src/gui/chooser.cpp', - 'src/gui/input.cpp', - 'src/gui/Button.cpp', - 'src/gui/ButtonBox.cpp', - 'src/gui/widget.cpp', - 'src/gui/radiobutton.cpp', - 'src/shadow.cpp', - 'src/menu.cpp', - 'src/ReplayControl.cpp', - 'src/tetromino.cpp', - 'src/engine/screen.cpp', - 'src/engine/work.cpp', - 'src/engine/procedure.cpp', - 'src/engine/debugoverlay.cpp', - 'src/engine/resizegraphics.cpp', - 'src/engine/vector2d.cpp', - 'src/engine/socket.cpp', - 'src/engine/options.cpp', - 'src/engine/fade.cpp', - 'src/engine/paths.cpp', - 'src/pausemenu.cpp', - 'src/gameoverscreen.cpp', -] -if target_machine.system() == 'windows' - src += [import('windows').compile_resources('src/icon.rc')] -endif - -executable( - 'jntetri', src, - dependencies : [ - cxx.find_library('dl'), - dependency('threads'), - boost_dep, - subproject('cereal').get_variable('cereal_dep'), - spdlog_dep, - ], - include_directories : [ - jngl.get_variable('include'), - ], - link_with : jngl.get_variable('lib'), -) diff --git a/subprojects/cereal.wrap b/subprojects/cereal.wrap deleted file mode 100644 index ff60da4..0000000 --- a/subprojects/cereal.wrap +++ /dev/null @@ -1,10 +0,0 @@ -[wrap-file] -directory = cereal-1.2.2 - -source_url = https://github.com/USCiLab/cereal/archive/v1.2.2.tar.gz -source_filename = cereal-1.2.2.tar.gz -source_hash = 1921f26d2e1daf9132da3c432e2fd02093ecaedf846e65d7679ddf868c7289c4 - -patch_url = https://wrapdb.mesonbuild.com/v1/projects/cereal/1.2.2/1/get_zip -patch_filename = cereal-1.2.2-1-wrap.zip -patch_hash = 35203a5db0b66bf45971f5c274c3a59b4c0453c2675874aa69fce1d39b369c7f diff --git a/subprojects/spdlog.wrap b/subprojects/spdlog.wrap deleted file mode 100644 index 9dac4d8..0000000 --- a/subprojects/spdlog.wrap +++ /dev/null @@ -1,10 +0,0 @@ -[wrap-file] -directory = spdlog-1.3.1 - -source_url = https://github.com/gabime/spdlog/archive/v1.3.1.tar.gz -source_filename = v1.3.1.tar.gz -source_hash = 160845266e94db1d4922ef755637f6901266731c4cb3b30b45bf41efa0e6ab70 - -patch_url = https://wrapdb.mesonbuild.com/v1/projects/spdlog/1.3.1/1/get_zip -patch_filename = spdlog-1.3.1-1-wrap.zip -patch_hash = 715a0229781019b853d409cc0bf891ee4b9d3a17bec0cf87f4ad30b28bbecc87
jhasse/jntetri
48ce5c5f0300fd48d0d9038bd3570237bf5ef98f
Remove unused Procedure
diff --git a/src/engine/procedure.cpp b/src/engine/procedure.cpp deleted file mode 100644 index 0ff8b59..0000000 --- a/src/engine/procedure.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "procedure.hpp" -#include "../constants.hpp" - -#include <jngl.hpp> - -Procedure::Procedure() -: oldTime_(jngl::getTime()), needDraw_(true), fps_(0), fpsTemp_(0), changeWork_(false), - running_(true), showFps_(false) { -} - -Procedure& GetProcedure() { - return *Procedure::handle(); -} - -const double Procedure::timePerStep_ = 1.0 / 100.0; diff --git a/src/engine/procedure.hpp b/src/engine/procedure.hpp deleted file mode 100644 index 229ea70..0000000 --- a/src/engine/procedure.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include "singleton.hpp" -#include "work.hpp" - -#include <boost/shared_ptr.hpp> -#include <string> - -class Procedure : public Singleton<Procedure> { -public: - Procedure(); - void MainLoop(); - -private: - double oldTime_; - bool needDraw_; - double fps_; - double fpsTemp_; - int fpsCounter_; - std::string fpsText_; - const static double timePerStep_; - std::shared_ptr<Work> currentWork_; - bool changeWork_; - std::shared_ptr<Work> newWork_; - bool running_; - bool showFps_; -}; - -Procedure& GetProcedure(); diff --git a/src/engine/work.cpp b/src/engine/work.cpp index 6e76539..1785704 100644 --- a/src/engine/work.cpp +++ b/src/engine/work.cpp @@ -1,82 +1,82 @@ #include "work.hpp" -#include "procedure.hpp" + #include "../gui/widget.hpp" #include <algorithm> #include <jngl.hpp> Work::~Work() { } void Work::FocusPrevious() { focusedWidget_->setFocus(false); if (focusedWidget_ == widgets_.front()) { focusedWidget_ = widgets_.back(); } else { auto it = std::find(widgets_.begin(), widgets_.end(), focusedWidget_); --it; focusedWidget_ = *it; } } void Work::FocusNext() { focusedWidget_->setFocus(false); if (focusedWidget_ == widgets_.back()) { focusedWidget_ = widgets_.front(); } else { auto it = std::find(widgets_.begin(), widgets_.end(), focusedWidget_); ++it; focusedWidget_ = *it; } } void Work::StepFocus() { if (jngl::keyPressed(jngl::key::Down) || (!jngl::keyDown(jngl::key::ShiftL) && jngl::keyPressed(jngl::key::Tab))) { FocusNext(); while (!focusedWidget_->getSensitive()) { FocusNext(); } } if (jngl::keyPressed(jngl::key::Up) || (jngl::keyDown(jngl::key::ShiftL) && jngl::keyPressed(jngl::key::Tab))) { FocusPrevious(); while (!focusedWidget_->getSensitive()) { FocusPrevious(); } } focusedWidget_->setFocus(true); } void Work::StepWidgets() { if (widgets_.empty()) { return; } jngl::setCursor(jngl::Cursor::ARROW); for (auto w : widgets_) { bool focus = w->getFocus(); w->step(); if (!focus && w->getFocus()) { // the widget requests focus focusedWidget_->setFocus(false); focusedWidget_ = w; } else if (focus && !w->getFocus()) { // the widget wants to lose focus FocusNext(); } } StepFocus(); } void Work::DrawWidgets() const { for (auto& w : widgets_) { w->draw(); } } void Work::addWidget(std::shared_ptr<Widget> widget) { widgets_.push_back(widget); if (!focusedWidget_) { focusedWidget_ = widget; } widget->onAdd(*this); StepFocus(); } diff --git a/src/gui/ButtonBox.cpp b/src/gui/ButtonBox.cpp index 8d6da86..5d6977e 100644 --- a/src/gui/ButtonBox.cpp +++ b/src/gui/ButtonBox.cpp @@ -1,41 +1,41 @@ #include "ButtonBox.hpp" -#include "Button.hpp" #include "../engine/work.hpp" +#include "Button.hpp" const int ButtonBox::spacing_ = 30; ButtonBox::ButtonBox(const int xCenter, const int yCenter) : xCenter_(xCenter), yCenter_(yCenter) { setSensitive(false); } ButtonBox::ButtonBox() : xCenter_(0), yCenter_(0) { setSensitive(false); } void ButtonBox::add(const std::string& text, std::function<void()> function) { buttons_.push_back(std::make_shared<Button>(text, function)); auto end = buttons_.end(); int yPosButton = yCenter_ - (buttons_.size() * (buttons_[0]->getHeight() + spacing_) - spacing_) / 2 + buttons_[0]->getHeight() / 2; for (auto it = buttons_.begin(); it != end; ++it) { (*it)->setCenter(xCenter_, yPosButton); yPosButton += buttons_[0]->getHeight() + spacing_; } } void ButtonBox::draw() const { } void ButtonBox::step() { } void ButtonBox::onAdd(Work& work) { for (auto& button : buttons_) { work.addWidget(button); } } diff --git a/src/lobby.cpp b/src/lobby.cpp index 7094f77..f5f5416 100644 --- a/src/lobby.cpp +++ b/src/lobby.cpp @@ -1,102 +1,100 @@ #include "lobby.hpp" +#include "NetworkControl.hpp" +#include "SplitScreen.hpp" #include "engine/fade.hpp" -#include "engine/procedure.hpp" -#include "engine/screen.hpp" #include "gui/MessageBox.hpp" #include "multiplayermenu.hpp" -#include "NetworkControl.hpp" -#include "SplitScreen.hpp" #include <jngl.hpp> #include <nlohmann/json.hpp> #include <spdlog/spdlog.h> Lobby::Lobby(std::shared_ptr<Socket> socket, bool quickLogin) : socket_(socket), chatText_(""), input_(new Input(-700, 500)) { logout_.reset(new Button("Logout", [this]() { OnLogout(); })); play_.reset(new Button("Play!™", [this]() { OnPlay(); })); startReceiving(); input_->setMaxWidth(2500); addWidget(input_); addWidget(logout_); addWidget(play_); logout_->setCenter(-450, -450); play_->setCenter(450, -450); if (quickLogin) { OnPlay(); } } void Lobby::OnLogout() { jngl::setWork(std::make_shared<Fade>(std::make_shared<MultiplayerMenu>(false))); } void Lobby::OnPlay() { play_->setSensitive(false); socket_->send(json{ { "type", "play" } }, []() { spdlog::info("Successfully sent 'play'."); }); } void Lobby::step() { try { socket_->step(); } catch (std::exception& e) { jngl::setWork(std::make_shared<Fade>( std::make_shared<MessageBox>(e.what(), std::make_shared<MultiplayerMenu>(false)))); } if (jngl::keyPressed(jngl::key::Return)) { nlohmann::json j = { { "type", "chat" }, { "text", input_->getText() }, }; spdlog::debug("Sending: {}", j.dump()); socket_->send(j, [this]() { OnMessageSent(); }); input_->setSensitive(false); } StepWidgets(); } void Lobby::OnMessageSent() { input_->setText(""); input_->setSensitive(true); } void Lobby::draw() const { jngl::setFontColor(0, 0, 0); jngl::setFontSize(35); jngl::print(chatText_, -700, -250); DrawWidgets(); } void Lobby::handleReceive(json buf) { if (buf["type"] == "chat") { chatText_ += buf["text"]; chatText_ += '\n'; int lineCount = 0; size_t pos = 0; while ((pos = chatText_.find_first_of("\n", pos + 1)) != std::string::npos) { ++lineCount; } if (lineCount > 13) { pos = chatText_.find_first_of("\n"); chatText_ = chatText_.substr(pos + 1); } } else if (buf["type"] == "play") { // Matchmaking was successful and an opponent found. Let's start the game. spdlog::debug("Starting match making"); auto control = std::make_shared<NetworkControl>(socket_); jngl::setWork(std::make_shared<Fade>( std::make_shared<SplitScreen>(control, buf["seed"].get<int32_t>()))); return; // move out of Lobby loop } else if (buf["type"] == "error") { jngl::setWork<MessageBox>(buf["msg"], std::make_shared<MultiplayerMenu>(false)); return; } else { spdlog::warn("Received unknown type: {}", buf); } startReceiving(); } void Lobby::startReceiving() { socket_->receive([this](json buf) { handleReceive(std::move(buf)); }); } diff --git a/src/menu.cpp b/src/menu.cpp index 52e905d..588e549 100644 --- a/src/menu.cpp +++ b/src/menu.cpp @@ -1,75 +1,73 @@ #include "menu.hpp" -#include "engine/paths.hpp" -#include "engine/procedure.hpp" +#include "Game.hpp" #include "engine/fade.hpp" -#include "gui/ButtonBox.hpp" -#include "optionsmenu.hpp" #include "engine/screen.hpp" -#include "Game.hpp" +#include "gui/ButtonBox.hpp" #include "multiplayermenu.hpp" +#include "optionsmenu.hpp" #include <ctime> Menu::Menu() : buttonBox_(new ButtonBox(-450, 0)), normalHighscore_(GameType::NORMAL), fiftyLinesHighscore_(GameType::FIFTYLINES) { buttonBox_->add("Normal", std::bind(&Menu::Normal, this)); buttonBox_->add("50 Lines", std::bind(&Menu::FiftyLines, this)); buttonBox_->add("Multiplayer", []() { jngl::setWork(std::make_shared<Fade>(std::make_shared<MultiplayerMenu>(false))); }); // buttonBox_->add("Multiplayer", []() { // jngl::setWork(std::make_shared<Fade>(std::make_shared<SplitScreen>(std::make_shared<GamepadControl>(1)))); // }); buttonBox_->add("Options", std::bind(&Menu::OptionsMenuCallback, this)); if (jngl::canQuit()) { buttonBox_->add("Quit", std::bind(&Menu::QuitGame, this)); } addWidget(buttonBox_); } void Menu::BlinkHighscore(Data data) { normalHighscore_.Blink(data); fiftyLinesHighscore_.Blink(data); } void Menu::step() { StepWidgets(); } void Menu::draw() const { jngl::setBackgroundColor(0xffffff_rgb); DrawWidgets(); GetScreen().DrawCentered("box", 340, 0); jngl::pushMatrix(); jngl::translate(-20, -400); jngl::setFontSize(50); jngl::setFontColor(0, 0, 0); jngl::print("Highscores Normal", 0, -90); normalHighscore_.draw(); jngl::translate(0, 530); jngl::setFontColor(0, 0, 0); jngl::print("Highscores 50 Lines", 0, -90); fiftyLinesHighscore_.draw(); jngl::popMatrix(); } void Menu::Normal() const { jngl::setWork(std::make_shared<Fade>( std::make_shared<Game>(GameType::NORMAL, static_cast<int>(time(0)), false))); } void Menu::FiftyLines() const { jngl::setWork(std::make_shared<Fade>( std::make_shared<Game>(GameType::FIFTYLINES, static_cast<int>(time(0)), false))); } void Menu::OptionsMenuCallback() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<OptionsMenu>())); } void Menu::QuitGame() const { jngl::quit(); } diff --git a/src/pausemenu.cpp b/src/pausemenu.cpp index ed857f4..c89b070 100644 --- a/src/pausemenu.cpp +++ b/src/pausemenu.cpp @@ -1,42 +1,40 @@ #include "pausemenu.hpp" -#include "engine/procedure.hpp" -#include "engine/screen.hpp" #include "Game.hpp" +#include "engine/fade.hpp" #include "gui/ButtonBox.hpp" #include "menu.hpp" -#include "engine/fade.hpp" PauseMenu::PauseMenu(std::shared_ptr<Game> game) : work(jngl::getWork()), buttonBox(new ButtonBox), game(std::move(game)) { this->game->SetRotateScreen(false); // Don't rotate the screen so that the buttons work correctly buttonBox->add("Resume", std::bind(&PauseMenu::Continue, this)); buttonBox->add("Menu", std::bind(&PauseMenu::QuitToMenu, this)); buttonBox->add("Quit", jngl::quit); addWidget(buttonBox); } void PauseMenu::step() { if (jngl::keyPressed(jngl::key::Escape)) { jngl::setWork(work); } StepWidgets(); game->StepToRotateScreen(); } void PauseMenu::Continue() { jngl::setWork(work); } void PauseMenu::draw() const { game->draw(); DrawWidgets(); } void PauseMenu::QuitToMenu() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void PauseMenu::onQuitEvent() { // Do Nothing } diff --git a/src/tetromino.cpp b/src/tetromino.cpp index 42b601c..073ec99 100644 --- a/src/tetromino.cpp +++ b/src/tetromino.cpp @@ -1,306 +1,303 @@ #include "tetromino.hpp" #include "Field.hpp" -#include "engine/screen.hpp" - -#include <random> Tetromino::Tetromino(int type, Field& field) : field_(field), shadow(jngl::ScaleablePixels(6 * Block::size), jngl::ScaleablePixels(6 * Block::size)) { assert(0 <= type && type < 7); switch(type) { case 0:{ jngl::Color color(200, 200, 0); blocks_.push_back(Block(-1, 1, color)); // XX blocks_.push_back(Block( 0, 1, color)); // XX blocks_.push_back(Block(-1, 0, color)); blocks_.push_back(Block( 0, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); break;} case 1:{ jngl::Color color(200, 0, 0); blocks_.push_back(Block(-1, 0, color)); // 1234 blocks_.push_back(Block( 0, 0, color)); blocks_.push_back(Block( 1, 0, color)); blocks_.push_back(Block( 2, 0, color)); rotationCenterX_.push_back( 0); rotationCenterY_.push_back( 0); rotationCenterX_.push_back( 0.5); rotationCenterY_.push_back(-0.5); break;} case 2:{ jngl::Color color(0, 200, 200); blocks_.push_back(Block( 0, 1, color)); // 1 blocks_.push_back(Block(-1, 0, color)); // 234 blocks_.push_back(Block( 0, 0, color)); blocks_.push_back(Block( 1, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); rotationCenterX_.push_back( 0); rotationCenterY_.push_back( 0); break;} case 3:{ jngl::Color color(0, 0, 200); blocks_.push_back(Block( 0, 1, color)); // 1 blocks_.push_back(Block( 0, 0, color)); // 2 blocks_.push_back(Block( 0, -1, color)); // 43 blocks_.push_back(Block(-1, -1, color)); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); break;} case 4:{ jngl::Color color(200, 100, 0); blocks_.push_back(Block(-1, 1, color)); // 12 blocks_.push_back(Block( 0, 1, color)); // 3 blocks_.push_back(Block( 0, 0, color)); // 4 blocks_.push_back(Block( 0, -1, color)); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); break;} case 5:{ jngl::Color color(200, 0, 200); blocks_.push_back(Block( 0, 1, color)); // 12 blocks_.push_back(Block( 1, 1, color)); // 34 blocks_.push_back(Block(-1, 0, color)); blocks_.push_back(Block( 0, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); rotationCenterX_.push_back( 0); rotationCenterY_.push_back( 0); break;} case 6:{ jngl::Color color(0, 200, 0); blocks_.push_back(Block(-1, 1, color)); // 12 blocks_.push_back(Block( 0, 1, color)); // 34 blocks_.push_back(Block( 0, 0, color)); blocks_.push_back(Block( 1, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); rotationCenterX_.push_back( 0); rotationCenterY_.push_back( 0); break;} } int numberOfRotations = field_.getRandom() % 4; for (int i = 0; i < numberOfRotations; ++i) { Rotate(CLOCKWISE, true); } animationX_ = animationY_ = rotation_ = 0; // Clear animation set by Rotate(CLOCKWISE) x_ = 5; y_ = 17; } void Tetromino::Step() { animationX_ *= 0.7; animationY_ *= 0.8; rotation_ *= 0.8; if (field_.getControl().Check(ControlType::Left)) { changeX(-1); if (Collided()) { changeX(1); } } if (field_.getControl().Check(ControlType::Right)) { changeX(1); if (Collided()) { changeX(-1); } } if (field_.getControl().Check(ControlType::Rotate)) { Rotate(CLOCKWISE, false); } if (field_.getControl().Check(ControlType::RotateCounter)) { Rotate(COUNTERCLOCKWISE, false); } } void Tetromino::SetX(const int x) { x_ = x; } void Tetromino::changeX(int c) { x_ += c; animationX_ -= c; } void Tetromino::changeY(int c) { y_ += c; animationY_ -= c; } void Tetromino::Rotate(const Direction direction, bool ignoreCollision) { // if ignoreCollision is true, we don't want to make any calls to Collided() bool collidedBeforeRotation = ignoreCollision || Collided(); auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (direction == CLOCKWISE) { it->rotate(direction, rotationCenterX_.front(), rotationCenterY_.front()); } else { it->rotate(direction, rotationCenterX_.back(), rotationCenterY_.back()); } } rotationCenterX_.push_back(rotationCenterX_.front()); rotationCenterX_.pop_front(); rotationCenterY_.push_back(rotationCenterY_.front()); rotationCenterY_.pop_front(); if (direction == CLOCKWISE) { rotation_ -= 90; } else { rotation_ += 90; } if (!collidedBeforeRotation && Collided()) { changeX(1); if (Collided()) { changeX(-2); if (Collided()) { changeX(3); if (Collided()) { changeX(-4); if (Collided()) { changeX(2); // Undo rotation if (direction == CLOCKWISE) { Rotate(COUNTERCLOCKWISE, true); } else { Rotate(CLOCKWISE, true); } } } } } } } void Tetromino::AttachToField() { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { it->setX(it->getX() + x_); it->setY(it->getY() + y_); it->setAnimationX(animationX_); it->setAnimationY(animationY_); it->flash(); field_.AddBlock(*it); } } bool Tetromino::MoveDown() { --y_; if (Collided()) { ++y_; return false; } animationY_ += 1; return true; } void Tetromino::moveUp(int amount) { y_ += amount; animationY_ -= amount; } void Tetromino::draw(bool withShadow) const { if (withShadow) { auto context = shadow.use(); jngl::translate(-Block::size / 2., -Block::size / 2.); context.clear(); jngl::setSpriteColor(0, 0, 0, 10); // 10 // at y == 310 no tetromino would be visible const double STEP_SIZE = 2; for (double y = 1; y < 310; y += STEP_SIZE) { jngl::translate(0, STEP_SIZE); jngl::pushMatrix(); drawBlocks(); jngl::popMatrix(); } jngl::setSpriteAlpha(255); } jngl::pushMatrix(); jngl::translate(field_.indexToPixel(x_ + animationX_, y_ + animationY_)); assert(!blocks_.empty()); blocks_.front().setSpriteColor(); drawBlocks(); jngl::setSpriteColor(255, 255, 255); jngl::popMatrix(); } void Tetromino::drawShadow() const { jngl::pushMatrix(); const auto pos = field_.indexToPixel(x_ + animationX_, y_ + animationY_); jngl::translate(pos); jngl::translate(-Block::size * 2.5, -Block::size * 2.5); jngl::setSpriteAlpha(50); const float width = shadow.getSize().x; float height = shadow.getSize().y; float minV = 0; float extensionHeight = field_.getBottomY() - pos.y - height / 2.; if (extensionHeight < 0) { height += extensionHeight; minV = -extensionHeight / shadow.getSize().y; assert(minV >= 0 && minV <= 1); extensionHeight = 0; } shadow.drawMesh({ // top right triangle jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, jngl::Vertex{ .x = width, .y = 0, .u = 1, .v = 1 }, jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, // bottom left triangle jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, jngl::Vertex{ .x = 0, .y = height, .u = 0, .v = minV }, jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, // Now extend the end of the shadow (v == 0) to the bottom of the field: // top right triangle jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, jngl::Vertex{ .x = width, .y = height + 0, .u = 1, .v = 0 }, jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, // bottom left triangle jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, jngl::Vertex{ .x = 0, .y = height + extensionHeight, .u = 0, .v = 0 }, jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, }); jngl::setSpriteAlpha(255); jngl::popMatrix(); } bool Tetromino::Collided() const { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (field_.checkCollision(x_ + it->getX(), y_ + it->getY())) { return true; } } return false; } void Tetromino::drop() { while (MoveDown()); animationX_ = animationY_ = 0; } void Tetromino::drawBlocks() const { const int blockSize = field_.getBlockSize(); if (rotation_ < 0) { // Clockwise jngl::translate( rotationCenterX_.back() * blockSize, -rotationCenterY_.back() * blockSize); jngl::rotate(rotation_); jngl::translate(-rotationCenterX_.back() * blockSize, rotationCenterY_.back() * blockSize); } else { jngl::translate( rotationCenterX_.front() * blockSize, -rotationCenterY_.front() * blockSize); jngl::rotate(rotation_); jngl::translate(-rotationCenterX_.front() * blockSize, rotationCenterY_.front() * blockSize); } for (auto& block : blocks_) { block.draw(); } } diff --git a/src/tetromino.hpp b/src/tetromino.hpp index 347aeb0..44db93f 100644 --- a/src/tetromino.hpp +++ b/src/tetromino.hpp @@ -1,45 +1,45 @@ #pragma once #include "Block.hpp" +#include <deque> #include <jngl.hpp> #include <vector> -#include <deque> class Field; class Tetromino { public: Tetromino(int type, Field&); void Step(); void draw(bool withShadow) const; void drawShadow() const; bool Collided() const; bool MoveDown(); void moveUp(int amount); void AttachToField(); /// \a ignoreCollision is used when creating the Tetromino void Rotate(Direction, bool ignoreCollision); void RandomRotate(); void SetX(int); void drop(); private: void drawBlocks() const; void changeX(int); void changeY(int); std::vector<Block> blocks_; Field& field_; int x_, y_; double animationX_ = 0; double animationY_ = 0; double rotation_; std::deque<int> positionTweaksX_; // These values help correctly rotate the tetromino because std::deque<int> positionTweaksY_; // in nearly all Tetris versions it isn't a real rotation. std::deque<double> rotationCenterX_; std::deque<double> rotationCenterY_; mutable jngl::FrameBuffer shadow; };
jhasse/jntetri
56d2d2d7deb7b533d851fdb3fa25c418dac3401e
Add .clang-tidy
diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..df8803d --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,70 @@ +--- +Checks: ' + ,*, + ,-altera-id-dependent-backward-branch, + ,-altera-struct-pack-align, + ,-altera-unroll-loops, + ,-android-cloexec-fopen, + ,-bugprone-easily-swappable-parameters, + ,-cert-err52-cpp, + ,-cert-err58-cpp, + ,-cert-flp30-c, + ,-clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, + ,-clang-diagnostic-unused-command-line-argument, + ,-cppcoreguidelines-avoid-c-arrays, + ,-cppcoreguidelines-avoid-magic-numbers, + ,-cppcoreguidelines-avoid-non-const-global-variables, + ,-cppcoreguidelines-init-variables, + ,-cppcoreguidelines-non-private-member-variables-in-classes, + ,-cppcoreguidelines-owning-memory, + ,-cppcoreguidelines-pro-bounds-array-to-pointer-decay, + ,-cppcoreguidelines-pro-bounds-constant-array-index, + ,-cppcoreguidelines-pro-bounds-pointer-arithmetic, + ,-cppcoreguidelines-pro-type-vararg, + ,-cppcoreguidelines-special-member-functions, + ,-fuchsia-default-arguments-calls, + ,-fuchsia-default-arguments-declarations, + ,-fuchsia-default-arguments, + ,-fuchsia-multiple-inheritance, + ,-fuchsia-overloaded-operator, + ,-fuchsia-statically-constructed-objects, + ,-google-global-names-in-headers, + ,-google-readability-todo, + ,-google-runtime-int, + ,-google-runtime-references, + ,-hicpp-avoid-c-arrays, + ,-hicpp-named-parameter, + ,-hicpp-no-array-decay, + ,-hicpp-signed-bitwise, + ,-hicpp-special-member-functions, + ,-hicpp-uppercase-literal-suffix, + ,-hicpp-vararg, + ,-llvm-header-guard, + ,-llvm-qualified-auto, + ,-llvmlibc-callee-namespace, + ,-llvmlibc-implementation-in-namespace, + ,-llvmlibc-inline-function-decl, + ,-llvmlibc-restrict-system-libc-headers, + ,-misc-no-recursion, + ,-misc-non-private-member-variables-in-classes, + ,-modernize-avoid-c-arrays, + ,-modernize-use-nodiscard, + ,-modernize-use-trailing-return-type, + ,-readability-function-cognitive-complexity, + ,-readability-identifier-length, + ,-readability-magic-numbers, + ,-readability-named-parameter, + ,-readability-qualified-auto, + ,-readability-uppercase-literal-suffix, + ,-readability-use-anyofallof, +' +WarningsAsErrors: 'hicpp-use-override,modernize-avoid-bind,llvm-namespace-comment,modernize-use-nullptr,modernize-pass-by-value,hicpp-noexcept-move,boost-use-to-string,google-readability-namespace-comments,modernize-use-default-member-init,modernize-loop-convert,hicpp-use-nullptr,google-readability-braces-around-statements,cert-dcl03-c,readability-else-after-return,bugprone-macro-parentheses,readability-redundant-declaration,google-explicit-constructor,readability-avoid-const-params-in-decls' +CheckOptions: + - key: readability-implicit-bool-conversion.AllowPointerConditions + value: '1' + - key: readability-implicit-bool-conversion.AllowIntegerConditions + value: '1' + - key: bugprone-narrowing-conversions.WarnOnFloatingPointNarrowingConversion + value: '0' + - key: cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion + value: '0' diff --git a/subprojects/jngl b/subprojects/jngl index fd1bd19..90a8751 160000 --- a/subprojects/jngl +++ b/subprojects/jngl @@ -1 +1 @@ -Subproject commit fd1bd196ba190986a1dd107461660a9d6a9d5812 +Subproject commit 90a875115023924bad21d6e94d1ad4110679c0b6
jhasse/jntetri
195981d4517b1937af92851c84cc87f304c1f236
JNGL no longer uses OpenAL
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 3238af6..779403f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,72 +1,72 @@ image: fedora:39 linux: stage: build script: - - dnf install -y git gcc-c++ fontconfig-devel freetype-devel libvorbis-devel libepoxy-devel libwebp-devel boost-python3-devel python3-devel cmake ninja-build SDL2-devel openal-soft-devel + - dnf install -y git gcc-c++ fontconfig-devel freetype-devel libvorbis-devel libepoxy-devel libwebp-devel boost-python3-devel python3-devel cmake ninja-build SDL2-devel libatomic - cmake -Bbuild -GNinja - ninja -C build server: image: ubuntu:20.04 stage: build script: - apt-get update && apt-get install -y cmake ninja-build libsoci-dev libsqlite3-dev g++ git libboost-system-dev libboost-coroutine-dev - cd server - cmake -Bbuild -GNinja - cmake --build build web: image: emscripten/emsdk stage: build script: - apt-get update && apt-get install -y ninja-build - cd /tmp - curl --silent -O -L https://boostorg.jfrog.io/artifactory/main/release/1.82.0/source/boost_1_82_0.tar.bz2 - tar --wildcards -xf *.tar.bz2 'boost_1_*_0/boost' - cd - - emcmake cmake -GNinja -Bbuild-web -DCMAKE_BUILD_TYPE=Release -DJNGL_VIDEO=0 -DBoost_INCLUDE_DIR=/tmp/boost_1_82_0 - mv data/ build-web/ - ninja -Cbuild-web jntetri artifacts: paths: - build-web/ docker-build: image: docker:latest stage: build services: - docker:dind before_script: - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY # Default branch leaves tag empty (= latest tag) # All other branches are tagged with the escaped branch name (commit ref slug) script: - | if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then tag="" echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'" else tag=":$CI_COMMIT_REF_SLUG" echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag" fi - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" web - docker push "$CI_REGISTRY_IMAGE${tag}" pages: stage: deploy dependencies: - web script: - mv build-web public - mv web/index.html public/ artifacts: paths: - public only: - master variables: CLICOLOR_FORCE: "1" GIT_SUBMODULE_STRATEGY: recursive DEBIAN_FRONTEND: noninteractive
jhasse/jntetri
1b5779e2ea76ccaa337d3b8fb263d54eb8fb674c
GitLab CI: Update to Fedora 39
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index caefe44..3238af6 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,72 +1,72 @@ -image: fedora:34 +image: fedora:39 linux: stage: build script: - dnf install -y git gcc-c++ fontconfig-devel freetype-devel libvorbis-devel libepoxy-devel libwebp-devel boost-python3-devel python3-devel cmake ninja-build SDL2-devel openal-soft-devel - cmake -Bbuild -GNinja - ninja -C build server: image: ubuntu:20.04 stage: build script: - apt-get update && apt-get install -y cmake ninja-build libsoci-dev libsqlite3-dev g++ git libboost-system-dev libboost-coroutine-dev - cd server - cmake -Bbuild -GNinja - cmake --build build web: image: emscripten/emsdk stage: build script: - apt-get update && apt-get install -y ninja-build - cd /tmp - curl --silent -O -L https://boostorg.jfrog.io/artifactory/main/release/1.82.0/source/boost_1_82_0.tar.bz2 - tar --wildcards -xf *.tar.bz2 'boost_1_*_0/boost' - cd - - emcmake cmake -GNinja -Bbuild-web -DCMAKE_BUILD_TYPE=Release -DJNGL_VIDEO=0 -DBoost_INCLUDE_DIR=/tmp/boost_1_82_0 - mv data/ build-web/ - ninja -Cbuild-web jntetri artifacts: paths: - build-web/ docker-build: image: docker:latest stage: build services: - docker:dind before_script: - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY # Default branch leaves tag empty (= latest tag) # All other branches are tagged with the escaped branch name (commit ref slug) script: - | if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then tag="" echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'" else tag=":$CI_COMMIT_REF_SLUG" echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag" fi - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" web - docker push "$CI_REGISTRY_IMAGE${tag}" pages: stage: deploy dependencies: - web script: - mv build-web public - mv web/index.html public/ artifacts: paths: - public only: - master variables: CLICOLOR_FORCE: "1" GIT_SUBMODULE_STRATEGY: recursive DEBIAN_FRONTEND: noninteractive
jhasse/jntetri
e601fe3a44b319fc9fe97dd88c6472c3718c8a36
Rename options.hpp/cpp to Options.hpp/cpp
diff --git a/src/Block.cpp b/src/Block.cpp index 88c06ed..ab50352 100644 --- a/src/Block.cpp +++ b/src/Block.cpp @@ -1,86 +1,87 @@ #include "Block.hpp" + #include "engine/screen.hpp" #include <jngl/sprite.hpp> const int Block::size = 60; Block::Block(int x, int y, jngl::Color color) : x(x), y(y), color(color), flashAnimation(0) { } void Block::step() { animationX *= 0.7; animationY *= 0.95; if (flashAnimation > 0) { flashAnimation *= 0.96; } } void Block::setAnimationY(double a) { animationY = a; } double Block::getAnimationY() const { return animationY; } void Block::setAnimationX(double a) { animationX = a; } double Block::getAnimationX() const { return animationX; } void Block::setSpriteColor() const { jngl::setSpriteColor(static_cast<unsigned char>(color.getRed() + flashAnimation), static_cast<unsigned char>(color.getGreen() + flashAnimation), static_cast<unsigned char>(color.getBlue() + flashAnimation)); } void Block::draw() const { GetScreen().DrawCentered("block", (x + animationX) * size, -(y + animationY) * size); } void Block::rotate(Direction direction, double rotationCenterX, double rotationCenterY) { double tempX, tempY; double xRot = x - rotationCenterX; double yRot = y - rotationCenterY; if (direction == CLOCKWISE) { tempX = yRot; tempY = -xRot; } else { tempX = -yRot; tempY = xRot; } x = static_cast<int>(tempX + rotationCenterX); y = static_cast<int>(tempY + rotationCenterY); } int Block::getX() const { return x; } int Block::getY() const { return y; } void Block::setX(const int x) { this->x = x; } void Block::setY(const int y) { this->y = y; } int Block::getSize() const { return size; } jngl::Color Block::getColor() const { return color; } void Block::flash() { flashAnimation = 50; } diff --git a/src/Game.cpp b/src/Game.cpp index a203113..ccc7b8d 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -1,137 +1,136 @@ #include "Game.hpp" #include "engine/screen.hpp" -#include "engine/options.hpp" -#include "engine/procedure.hpp" +#include "engine/Options.hpp" #include "gameoverscreen.hpp" #include "pausemenu.hpp" #include "ReplayRecorder.hpp" #include <jngl.hpp> #include <sstream> #include <iomanip> #include <boost/lexical_cast.hpp> Game::Game(const GameType type, const int seed, const bool replay) : field_(seed, getOptions().startLevel, getOptions().startJunks), type_(type), nextPosition_(field_.GetNextPosition()), oldNextPosition_(nextPosition_), rotateScreen_(false), rotateDegree_(0) { if (!replay) { // Don't record when we're playing back a replay replayRecorder = std::make_unique<ReplayRecorder>(field_, type); } jngl::setMouseVisible(false); } Game::~Game() { jngl::setMouseVisible(true); } void Game::SetRotateScreen(bool rotateScreen) { rotateScreen_ = rotateScreen; } void Game::step() { StepToRotateScreen(); if (field_.GameOver()) { pauseTime_ = jngl::getTime(); jngl::setWork(std::make_shared<GameOverScreen>(this)); } else { field_.SetPause(false); field_.step(); if (replayRecorder) { replayRecorder->Step(); } if (type_ == GameType::FIFTYLINES && field_.GetLines() >= 50) { field_.setGameOver(true); } } nextPosition_ = field_.GetNextPosition(); oldNextPosition_ = (nextPosition_ - oldNextPosition_) * 0.01 + oldNextPosition_; if (pauseTime_ > 0.0001 && !field_.GameOver()) { pauseTime_ = 0; } if (jngl::keyPressed('p') || jngl::keyPressed(jngl::key::Escape)) { onQuitEvent(); // Pause } } void Game::onQuitEvent() { static double lastPauseTime = 0; if (jngl::getTime() - lastPauseTime > 1) { // Don't allow pausing the game more then one time per second lastPauseTime = pauseTime_ = jngl::getTime(); field_.SetPause(true); jngl::setWork(std::make_shared<PauseMenu>(shared_from_this())); jngl::cancelQuit(); } } void Game::DrawTime(const int x, const int y) const { jngl::print("Time: ", x, y); double time = GetTime(); int minutes = int(time / 60); int seconds = int(time - minutes * 60); std::stringstream sstream; sstream.fill('0'); sstream << minutes << ":" << std::setw(2) << seconds; jngl::print(sstream.str(), 450, y + 100); } void Game::StepToRotateScreen() { if (rotateScreen_ && rotateDegree_ < 90) { rotateDegree_ += (90 - rotateDegree_) * 0.05; } else { rotateDegree_ *= 0.95; } } void Game::draw() const { jngl::pushMatrix(); jngl::rotate(rotateDegree_); jngl::scale(1 + rotateDegree_ / 270); field_.draw(); if (!rotateScreen_) { jngl::setFontColor(0, 0, 0); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(-600, oldNextPosition_); field_.drawNextTetromino(); jngl::popMatrix(); if (type_ == GameType::FIFTYLINES) { DrawTime(450, -500); } else { jngl::print("Score: ", 450, -500); jngl::print(std::to_string(field_.GetScore()), 450, -400); DrawTime(450, 220); } jngl::print("Level: ", 450, -260); jngl::print(std::to_string(field_.GetLevel()), 450, -160); jngl::print("Lines: ", 450, -20); jngl::print(std::to_string(field_.GetLines()), 450, 80); } jngl::popMatrix(); } Field& Game::GetField() { return field_; } double Game::GetTime() const { return field_.getSecondsPlayed(); } bool Game::GameOverAnimationFinished() const { return field_.GameOverAnimationFinished(); } GameType Game::getType() const { return type_; } bool Game::gameOver() const { return field_.GameOver(); } bool Game::isReplay() const { return replayRecorder == nullptr; } diff --git a/src/Intro.cpp b/src/Intro.cpp index 230fb44..2a6d1dd 100644 --- a/src/Intro.cpp +++ b/src/Intro.cpp @@ -1,78 +1,76 @@ #include "Intro.hpp" #include "constants.hpp" #include "engine/fade.hpp" -#include "engine/options.hpp" -#include "engine/procedure.hpp" +#include "engine/Options.hpp" #include "engine/screen.hpp" #include "fonts.hpp" -#include "Game.hpp" #include "menu.hpp" #include "multiplayermenu.hpp" #include <jngl.hpp> Intro::Intro() : blink_(0), finished_(false) { } void Intro::draw() const { jngl::setFontSize(250); jngl::setFontColor(50, 50, 50); GetScreen().printCentered("JNTETRI", { 0, -250 }); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(0, 150); float percentage; if (resizeGraphics_.isFinished(percentage)) { finished_ = true; jngl::setFontColor(0, 0, 0, blink_ > 255 ? 510 - blink_ : blink_); fonts::label(); // TODO: find a better way to load all fonts GetScreen().printCentered("Press any key to continue", { 0, 0 }); } else { GetScreen().printCentered(std::to_string(int(percentage)) + " %", { 0, 0 }); } jngl::popMatrix(); jngl::setFontColor(100, 100, 100, 255); jngl::setFontSize(35); GetScreen().printCentered(programVersion, { 0, 360 }); GetScreen().printCentered("https://bixense.itch.io/jntetri", { 0, 430 }); GetScreen().printCentered("Copyright 2009-2019 bixense.com", { 0, 500 }); } void Intro::step() { blink_ += 4; if (blink_ > 2 * 255) { blink_ = 0; } #ifdef NDEBUG bool anyKeyPressed = jngl::mousePressed() || jngl::keyPressed(jngl::key::Any) || getOptions().lastLoginName.empty(); #else bool anyKeyPressed = true; #endif if (anyKeyPressed && finished_) { bool login = false; for (const auto& arg : jngl::getArgs()) { if (arg == "--login") { login = true; } if (login) { getOptions().lastLoginName = arg; } } if (login) { jngl::setWork<MultiplayerMenu>(false); } else { if (getOptions().lastLoginName.empty()) { jngl::setWork<MultiplayerMenu>(true); } else { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } } // jngl::setWork(std::make_shared<Fade>(std::make_shared<ReplayPlayer>("test3.jtr"))); // jngl::setWork(std::make_shared<Game>(GameType::NORMAL, static_cast<int>(time(0)), // false)); } } diff --git a/src/Login.cpp b/src/Login.cpp index a4798b4..79e5374 100644 --- a/src/Login.cpp +++ b/src/Login.cpp @@ -1,186 +1,185 @@ #include "Login.hpp" #include "../server/NetworkConstants.hpp" #include "engine/screen.hpp" #include "engine/fade.hpp" -#include "engine/options.hpp" +#include "engine/Options.hpp" #include "gui/Button.hpp" #include "lobby.hpp" #include <jngl.hpp> #include <boost/bind/bind.hpp> #include <boost/lexical_cast.hpp> -#include <sstream> #include <spdlog/spdlog.h> #ifdef __EMSCRIPTEN__ const std::string Login::server_("89.58.48.219"); // boomshine.de const int Login::port_ = 9999; #else // const std::string Login::server_("127.0.0.1"); const std::string Login::server_("89.58.48.219"); // boomshine.de // const std::string Login::server_("85.214.187.23"); // babynamensuche.de const int Login::port_ = 7070; #endif Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu, bool quickLogin) : menu(multiplayerMenu), text_("connecting ..."), cancel_("Cancel", [this]() { OnCancel(); }), socket_(new Socket), quickLogin(quickLogin) { spdlog::info("Connecting to {}:{}", server_, port_); try { socket_->connect(server_, port_, [this]() { HandleConnect(); }); } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.setCenter(0, 200); } void Login::HandleConnect() { text_ = "sending ..."; spdlog::info("Sending protocol version {}", PROTOCOL_VERSION); socket_->send(std::to_string(PROTOCOL_VERSION), [this]() { ProtocolCheck1(); }); } void Login::ProtocolCheck1() { text_ = "receiving ..."; spdlog::info("Waiting for server accept connection"); socket_->receive([this](json data) { ProtocolCheck2(std::move(data)); }); } void Login::ProtocolCheck2(json temp) { if (temp["type"] != "ok") { text_ = "Error: "; if (const std::string msg = temp["msg"]; !msg.empty()) { text_ += msg; } else { text_ += temp.dump(); } OnError(); } else { if (menu->GetName().empty()) { if (!menu->GetPassword().empty()) { text_ = "Name must not be empty!"; return OnError(); } socket_->send(json{ { "type", "login_anonymous" } }, [this]() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; }); } else { socket_->send(json{ { "type", "login" }, { "name", menu->GetName() }, { "password", menu->GetPassword() } }, [this]() { HandleLogin1(); }); } } } void Login::HandleLogin1() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; } void Login::HandleLogin2(json temp) { if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else if (temp["type"] == "unknown name") { text_ = "No user with this name found.\nDo you want to register yourself?"; cancel_.setCenter(-350, 280); cancel_.SetText("No"); Button* yes = new Button("Yes", boost::bind(&Login::Register, this)); yes->setCenter(350, 280); addWidget(std::shared_ptr<Widget>(yes)); } else if (temp["type"] == "wrong password") { text_ = "The password you've entered\nis wrong. Please try again."; OnError(); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::Register() { json j{ { "type", "register" }, { "name", menu->GetName() }, { "password", menu->GetPassword() } }; spdlog::info("Sending: {}", j.dump()); socket_->send(j, boost::bind(&Login::HandleRegister1, this)); cancel_.setCenter(0, 200); cancel_.SetText("Cancel"); widgets_.clear(); // FIXME: Implement RemoveWidget function } void Login::HandleRegister1() { socket_->receive([this](json temp) { HandleRegister2(std::move(temp)); }); text_ = "please wait ..."; } void Login::HandleRegister2(json temp) { spdlog::debug("HandleRegister2"); if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::step() { try { if (socket_) { socket_->step(); } } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.step(); StepWidgets(); } void Login::GoToLobby(std::string username) { getOptions().lastLoginName = std::move(username); getOptions().Save(); jngl::setWork(std::make_shared<Fade>( std::make_shared<Lobby>(std::move(socket_), quickLogin))); } void Login::draw() const { menu->draw(); jngl::setColor(255, 255, 255, 220); jngl::drawRect(-jngl::getScreenWidth() / 2, -jngl::getScreenHeight() / 2, jngl::getScreenWidth(), jngl::getScreenHeight()); jngl::setFontColor(0, 0, 0); GetScreen().printCentered(text_, { 0, -150 }); cancel_.draw(); DrawWidgets(); } void Login::OnCancel() { jngl::setWork(menu); } void Login::OnError() { // hacked together algorithm to word wrap long error messages: size_t pos = 42; while (jngl::getTextWidth(text_) > jngl::getScreenWidth() && pos < text_.size()) { size_t i = pos; while (i > 0 && text_[i - 1] != ' ') { if (text_[i] == '\n') { i = pos; break; } --i; } text_.insert(text_.begin() + i, '\n'); pos += 42; } cancel_.SetText("OK"); cancel_.setFocus(true); } diff --git a/src/ReplayPlayer.cpp b/src/ReplayPlayer.cpp index 3f5c6fa..626860e 100644 --- a/src/ReplayPlayer.cpp +++ b/src/ReplayPlayer.cpp @@ -1,47 +1,47 @@ #include "ReplayPlayer.hpp" #include "Game.hpp" #include "ReplayControl.hpp" -#include "engine/options.hpp" +#include "engine/Options.hpp" #include <jngl/input.hpp> ReplayPlayer::ReplayPlayer(const std::string& filename) : fin_(filename.c_str()) { assert(fin_); int seed, startLevel, startJunk, gameType; fin_ >> seed >> startLevel >> startJunk >> gameType; oldStartLevel = getOptions().startLevel; oldStartJunk = getOptions().startJunks; getOptions().startLevel = startLevel; getOptions().startJunks = startJunk; game_ = std::make_shared<Game>(static_cast<GameType>(gameType), seed, true); game_->GetField().setControl(new Control{std::make_shared<ReplayControl>(fin_)}); } ReplayPlayer::~ReplayPlayer() { getOptions().startLevel = oldStartLevel; getOptions().startJunks = oldStartJunk; } void ReplayPlayer::step() { if (jngl::keyDown('f')) { for (int i = 0; i < 19; ++i) { game_->step(); } } if (jngl::keyDown('s')) { for (int i = 0; i < 60; ++i) { game_->step(); } } if (jngl::keyPressed('e')) { while (!game_->gameOver()) { game_->step(); } } game_->step(); } void ReplayPlayer::draw() const { game_->draw(); } diff --git a/src/ReplayRecorder.cpp b/src/ReplayRecorder.cpp index 15ef10f..7f80af3 100644 --- a/src/ReplayRecorder.cpp +++ b/src/ReplayRecorder.cpp @@ -1,24 +1,24 @@ #include "ReplayRecorder.hpp" #include "Field.hpp" -#include "engine/options.hpp" +#include "engine/Options.hpp" ReplayRecorder::ReplayRecorder(Field& field, const GameType gameType) : fout("testReplay.jtr"), field_(field), time_(0) { fout << field_.getRandomSeed() << " " << getOptions().startLevel << " " << getOptions().startJunks << " " << static_cast<int>(gameType) << std::endl; } void ReplayRecorder::Step() { field_.getControl().forEach([this](ControlType c) { write(c); }); if(time_ == 255) { time_ = 0; write(ControlType::Null); } else { ++time_; } } void ReplayRecorder::write(ControlType c) { fout << static_cast<int>(time_) << " " << static_cast<int>(c) << std::endl; } diff --git a/src/engine/options.cpp b/src/engine/Options.cpp similarity index 97% rename from src/engine/options.cpp rename to src/engine/Options.cpp index 85cca3e..3603ba7 100644 --- a/src/engine/options.cpp +++ b/src/engine/Options.cpp @@ -1,37 +1,37 @@ -#include "options.hpp" +#include "Options.hpp" #include "paths.hpp" #include <cereal/archives/json.hpp> #include <fstream> #include <iostream> #include <jngl.hpp> Options::Options() : filename("options.json") { const int BORDER = 50; const int dpiFactor = std::max(std::min( (jngl::getDesktopWidth() - BORDER) / windowWidth, (jngl::getDesktopHeight() - BORDER) / windowHeight ), 1); windowWidth *= dpiFactor; windowHeight *= dpiFactor; try { std::istringstream ifs(jngl::readConfig(filename)); cereal::JSONInputArchive archive(ifs); archive >> cereal::make_nvp("options", *this); } catch(std::exception& e) { std::cout << "Error loading " << filename << ": " << e.what() << std::endl; } } void Options::Save() const { std::ostringstream ofs; { cereal::JSONOutputArchive archive(ofs); archive << cereal::make_nvp("options", *this); } jngl::writeConfig(filename, ofs.str()); } Options& getOptions() { return *Options::handle(); } diff --git a/src/engine/options.hpp b/src/engine/Options.hpp similarity index 100% rename from src/engine/options.hpp rename to src/engine/Options.hpp diff --git a/src/engine/fade.cpp b/src/engine/fade.cpp index cb4339d..6a3fae8 100644 --- a/src/engine/fade.cpp +++ b/src/engine/fade.cpp @@ -1,45 +1,42 @@ #include "fade.hpp" -#include "procedure.hpp" -#include "options.hpp" -#include "screen.hpp" #include <jngl.hpp> Fade::Fade(std::shared_ptr<Work> work, int speed) : work_(std::move(work)), oldWork_(jngl::getWork()), fadeCount_(0), speed_(speed) { } void Fade::step() { #ifdef NDEBUG const int maxAlpha = 255; #endif fadeCount_ += speed_; #ifdef NDEBUG if (fadeCount_ >= 2 * maxAlpha) // Finished? #endif { jngl::setWork(work_); } } void Fade::draw() const { const int maxAlpha = 255; if(fadeCount_ < maxAlpha) { if(!dynamic_cast<Fade*>(oldWork_.get())) { oldWork_->draw(); } } else { work_->draw(); } const int alpha = static_cast<int>(fadeCount_ > maxAlpha ? 2 * maxAlpha - fadeCount_ : fadeCount_); jngl::setColor(0, 0, 0, alpha); jngl::drawRect(-jngl::getScreenWidth() / 2.0 - 1, -jngl::getScreenHeight() / 2.0 - 1, jngl::getScreenWidth() + 2, jngl::getScreenHeight() + 2); jngl::setColor(255, 255, 255, 255); } diff --git a/src/engine/paths.cpp b/src/engine/paths.cpp index c154399..d14e7e2 100644 --- a/src/engine/paths.cpp +++ b/src/engine/paths.cpp @@ -1,27 +1,23 @@ #include "paths.hpp" -#include "options.hpp" #include "../constants.hpp" -#include <iostream> -#include <sstream> -#include <filesystem> #include <jngl.hpp> Paths::Paths() { } std::string Paths::getGraphics() { return graphics; } void Paths::setGraphics(const std::string& g) { graphics = g; } void Paths::setOriginalGfx(const std::string& o) { originalGfx = o; } Paths& getPaths() { return *Paths::handle(); } diff --git a/src/engine/procedure.cpp b/src/engine/procedure.cpp index d70bb5e..0ff8b59 100644 --- a/src/engine/procedure.cpp +++ b/src/engine/procedure.cpp @@ -1,18 +1,15 @@ #include "procedure.hpp" -#include "options.hpp" -#include "screen.hpp" #include "../constants.hpp" #include <jngl.hpp> -#include <stdexcept> Procedure::Procedure() : oldTime_(jngl::getTime()), needDraw_(true), fps_(0), fpsTemp_(0), changeWork_(false), running_(true), showFps_(false) { } Procedure& GetProcedure() { return *Procedure::handle(); } const double Procedure::timePerStep_ = 1.0 / 100.0; diff --git a/src/engine/resizegraphics.cpp b/src/engine/resizegraphics.cpp index 0af61a4..6b3b2e4 100644 --- a/src/engine/resizegraphics.cpp +++ b/src/engine/resizegraphics.cpp @@ -1,59 +1,55 @@ #include "resizegraphics.hpp" #include "paths.hpp" -#include "options.hpp" -#include "screen.hpp" #include <jngl.hpp> -#include <iostream> -#include <fstream> #include <boost/lexical_cast.hpp> void ScanPath(fs::path path, std::deque<std::string>& filesToResize) { fs::directory_iterator end; for (fs::directory_iterator it(path); it != end; ++it) { if (fs::is_directory(it->status())) { ScanPath(it->path(), filesToResize); } else { std::string file = it->path().string(); const std::string extension = ".webp"; if (file.substr(file.size() - extension.size()) == extension) { filesToResize.push_back(std::string(it->path().string()).erase(0, jngl::getPrefix().size())); } } } } ResizeGraphics::ResizeGraphics() : originalSize_(1200) { const std::string origGfx = "gfx/x" + std::to_string(originalSize_) + "/"; getPaths().setOriginalGfx("gfx/x1200"); jngl::setScaleFactor(double(jngl::getWindowHeight()) / double(originalSize_)); getPaths().setGraphics(origGfx); ScanPath(jngl::getPrefix() + "gfx/x" + std::to_string(originalSize_), filesToResize_); } ResizeGraphics::~ResizeGraphics() { } bool ResizeGraphics::isFinished(float& percentage) { if (filesToResize_.empty()) { return true; } static size_t numberOfImages = filesToResize_.size(); percentage = float(100 - filesToResize_.size() * 100 / numberOfImages); // Don't do anything in the first frame in order to draw the loading screen for the first time static bool firstFrame = true; if (firstFrame) { firstFrame = false; return false; } std::string basedir = "gfx/x" + std::to_string(originalSize_); std::string relativeFilename(filesToResize_[0].substr(basedir.size() + 1)); std::string newFilename = getPaths().getGraphics() + relativeFilename; jngl::load(newFilename.substr(0, newFilename.size()-5)); filesToResize_.pop_front(); return false; } diff --git a/src/engine/screen.cpp b/src/engine/screen.cpp index 3c3291a..877b540 100644 --- a/src/engine/screen.cpp +++ b/src/engine/screen.cpp @@ -1,28 +1,27 @@ #include "screen.hpp" #include "paths.hpp" -#include "options.hpp" #include <jngl.hpp> void Screen::DrawCentered(const std::string& filename, const double x, const double y) { const std::string filepath = getPaths().getGraphics() + filename; jngl::draw(filepath, x - jngl::getWidth(filepath) / 2.0, y - jngl::getHeight(filepath) / 2.0); } void Screen::DrawCentered(const std::string& filename, const Vector2d& position) { GetScreen().DrawCentered(filename, position.X(), position.Y()); } Screen& GetScreen() { return *Screen::handle(); } void Screen::printCentered(const std::string& text, const jngl::Vec2 center) { jngl::print(text, static_cast<int>((center.x - jngl::getTextWidth(text) / 2)), static_cast<int>(center.y) - jngl::getFontSize() / 2); } diff --git a/src/gameoverscreen.cpp b/src/gameoverscreen.cpp index e596020..34402fc 100644 --- a/src/gameoverscreen.cpp +++ b/src/gameoverscreen.cpp @@ -1,83 +1,82 @@ #include "gameoverscreen.hpp" -#include "engine/procedure.hpp" #include "engine/screen.hpp" #include "engine/fade.hpp" -#include "engine/options.hpp" +#include "engine/Options.hpp" #include "Game.hpp" #include "menu.hpp" #include <jngl.hpp> GameOverScreen::GameOverScreen(Game* game) : game_(game), blink_(0), highscore_(game_->getType()), input_(new Input(-160, 200)), work_(jngl::getWork()) { data_.score = game_->GetField().GetScore(); data_.time = game_->GetTime(); input_->setText(getOptions().lastHighscoreName); input_->setMaxWidth(400); addWidget(input_); } bool GameOverScreen::isHighscore() const { return !game_->isReplay() && highscore_.isHighscore(data_) && (game_->getType() == GameType::NORMAL || game_->GetField().GetLines() >= 50); } void GameOverScreen::step() { game_->GetField().step(); // Show GameOver animation game_->StepToRotateScreen(); if (game_->GameOverAnimationFinished()) { if (isHighscore()) { StepWidgets(); if (jngl::keyPressed(jngl::key::Return)) { data_.name = input_->getText(); getOptions().lastHighscoreName = data_.name; highscore_.Add(data_); highscore_.save(); auto menu = std::make_shared<Menu>(); menu->BlinkHighscore(data_); jngl::setWork(std::make_shared<Fade>(std::move(menu))); } } else { blink_ += 4; if (blink_ > 2 * 255) { blink_ = 0; } if (jngl::mousePressed() || jngl::keyPressed(jngl::key::Any)) { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } } } else if (jngl::keyPressed(jngl::key::Escape)) { while (!game_->GameOverAnimationFinished()) { game_->GetField().step(); } } } void GameOverScreen::onQuitEvent() { while (!game_->GameOverAnimationFinished()) { game_->GetField().step(); } if (!isHighscore()) { jngl::quit(); } } void GameOverScreen::draw() const { game_->draw(); jngl::setFontSize(80); jngl::setFontColor(0, 0, 0); GetScreen().printCentered("GAMEOVER", { 0, -100 }); if (game_->GameOverAnimationFinished()) { jngl::setFontSize(50); if (isHighscore()) { jngl::setFontColor(0, 0, 0); GetScreen().printCentered("You entered the top!", { 0, 50 }); GetScreen().printCentered("Enter your name:", { 0, 130 }); DrawWidgets(); } else { jngl::setFontColor(0, 0, 0, blink_ > 255 ? 510 - blink_ : blink_); GetScreen().printCentered("Press any key", { 0, 100 }); } } } diff --git a/src/gui/ButtonBox.cpp b/src/gui/ButtonBox.cpp index fadfe94..8d6da86 100644 --- a/src/gui/ButtonBox.cpp +++ b/src/gui/ButtonBox.cpp @@ -1,43 +1,41 @@ #include "ButtonBox.hpp" -#include "../engine/options.hpp" -#include "../engine/screen.hpp" -#include "../engine/procedure.hpp" #include "Button.hpp" +#include "../engine/work.hpp" const int ButtonBox::spacing_ = 30; ButtonBox::ButtonBox(const int xCenter, const int yCenter) : xCenter_(xCenter), yCenter_(yCenter) { setSensitive(false); } ButtonBox::ButtonBox() : xCenter_(0), yCenter_(0) { setSensitive(false); } void ButtonBox::add(const std::string& text, std::function<void()> function) { buttons_.push_back(std::make_shared<Button>(text, function)); auto end = buttons_.end(); int yPosButton = yCenter_ - (buttons_.size() * (buttons_[0]->getHeight() + spacing_) - spacing_) / 2 + buttons_[0]->getHeight() / 2; for (auto it = buttons_.begin(); it != end; ++it) { (*it)->setCenter(xCenter_, yPosButton); yPosButton += buttons_[0]->getHeight() + spacing_; } } void ButtonBox::draw() const { } void ButtonBox::step() { } void ButtonBox::onAdd(Work& work) { for (auto& button : buttons_) { work.addWidget(button); } } diff --git a/src/main.cpp b/src/main.cpp index b6155d1..8fe572a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,27 +1,25 @@ -#include "engine/procedure.hpp" -#include "engine/options.hpp" #include "Intro.hpp" #include "engine/debugoverlay.hpp" #include "constants.hpp" #include <spdlog/spdlog.h> #include <jngl.hpp> #include <jngl/init.hpp> jngl::AppParameters jnglInit() { jngl::AppParameters params; #ifndef NDEBUG spdlog::set_level(spdlog::level::trace); #endif params.displayName = programDisplayName; params.screenSize = { 1280, 720 }; params.start = []() { jngl::setAntiAliasing(true); jngl::setIcon("icon"); jngl::setFont("Inter-ExtraLight.ttf"); jngl::setFontSize(jngl::getScaleFactor() * 13); jngl::addJob(std::make_shared<DebugOverlay>()); return std::make_shared<Intro>(); }; return params; } diff --git a/src/multiplayermenu.cpp b/src/multiplayermenu.cpp index e41dfd0..381d731 100644 --- a/src/multiplayermenu.cpp +++ b/src/multiplayermenu.cpp @@ -1,59 +1,58 @@ #include "multiplayermenu.hpp" #include "engine/screen.hpp" -#include "engine/procedure.hpp" #include "engine/fade.hpp" -#include "engine/options.hpp" +#include "engine/Options.hpp" #include "menu.hpp" #include "Login.hpp" #include <jngl.hpp> MultiplayerMenu::MultiplayerMenu(const bool quickLogin) : name_(new Input(50, -240)), password_(new Input(50, -100)), quickLogin(quickLogin) { addWidget(name_); addWidget(password_); login_.reset(new Button("Login", [this]() { OnLogin(); })); addWidget(login_); back_.reset(new Button("Back", [this]() { OnBack(); })); addWidget(back_); back_->setCenter(-350, 280); login_->setCenter(350, 280); password_->SetPassword(true); name_->setText(getOptions().lastLoginName); if (name_->getText() != "") { FocusNext(); } } void MultiplayerMenu::step() { StepWidgets(); if (jngl::keyPressed(jngl::key::Return) || quickLogin) { OnLogin(); quickLogin = false; // if an error happens we will be reactivated } } void MultiplayerMenu::draw() const { jngl::setFontColor(0, 0, 0); jngl::print("Name:", -500, -240); jngl::print("Password:", -500, -100); DrawWidgets(); } void MultiplayerMenu::OnBack() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void MultiplayerMenu::OnLogin() { jngl::setWork(std::make_shared<Login>( std::dynamic_pointer_cast<MultiplayerMenu>(jngl::getWork()), quickLogin)); } std::string MultiplayerMenu::GetName() const { return name_->getText(); } std::string MultiplayerMenu::GetPassword() const { return password_->getText(); } diff --git a/src/optionsmenu.cpp b/src/optionsmenu.cpp index 7161a77..c81eb48 100644 --- a/src/optionsmenu.cpp +++ b/src/optionsmenu.cpp @@ -1,47 +1,46 @@ #include "optionsmenu.hpp" #include "engine/fade.hpp" -#include "engine/options.hpp" -#include "engine/procedure.hpp" +#include "engine/Options.hpp" #include "engine/screen.hpp" #include "menu.hpp" #include <jngl.hpp> OptionsMenu::OptionsMenu() : startLevel_(new Chooser(0, -300)), startJunks_(new Chooser(0, 100)) { back_.reset(new Button("Back", std::bind(&OptionsMenu::OnBack, this))); for (int i = 0; i < 10; ++i) { startLevel_->AddValue(i); } for (unsigned int i = 0; i < getOptions().startLevel; ++i) { startLevel_->Next(); } for (int i = 0; i < 6; ++i) { startJunks_->AddValue(i * 2); } for (unsigned int i = 0; i < getOptions().startJunks / 2; ++i) { startJunks_->Next(); } back_->setCenter(0, 400); addWidget(startLevel_); addWidget(startJunks_); addWidget(back_); } void OptionsMenu::step() { StepWidgets(); } void OptionsMenu::draw() const { DrawWidgets(); jngl::setFontColor(0, 0, 0); GetScreen().printCentered("Start Level", { 0, -500 }); GetScreen().printCentered("Start Junks", { 0, -100 }); } void OptionsMenu::OnBack() const { getOptions().startLevel = startLevel_->GetValue(); getOptions().startJunks = startJunks_->GetValue(); getOptions().Save(); jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } diff --git a/src/tetromino.cpp b/src/tetromino.cpp index 3ee43b6..42b601c 100644 --- a/src/tetromino.cpp +++ b/src/tetromino.cpp @@ -1,306 +1,306 @@ #include "tetromino.hpp" #include "Field.hpp" #include "engine/screen.hpp" #include <random> Tetromino::Tetromino(int type, Field& field) : field_(field), shadow(jngl::ScaleablePixels(6 * Block::size), jngl::ScaleablePixels(6 * Block::size)) { assert(0 <= type && type < 7); switch(type) { case 0:{ jngl::Color color(200, 200, 0); blocks_.push_back(Block(-1, 1, color)); // XX blocks_.push_back(Block( 0, 1, color)); // XX blocks_.push_back(Block(-1, 0, color)); blocks_.push_back(Block( 0, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); break;} case 1:{ jngl::Color color(200, 0, 0); blocks_.push_back(Block(-1, 0, color)); // 1234 blocks_.push_back(Block( 0, 0, color)); blocks_.push_back(Block( 1, 0, color)); blocks_.push_back(Block( 2, 0, color)); rotationCenterX_.push_back( 0); rotationCenterY_.push_back( 0); rotationCenterX_.push_back( 0.5); rotationCenterY_.push_back(-0.5); break;} case 2:{ jngl::Color color(0, 200, 200); blocks_.push_back(Block( 0, 1, color)); // 1 blocks_.push_back(Block(-1, 0, color)); // 234 blocks_.push_back(Block( 0, 0, color)); blocks_.push_back(Block( 1, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); rotationCenterX_.push_back( 0); rotationCenterY_.push_back( 0); break;} case 3:{ jngl::Color color(0, 0, 200); blocks_.push_back(Block( 0, 1, color)); // 1 blocks_.push_back(Block( 0, 0, color)); // 2 blocks_.push_back(Block( 0, -1, color)); // 43 blocks_.push_back(Block(-1, -1, color)); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); break;} case 4:{ jngl::Color color(200, 100, 0); blocks_.push_back(Block(-1, 1, color)); // 12 blocks_.push_back(Block( 0, 1, color)); // 3 blocks_.push_back(Block( 0, 0, color)); // 4 blocks_.push_back(Block( 0, -1, color)); rotationCenterX_.push_back(0); rotationCenterY_.push_back(0); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); break;} case 5:{ jngl::Color color(200, 0, 200); blocks_.push_back(Block( 0, 1, color)); // 12 blocks_.push_back(Block( 1, 1, color)); // 34 blocks_.push_back(Block(-1, 0, color)); blocks_.push_back(Block( 0, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); rotationCenterX_.push_back( 0); rotationCenterY_.push_back( 0); break;} case 6:{ jngl::Color color(0, 200, 0); blocks_.push_back(Block(-1, 1, color)); // 12 blocks_.push_back(Block( 0, 1, color)); // 34 blocks_.push_back(Block( 0, 0, color)); blocks_.push_back(Block( 1, 0, color)); rotationCenterX_.push_back(-0.5); rotationCenterY_.push_back( 0.5); rotationCenterX_.push_back( 0); rotationCenterY_.push_back( 0); break;} } int numberOfRotations = field_.getRandom() % 4; for (int i = 0; i < numberOfRotations; ++i) { Rotate(CLOCKWISE, true); } animationX_ = animationY_ = rotation_ = 0; // Clear animation set by Rotate(CLOCKWISE) x_ = 5; y_ = 17; } void Tetromino::Step() { animationX_ *= 0.7; animationY_ *= 0.8; rotation_ *= 0.8; if (field_.getControl().Check(ControlType::Left)) { - ChangeX(-1); + changeX(-1); if (Collided()) { - ChangeX(1); + changeX(1); } } if (field_.getControl().Check(ControlType::Right)) { - ChangeX(1); + changeX(1); if (Collided()) { - ChangeX(-1); + changeX(-1); } } if (field_.getControl().Check(ControlType::Rotate)) { Rotate(CLOCKWISE, false); } if (field_.getControl().Check(ControlType::RotateCounter)) { Rotate(COUNTERCLOCKWISE, false); } } void Tetromino::SetX(const int x) { x_ = x; } -void Tetromino::ChangeX(int c) { +void Tetromino::changeX(int c) { x_ += c; animationX_ -= c; } -void Tetromino::ChangeY(int c) { +void Tetromino::changeY(int c) { y_ += c; animationY_ -= c; } void Tetromino::Rotate(const Direction direction, bool ignoreCollision) { // if ignoreCollision is true, we don't want to make any calls to Collided() bool collidedBeforeRotation = ignoreCollision || Collided(); auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (direction == CLOCKWISE) { it->rotate(direction, rotationCenterX_.front(), rotationCenterY_.front()); } else { it->rotate(direction, rotationCenterX_.back(), rotationCenterY_.back()); } } rotationCenterX_.push_back(rotationCenterX_.front()); rotationCenterX_.pop_front(); rotationCenterY_.push_back(rotationCenterY_.front()); rotationCenterY_.pop_front(); if (direction == CLOCKWISE) { rotation_ -= 90; } else { rotation_ += 90; } if (!collidedBeforeRotation && Collided()) { - ChangeX(1); + changeX(1); if (Collided()) { - ChangeX(-2); + changeX(-2); if (Collided()) { - ChangeX(3); + changeX(3); if (Collided()) { - ChangeX(-4); + changeX(-4); if (Collided()) { - ChangeX(2); + changeX(2); // Undo rotation if (direction == CLOCKWISE) { Rotate(COUNTERCLOCKWISE, true); } else { Rotate(CLOCKWISE, true); } } } } } } } void Tetromino::AttachToField() { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { it->setX(it->getX() + x_); it->setY(it->getY() + y_); it->setAnimationX(animationX_); it->setAnimationY(animationY_); it->flash(); field_.AddBlock(*it); } } bool Tetromino::MoveDown() { --y_; if (Collided()) { ++y_; return false; } animationY_ += 1; return true; } void Tetromino::moveUp(int amount) { y_ += amount; animationY_ -= amount; } void Tetromino::draw(bool withShadow) const { if (withShadow) { auto context = shadow.use(); jngl::translate(-Block::size / 2., -Block::size / 2.); context.clear(); jngl::setSpriteColor(0, 0, 0, 10); // 10 // at y == 310 no tetromino would be visible const double STEP_SIZE = 2; for (double y = 1; y < 310; y += STEP_SIZE) { jngl::translate(0, STEP_SIZE); jngl::pushMatrix(); drawBlocks(); jngl::popMatrix(); } jngl::setSpriteAlpha(255); } jngl::pushMatrix(); jngl::translate(field_.indexToPixel(x_ + animationX_, y_ + animationY_)); assert(!blocks_.empty()); blocks_.front().setSpriteColor(); drawBlocks(); jngl::setSpriteColor(255, 255, 255); jngl::popMatrix(); } void Tetromino::drawShadow() const { jngl::pushMatrix(); const auto pos = field_.indexToPixel(x_ + animationX_, y_ + animationY_); jngl::translate(pos); jngl::translate(-Block::size * 2.5, -Block::size * 2.5); jngl::setSpriteAlpha(50); const float width = shadow.getSize().x; float height = shadow.getSize().y; float minV = 0; float extensionHeight = field_.getBottomY() - pos.y - height / 2.; if (extensionHeight < 0) { height += extensionHeight; minV = -extensionHeight / shadow.getSize().y; assert(minV >= 0 && minV <= 1); extensionHeight = 0; } shadow.drawMesh({ // top right triangle jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, jngl::Vertex{ .x = width, .y = 0, .u = 1, .v = 1 }, jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, // bottom left triangle jngl::Vertex{ .x = 0, .y = 0, .u = 0, .v = 1 }, jngl::Vertex{ .x = 0, .y = height, .u = 0, .v = minV }, jngl::Vertex{ .x = width, .y = height, .u = 1, .v = minV }, // Now extend the end of the shadow (v == 0) to the bottom of the field: // top right triangle jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, jngl::Vertex{ .x = width, .y = height + 0, .u = 1, .v = 0 }, jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, // bottom left triangle jngl::Vertex{ .x = 0, .y = height + 0, .u = 0, .v = 0 }, jngl::Vertex{ .x = 0, .y = height + extensionHeight, .u = 0, .v = 0 }, jngl::Vertex{ .x = width, .y = height + extensionHeight, .u = 1, .v = 0 }, }); jngl::setSpriteAlpha(255); jngl::popMatrix(); } bool Tetromino::Collided() const { auto end = blocks_.end(); for (auto it = blocks_.begin(); it != end; ++it) { if (field_.checkCollision(x_ + it->getX(), y_ + it->getY())) { return true; } } return false; } void Tetromino::drop() { while (MoveDown()); animationX_ = animationY_ = 0; } void Tetromino::drawBlocks() const { const int blockSize = field_.getBlockSize(); if (rotation_ < 0) { // Clockwise jngl::translate( rotationCenterX_.back() * blockSize, -rotationCenterY_.back() * blockSize); jngl::rotate(rotation_); jngl::translate(-rotationCenterX_.back() * blockSize, rotationCenterY_.back() * blockSize); } else { jngl::translate( rotationCenterX_.front() * blockSize, -rotationCenterY_.front() * blockSize); jngl::rotate(rotation_); jngl::translate(-rotationCenterX_.front() * blockSize, rotationCenterY_.front() * blockSize); } for (auto& block : blocks_) { block.draw(); } } diff --git a/src/tetromino.hpp b/src/tetromino.hpp index 0cc2e54..347aeb0 100644 --- a/src/tetromino.hpp +++ b/src/tetromino.hpp @@ -1,45 +1,45 @@ #pragma once #include "Block.hpp" #include <jngl.hpp> #include <vector> #include <deque> class Field; class Tetromino { public: Tetromino(int type, Field&); void Step(); void draw(bool withShadow) const; void drawShadow() const; bool Collided() const; bool MoveDown(); void moveUp(int amount); void AttachToField(); /// \a ignoreCollision is used when creating the Tetromino void Rotate(Direction, bool ignoreCollision); void RandomRotate(); void SetX(int); void drop(); private: void drawBlocks() const; - void ChangeX(int); - void ChangeY(int); + void changeX(int); + void changeY(int); std::vector<Block> blocks_; Field& field_; int x_, y_; double animationX_ = 0; double animationY_ = 0; double rotation_; std::deque<int> positionTweaksX_; // These values help correctly rotate the tetromino because std::deque<int> positionTweaksY_; // in nearly all Tetris versions it isn't a real rotation. std::deque<double> rotationCenterX_; std::deque<double> rotationCenterY_; mutable jngl::FrameBuffer shadow; };
jhasse/jntetri
6d3bf2023e93d1bf9fe7f79d28a34a04e16bc64a
Refactoring
diff --git a/src/block.cpp b/src/Block.cpp similarity index 98% rename from src/block.cpp rename to src/Block.cpp index d8589bf..88c06ed 100644 --- a/src/block.cpp +++ b/src/Block.cpp @@ -1,86 +1,86 @@ -#include "block.hpp" +#include "Block.hpp" #include "engine/screen.hpp" #include <jngl/sprite.hpp> const int Block::size = 60; Block::Block(int x, int y, jngl::Color color) : x(x), y(y), color(color), flashAnimation(0) { } void Block::step() { animationX *= 0.7; animationY *= 0.95; if (flashAnimation > 0) { flashAnimation *= 0.96; } } void Block::setAnimationY(double a) { animationY = a; } double Block::getAnimationY() const { return animationY; } void Block::setAnimationX(double a) { animationX = a; } double Block::getAnimationX() const { return animationX; } void Block::setSpriteColor() const { jngl::setSpriteColor(static_cast<unsigned char>(color.getRed() + flashAnimation), static_cast<unsigned char>(color.getGreen() + flashAnimation), static_cast<unsigned char>(color.getBlue() + flashAnimation)); } void Block::draw() const { GetScreen().DrawCentered("block", (x + animationX) * size, -(y + animationY) * size); } void Block::rotate(Direction direction, double rotationCenterX, double rotationCenterY) { double tempX, tempY; double xRot = x - rotationCenterX; double yRot = y - rotationCenterY; if (direction == CLOCKWISE) { tempX = yRot; tempY = -xRot; } else { tempX = -yRot; tempY = xRot; } x = static_cast<int>(tempX + rotationCenterX); y = static_cast<int>(tempY + rotationCenterY); } int Block::getX() const { return x; } int Block::getY() const { return y; } void Block::setX(const int x) { this->x = x; } void Block::setY(const int y) { this->y = y; } int Block::getSize() const { return size; } jngl::Color Block::getColor() const { return color; } void Block::flash() { flashAnimation = 50; } diff --git a/src/block.hpp b/src/Block.hpp similarity index 100% rename from src/block.hpp rename to src/Block.hpp diff --git a/src/Field.hpp b/src/Field.hpp index 65bca50..095cbca 100644 --- a/src/Field.hpp +++ b/src/Field.hpp @@ -1,94 +1,94 @@ #pragma once -#include "block.hpp" +#include "Block.hpp" #include "DesyncInfo.hpp" #include "tetromino.hpp" #include "explosion.hpp" #include "control.hpp" #include <vector> #include <random> #include <ctime> #include <boost/noncopyable.hpp> #include <memory> #include <optional> class Field : boost::noncopyable { public: Field(int seed, int level, uint32_t startJunks); void step(); void draw() const; void DrawBlock(int x, int y) const; void AddBlock(const Block&); [[nodiscard]] jngl::Vec2 indexToPixel(double x, double y) const; /// y coordinate in dp of the bottom double getBottomY() const; int getBlockSize() const; Block* getBlock(int x, int y); bool checkCollision(int x, int y) const; void NewTetromino(); void removeLine(int y, int numberOfLines); void setGameOver(bool); bool GameOver() const; int GetScore() const; int GetLines() const; int GetLevel() const; int GetNextPosition() const; void drawNextTetromino() const; void SetPause(bool pause); /// returns true when there are network issues bool desync() const; /// the function will be called to check if there's a network desync and the game should be /// paused void setCheckDesync(std::function<bool()>); void onUserQuit(std::function<void()>); bool GameOverAnimationFinished() const; void setControl(Control*); Control& getControl() const; unsigned int getRandom(); int getRandomSeed() const; int getLinesCleared() const; void addJunk(int nr); double getSecondsPlayed() const; private: void CheckLines(); void ResetCounter(); std::vector<Block> blocks_; std::vector<Explosion> explosions_; std::shared_ptr<Tetromino> nextTetromino_; std::shared_ptr<Tetromino> tetromino_; const static int width_; const static int height_; const int blockSize_; int counter_; bool gameOver_; int score_; int level_; int lines; int maxY; bool pause_; /// >0 when there are network issues i.e. control_->step() hasn't returned any data int stepsWithoutPackage = 0; bool delay_; std::shared_ptr<Control> control_; bool downKeyReleased_; std::mt19937 random; int randomSeed; int linesCleared; double secondsPlayed = 0; /// If set, we force-pause the game when it returns true std::function<bool()> checkDesync; std::optional<DesyncInfo> desyncInfo; std::function<void()> onUserQuitCallback; }; diff --git a/src/Game.hpp b/src/Game.hpp index d05121e..3379160 100644 --- a/src/Game.hpp +++ b/src/Game.hpp @@ -1,38 +1,37 @@ #pragma once #include "engine/work.hpp" #include "Field.hpp" -#include "block.hpp" #include "gametype.hpp" class ReplayRecorder; class Game : public Work, public std::enable_shared_from_this<Game> { public: Game(GameType, int seed, bool replay); virtual ~Game(); virtual void step(); virtual void draw() const; void onQuitEvent(); Field& GetField(); double GetTime() const; bool GameOverAnimationFinished() const; GameType getType() const; void DrawTime(int x, int y) const; void StepToRotateScreen(); void SetRotateScreen(bool); bool gameOver() const; bool isReplay() const; protected: Field field_; GameType type_; double nextPosition_; double oldNextPosition_; double pauseTime_ = 0; bool rotateScreen_; double rotateDegree_; /// If we're owned by a ReplayPlayer, this is nullptr std::unique_ptr<ReplayRecorder> replayRecorder; }; diff --git a/src/Login.cpp b/src/Login.cpp index 13fc79b..a4798b4 100644 --- a/src/Login.cpp +++ b/src/Login.cpp @@ -1,187 +1,186 @@ #include "Login.hpp" #include "../server/NetworkConstants.hpp" #include "engine/screen.hpp" -#include "engine/procedure.hpp" #include "engine/fade.hpp" #include "engine/options.hpp" #include "gui/Button.hpp" #include "lobby.hpp" #include <jngl.hpp> #include <boost/bind/bind.hpp> #include <boost/lexical_cast.hpp> #include <sstream> #include <spdlog/spdlog.h> #ifdef __EMSCRIPTEN__ const std::string Login::server_("89.58.48.219"); // boomshine.de const int Login::port_ = 9999; #else // const std::string Login::server_("127.0.0.1"); const std::string Login::server_("89.58.48.219"); // boomshine.de // const std::string Login::server_("85.214.187.23"); // babynamensuche.de const int Login::port_ = 7070; #endif Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu, bool quickLogin) -: menu_(multiplayerMenu), text_("connecting ..."), cancel_("Cancel", [this]() { OnCancel(); }), +: menu(multiplayerMenu), text_("connecting ..."), cancel_("Cancel", [this]() { OnCancel(); }), socket_(new Socket), quickLogin(quickLogin) { spdlog::info("Connecting to {}:{}", server_, port_); try { socket_->connect(server_, port_, [this]() { HandleConnect(); }); } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.setCenter(0, 200); } void Login::HandleConnect() { text_ = "sending ..."; spdlog::info("Sending protocol version {}", PROTOCOL_VERSION); socket_->send(std::to_string(PROTOCOL_VERSION), [this]() { ProtocolCheck1(); }); } void Login::ProtocolCheck1() { text_ = "receiving ..."; spdlog::info("Waiting for server accept connection"); socket_->receive([this](json data) { ProtocolCheck2(std::move(data)); }); } void Login::ProtocolCheck2(json temp) { if (temp["type"] != "ok") { text_ = "Error: "; if (const std::string msg = temp["msg"]; !msg.empty()) { text_ += msg; } else { text_ += temp.dump(); } OnError(); } else { - if (menu_->GetName().empty()) { - if (!menu_->GetPassword().empty()) { + if (menu->GetName().empty()) { + if (!menu->GetPassword().empty()) { text_ = "Name must not be empty!"; return OnError(); } socket_->send(json{ { "type", "login_anonymous" } }, [this]() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; }); } else { socket_->send(json{ { "type", "login" }, - { "name", menu_->GetName() }, - { "password", menu_->GetPassword() } }, + { "name", menu->GetName() }, + { "password", menu->GetPassword() } }, [this]() { HandleLogin1(); }); } } } void Login::HandleLogin1() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; } void Login::HandleLogin2(json temp) { if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else if (temp["type"] == "unknown name") { text_ = "No user with this name found.\nDo you want to register yourself?"; cancel_.setCenter(-350, 280); cancel_.SetText("No"); Button* yes = new Button("Yes", boost::bind(&Login::Register, this)); yes->setCenter(350, 280); addWidget(std::shared_ptr<Widget>(yes)); } else if (temp["type"] == "wrong password") { text_ = "The password you've entered\nis wrong. Please try again."; OnError(); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::Register() { json j{ { "type", "register" }, - { "name", menu_->GetName() }, - { "password", menu_->GetPassword() } }; + { "name", menu->GetName() }, + { "password", menu->GetPassword() } }; spdlog::info("Sending: {}", j.dump()); socket_->send(j, boost::bind(&Login::HandleRegister1, this)); cancel_.setCenter(0, 200); cancel_.SetText("Cancel"); widgets_.clear(); // FIXME: Implement RemoveWidget function } void Login::HandleRegister1() { socket_->receive([this](json temp) { HandleRegister2(std::move(temp)); }); text_ = "please wait ..."; } void Login::HandleRegister2(json temp) { spdlog::debug("HandleRegister2"); if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::step() { try { if (socket_) { socket_->step(); } } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.step(); StepWidgets(); } void Login::GoToLobby(std::string username) { getOptions().lastLoginName = std::move(username); getOptions().Save(); jngl::setWork(std::make_shared<Fade>( std::make_shared<Lobby>(std::move(socket_), quickLogin))); } void Login::draw() const { - menu_->draw(); + menu->draw(); jngl::setColor(255, 255, 255, 220); jngl::drawRect(-jngl::getScreenWidth() / 2, -jngl::getScreenHeight() / 2, jngl::getScreenWidth(), jngl::getScreenHeight()); jngl::setFontColor(0, 0, 0); GetScreen().printCentered(text_, { 0, -150 }); cancel_.draw(); DrawWidgets(); } void Login::OnCancel() { - jngl::setWork(menu_); + jngl::setWork(menu); } void Login::OnError() { // hacked together algorithm to word wrap long error messages: size_t pos = 42; while (jngl::getTextWidth(text_) > jngl::getScreenWidth() && pos < text_.size()) { size_t i = pos; while (i > 0 && text_[i - 1] != ' ') { if (text_[i] == '\n') { i = pos; break; } --i; } text_.insert(text_.begin() + i, '\n'); pos += 42; } cancel_.SetText("OK"); cancel_.setFocus(true); } diff --git a/src/Login.hpp b/src/Login.hpp index 4ea70a2..dad7318 100644 --- a/src/Login.hpp +++ b/src/Login.hpp @@ -1,36 +1,36 @@ #pragma once #include "engine/work.hpp" #include "engine/socket.hpp" #include "gui/Button.hpp" #include "multiplayermenu.hpp" #include <boost/asio.hpp> class Login : public Work { public: Login(std::shared_ptr<MultiplayerMenu>, bool quickLogin); void step(); void draw() const; void HandleConnect(); void ProtocolCheck1(); void ProtocolCheck2(json); void HandleLogin1(); void HandleLogin2(json); void OnCancel(); void OnError(); void Register(); void HandleRegister1(); void HandleRegister2(json); void GoToLobby(std::string username); private: - std::shared_ptr<MultiplayerMenu> menu_; + std::shared_ptr<MultiplayerMenu> menu; std::string text_; const static std::string server_; const static int port_; const static std::string protocolVersion_; Button cancel_; std::shared_ptr<Socket> socket_; bool quickLogin; }; diff --git a/src/explosion.hpp b/src/explosion.hpp index 08b6055..ce3cfef 100644 --- a/src/explosion.hpp +++ b/src/explosion.hpp @@ -1,18 +1,18 @@ #pragma once -#include "block.hpp" +#include "Block.hpp" #include <jngl/sprite.hpp> class Explosion { public: Explosion(const Block&, int numberOfLines); void Step(); void Draw() const; bool isFinished() const; private: Block block_; int countdown_; int numberOfLines_; jngl::Sprite sprite; }; diff --git a/src/tetromino.hpp b/src/tetromino.hpp index a55a5e6..0cc2e54 100644 --- a/src/tetromino.hpp +++ b/src/tetromino.hpp @@ -1,45 +1,45 @@ #pragma once -#include "block.hpp" +#include "Block.hpp" #include <jngl.hpp> #include <vector> #include <deque> class Field; class Tetromino { public: Tetromino(int type, Field&); void Step(); void draw(bool withShadow) const; void drawShadow() const; bool Collided() const; bool MoveDown(); void moveUp(int amount); void AttachToField(); /// \a ignoreCollision is used when creating the Tetromino void Rotate(Direction, bool ignoreCollision); void RandomRotate(); void SetX(int); void drop(); private: void drawBlocks() const; void ChangeX(int); void ChangeY(int); std::vector<Block> blocks_; Field& field_; int x_, y_; double animationX_ = 0; double animationY_ = 0; double rotation_; std::deque<int> positionTweaksX_; // These values help correctly rotate the tetromino because std::deque<int> positionTweaksY_; // in nearly all Tetris versions it isn't a real rotation. std::deque<double> rotationCenterX_; std::deque<double> rotationCenterY_; mutable jngl::FrameBuffer shadow; };
jhasse/jntetri
263d0168d2e3d4ffb744887d7a6a4bd6acc94f20
server: Update downloaded Boost version if not found
diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 1293a7a..f99dd49 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -1,38 +1,39 @@ cmake_minimum_required(VERSION 3.10) project(jntetri-server) if(NOT MSVC) -string(APPEND CMAKE_CXX_FLAGS -fdiagnostics-color) + string(APPEND CMAKE_CXX_FLAGS -fdiagnostics-color) endif() include(../subprojects/jngl/cmake/CPM.cmake) find_package(Boost COMPONENTS coroutine system thread) if(NOT Boost_FOUND) CPMAddPackage( NAME Boost - VERSION 1.77.0 + VERSION 1.82.0 GITHUB_REPOSITORY "boostorg/boost" - GIT_TAG "boost-1.77.0" + GIT_TAG "boost-1.82.0" ) endif() CPMAddPackage( NAME nlohmann_json URL "https://github.com/nlohmann/json/archive/refs/tags/v3.10.2.tar.gz" ) CPMAddPackage("gh:gabime/spdlog@1.8.2") find_package(Threads REQUIRED) file(GLOB SRC *.cpp) add_executable(jntetri-server ${SRC}) target_link_libraries(jntetri-server PRIVATE + Boost::headers Boost::coroutine Boost::system Threads::Threads nlohmann_json::nlohmann_json soci_core soci_sqlite3 spdlog ) target_include_directories(jntetri-server PRIVATE /usr/include/soci) # TODO: This seems wrong target_compile_features(jntetri-server PRIVATE cxx_std_17)
jhasse/jntetri
215c387bd4807935c598dbe170c1f7a948de7c75
Only show Quit in PauseMenu if canQuit
diff --git a/src/pausemenu.cpp b/src/pausemenu.cpp index ed857f4..e6b0661 100644 --- a/src/pausemenu.cpp +++ b/src/pausemenu.cpp @@ -1,42 +1,44 @@ #include "pausemenu.hpp" #include "engine/procedure.hpp" #include "engine/screen.hpp" #include "Game.hpp" #include "gui/ButtonBox.hpp" #include "menu.hpp" #include "engine/fade.hpp" PauseMenu::PauseMenu(std::shared_ptr<Game> game) : work(jngl::getWork()), buttonBox(new ButtonBox), game(std::move(game)) { this->game->SetRotateScreen(false); // Don't rotate the screen so that the buttons work correctly buttonBox->add("Resume", std::bind(&PauseMenu::Continue, this)); buttonBox->add("Menu", std::bind(&PauseMenu::QuitToMenu, this)); - buttonBox->add("Quit", jngl::quit); + if (jngl::canQuit()) { + buttonBox->add("Quit", jngl::quit); + } addWidget(buttonBox); } void PauseMenu::step() { if (jngl::keyPressed(jngl::key::Escape)) { jngl::setWork(work); } StepWidgets(); game->StepToRotateScreen(); } void PauseMenu::Continue() { jngl::setWork(work); } void PauseMenu::draw() const { game->draw(); DrawWidgets(); } void PauseMenu::QuitToMenu() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void PauseMenu::onQuitEvent() { // Do Nothing }
jhasse/jntetri
8ed2954f8230b17aa0f9565077d41bd0f12f4b80
Only change Window title in Debug build
diff --git a/src/NetworkControl.cpp b/src/NetworkControl.cpp index 76b44a2..21fe66b 100644 --- a/src/NetworkControl.cpp +++ b/src/NetworkControl.cpp @@ -1,113 +1,115 @@ #include "NetworkControl.hpp" #include "engine/socket.hpp" #include "gui/MessageBox.hpp" #include "jngl/window.hpp" #include "jngl/work.hpp" #include "lobby.hpp" #include "multiplayermenu.hpp" #include <nlohmann/json.hpp> #include <spdlog/spdlog.h> NetworkControl::NetworkControl(std::shared_ptr<Socket> socket) : socket(std::move(socket)) { this->socket->receive([this](json buf) { handleReceive(std::move(buf)); }); } bool NetworkControl::step(const std::function<void(ControlType)>& set) { if (!sendQueue.empty() && !sendingInProgress) { sendingInProgress = true; nlohmann::json j = { { "type", "game" }, { "time", sendQueue.front().first }, { "control", sendQueue.front().second }, }; socket->send(j, [this]() { sendQueue.pop(); // spdlog::info("sent package success. {} to go.", sendQueue.size()); sendingInProgress = false; }); } socket->step(); if (nullPackagesReceived < 1) { return false; } bool handledNullPackage = false; while ((time % BUFFER_LENGTH) == data.front().first) { if (data.front().second == ControlType::Null) { if (handledNullPackage) { break; // Don't skip ahead if there are no commands between two null packages } handledNullPackage = true; --nullPackagesReceived; } else { set(data.front().second); // execute command } data.pop(); if (data.empty()) { break; } } ++time; return true; } void NetworkControl::handleReceive(json j) { if (j["type"] == "game") { uint8_t time = j["time"].get<uint8_t>(); uint8_t control = j["control"].get<uint8_t>(); if (control >= static_cast<int>(ControlType::LastValue)) { spdlog::error("invalid control type in package: {}", control); } else { if (control == static_cast<uint8_t>(ControlType::Null)) { // spdlog::info("Null package received."); ++nullPackagesReceived; } data.push( std::pair<unsigned char, ControlType>(time, static_cast<ControlType>(control))); } } else if (j["type"] == "opponentQuit") { jngl::setWork<MessageBox>("Your opponent left.", std::make_shared<Lobby>(std::move(socket), false)); return; } else if (j["type"] == "disconnected") { jngl::setWork<MessageBox>("Your opponent disconnected.", std::make_shared<Lobby>(std::move(socket), false)); return; } else if (j["type"] == "error") { jngl::setWork<MessageBox>(j["msg"], std::make_shared<MultiplayerMenu>(false)); return; } else { spdlog::error("Unknown package: {}", j.dump()); } socket->receive([this](json buf) { handleReceive(std::move(buf)); }); } void NetworkControl::stepSend(Control& control) { if (sendTime % BUFFER_LENGTH == 0) { sendQueue.push(std::pair<uint8_t, ControlType>(0, ControlType::Null)); } control.forEach([this](ControlType c) { sendQueue.push(std::pair<uint8_t, ControlType>(sendTime % BUFFER_LENGTH, c)); }); ++sendTime; } bool NetworkControl::desync() const { +#ifndef NDEBUG std::stringstream sstream; sstream << "time: " << time << " sendTime: " << sendTime << " nullPackagesReceived: " << nullPackagesReceived << " sendQueue.size(): " << sendQueue.size(); jngl::setTitle(sstream.str()); +#endif return std::abs(time - sendTime) > 1000; } void NetworkControl::sendQuit() { socket->send(json{ { "type", "quit" } }, [this]() { spdlog::info("sent quit success."); }); } std::shared_ptr<Socket> NetworkControl::getSocket() { return socket; }
jhasse/jntetri
9cec51e942b4550b5fc19368f62d30a0b9d66b02
Fix quickLogin not starting match making
diff --git a/src/Login.cpp b/src/Login.cpp index 41a353e..13fc79b 100644 --- a/src/Login.cpp +++ b/src/Login.cpp @@ -1,187 +1,187 @@ #include "Login.hpp" #include "../server/NetworkConstants.hpp" #include "engine/screen.hpp" #include "engine/procedure.hpp" #include "engine/fade.hpp" #include "engine/options.hpp" #include "gui/Button.hpp" #include "lobby.hpp" #include <jngl.hpp> #include <boost/bind/bind.hpp> #include <boost/lexical_cast.hpp> #include <sstream> #include <spdlog/spdlog.h> #ifdef __EMSCRIPTEN__ const std::string Login::server_("89.58.48.219"); // boomshine.de const int Login::port_ = 9999; #else // const std::string Login::server_("127.0.0.1"); const std::string Login::server_("89.58.48.219"); // boomshine.de // const std::string Login::server_("85.214.187.23"); // babynamensuche.de const int Login::port_ = 7070; #endif -Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu) +Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu, bool quickLogin) : menu_(multiplayerMenu), text_("connecting ..."), cancel_("Cancel", [this]() { OnCancel(); }), - socket_(new Socket) { + socket_(new Socket), quickLogin(quickLogin) { spdlog::info("Connecting to {}:{}", server_, port_); try { socket_->connect(server_, port_, [this]() { HandleConnect(); }); } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.setCenter(0, 200); } void Login::HandleConnect() { text_ = "sending ..."; spdlog::info("Sending protocol version {}", PROTOCOL_VERSION); socket_->send(std::to_string(PROTOCOL_VERSION), [this]() { ProtocolCheck1(); }); } void Login::ProtocolCheck1() { text_ = "receiving ..."; spdlog::info("Waiting for server accept connection"); socket_->receive([this](json data) { ProtocolCheck2(std::move(data)); }); } void Login::ProtocolCheck2(json temp) { if (temp["type"] != "ok") { text_ = "Error: "; if (const std::string msg = temp["msg"]; !msg.empty()) { text_ += msg; } else { text_ += temp.dump(); } OnError(); } else { if (menu_->GetName().empty()) { if (!menu_->GetPassword().empty()) { text_ = "Name must not be empty!"; return OnError(); } socket_->send(json{ { "type", "login_anonymous" } }, [this]() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; }); } else { socket_->send(json{ { "type", "login" }, { "name", menu_->GetName() }, { "password", menu_->GetPassword() } }, [this]() { HandleLogin1(); }); } } } void Login::HandleLogin1() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; } void Login::HandleLogin2(json temp) { if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else if (temp["type"] == "unknown name") { text_ = "No user with this name found.\nDo you want to register yourself?"; cancel_.setCenter(-350, 280); cancel_.SetText("No"); Button* yes = new Button("Yes", boost::bind(&Login::Register, this)); yes->setCenter(350, 280); addWidget(std::shared_ptr<Widget>(yes)); } else if (temp["type"] == "wrong password") { text_ = "The password you've entered\nis wrong. Please try again."; OnError(); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::Register() { json j{ { "type", "register" }, { "name", menu_->GetName() }, { "password", menu_->GetPassword() } }; spdlog::info("Sending: {}", j.dump()); socket_->send(j, boost::bind(&Login::HandleRegister1, this)); cancel_.setCenter(0, 200); cancel_.SetText("Cancel"); widgets_.clear(); // FIXME: Implement RemoveWidget function } void Login::HandleRegister1() { socket_->receive([this](json temp) { HandleRegister2(std::move(temp)); }); text_ = "please wait ..."; } void Login::HandleRegister2(json temp) { spdlog::debug("HandleRegister2"); if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::step() { try { if (socket_) { socket_->step(); } } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.step(); StepWidgets(); } void Login::GoToLobby(std::string username) { getOptions().lastLoginName = std::move(username); getOptions().Save(); jngl::setWork(std::make_shared<Fade>( - std::make_shared<Lobby>(std::move(socket_), menu_->getQuickLogin()))); + std::make_shared<Lobby>(std::move(socket_), quickLogin))); } void Login::draw() const { menu_->draw(); jngl::setColor(255, 255, 255, 220); jngl::drawRect(-jngl::getScreenWidth() / 2, -jngl::getScreenHeight() / 2, jngl::getScreenWidth(), jngl::getScreenHeight()); jngl::setFontColor(0, 0, 0); GetScreen().printCentered(text_, { 0, -150 }); cancel_.draw(); DrawWidgets(); } void Login::OnCancel() { jngl::setWork(menu_); } void Login::OnError() { // hacked together algorithm to word wrap long error messages: size_t pos = 42; while (jngl::getTextWidth(text_) > jngl::getScreenWidth() && pos < text_.size()) { size_t i = pos; while (i > 0 && text_[i - 1] != ' ') { if (text_[i] == '\n') { i = pos; break; } --i; } text_.insert(text_.begin() + i, '\n'); pos += 42; } cancel_.SetText("OK"); cancel_.setFocus(true); } diff --git a/src/Login.hpp b/src/Login.hpp index e25559f..4ea70a2 100644 --- a/src/Login.hpp +++ b/src/Login.hpp @@ -1,35 +1,36 @@ #pragma once #include "engine/work.hpp" #include "engine/socket.hpp" #include "gui/Button.hpp" #include "multiplayermenu.hpp" #include <boost/asio.hpp> class Login : public Work { public: - Login(std::shared_ptr<MultiplayerMenu>); + Login(std::shared_ptr<MultiplayerMenu>, bool quickLogin); void step(); void draw() const; void HandleConnect(); void ProtocolCheck1(); void ProtocolCheck2(json); void HandleLogin1(); void HandleLogin2(json); void OnCancel(); void OnError(); void Register(); void HandleRegister1(); void HandleRegister2(json); void GoToLobby(std::string username); private: std::shared_ptr<MultiplayerMenu> menu_; std::string text_; const static std::string server_; const static int port_; const static std::string protocolVersion_; Button cancel_; std::shared_ptr<Socket> socket_; + bool quickLogin; }; diff --git a/src/multiplayermenu.cpp b/src/multiplayermenu.cpp index c07ce02..e41dfd0 100644 --- a/src/multiplayermenu.cpp +++ b/src/multiplayermenu.cpp @@ -1,63 +1,59 @@ #include "multiplayermenu.hpp" #include "engine/screen.hpp" #include "engine/procedure.hpp" #include "engine/fade.hpp" #include "engine/options.hpp" #include "menu.hpp" #include "Login.hpp" #include <jngl.hpp> MultiplayerMenu::MultiplayerMenu(const bool quickLogin) : name_(new Input(50, -240)), password_(new Input(50, -100)), quickLogin(quickLogin) { addWidget(name_); addWidget(password_); login_.reset(new Button("Login", [this]() { OnLogin(); })); addWidget(login_); back_.reset(new Button("Back", [this]() { OnBack(); })); addWidget(back_); back_->setCenter(-350, 280); login_->setCenter(350, 280); password_->SetPassword(true); name_->setText(getOptions().lastLoginName); if (name_->getText() != "") { FocusNext(); } } void MultiplayerMenu::step() { StepWidgets(); if (jngl::keyPressed(jngl::key::Return) || quickLogin) { - quickLogin = false; // if an error happens we will be reactivated OnLogin(); + quickLogin = false; // if an error happens we will be reactivated } } void MultiplayerMenu::draw() const { jngl::setFontColor(0, 0, 0); jngl::print("Name:", -500, -240); jngl::print("Password:", -500, -100); DrawWidgets(); } void MultiplayerMenu::OnBack() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void MultiplayerMenu::OnLogin() { - jngl::setWork( - std::make_shared<Login>(std::dynamic_pointer_cast<MultiplayerMenu>(jngl::getWork()))); + jngl::setWork(std::make_shared<Login>( + std::dynamic_pointer_cast<MultiplayerMenu>(jngl::getWork()), quickLogin)); } std::string MultiplayerMenu::GetName() const { return name_->getText(); } std::string MultiplayerMenu::GetPassword() const { return password_->getText(); } - -bool MultiplayerMenu::getQuickLogin() const { - return quickLogin; -} diff --git a/src/multiplayermenu.hpp b/src/multiplayermenu.hpp index 9df2016..aad3934 100644 --- a/src/multiplayermenu.hpp +++ b/src/multiplayermenu.hpp @@ -1,28 +1,27 @@ #pragma once #include "engine/work.hpp" #include "gui/input.hpp" #include <memory> class Button; class MultiplayerMenu : public Work { public: MultiplayerMenu(bool quickLogin); void step(); void draw() const; void OnBack() const; void OnLogin(); std::string GetName() const; std::string GetPassword() const; void login(const std::string& name, const std::string& password); - bool getQuickLogin() const; private: std::shared_ptr<Button> back_; std::shared_ptr<Button> login_; std::shared_ptr<Input> name_; std::shared_ptr<Input> password_; bool quickLogin; };
jhasse/jntetri
da909465d893ec09c01f9577e8159edcd08392a7
server: Only show "xy left." message for logged in users
diff --git a/server/Server.cpp b/server/Server.cpp index 415f3f9..3a9109e 100644 --- a/server/Server.cpp +++ b/server/Server.cpp @@ -1,161 +1,160 @@ #include "Server.hpp" #include "Client.hpp" #include "NetworkConstants.hpp" #include <boost/bind/bind.hpp> #include <iostream> #include <soci/sqlite3/soci-sqlite3.h> #include <spdlog/spdlog.h> #include <optional> using boost::asio::ip::tcp; Server::Server() : socket(context), acceptor(context, tcp::endpoint(tcp::v4(), JNTETRI_PORT)), timer(context, boost::posix_time::seconds(15)), sql(soci::sqlite3, "jntetri.sqlite") { sql << "CREATE TABLE IF NOT EXISTS users (" "username VARCHAR(80) UNIQUE NOT NULL," "password VARCHAR(256) NOT NULL)"; timer.async_wait([this](const auto& e) { printStats(e); }); } Server::~Server() { socket.close(); } void Server::run() { boost::asio::spawn(context, [this](boost::asio::yield_context yield) { doAccept(yield); }); spdlog::info("start"); context.run(); } void Server::doAccept(boost::asio::yield_context yield) { while (true) { boost::asio::ip::tcp::socket socket(context); acceptor.async_accept(socket, yield); auto client = std::make_shared<Client>(*this, std::move(socket)); spdlog::info("new connection"); clients.emplace_back(client); boost::asio::spawn(context, [this, client](boost::asio::yield_context yield) { try { client->run(yield); } catch (std::exception& e) { client->log().error(e.what()); } client->log().info("disconnected"); { std::lock_guard<std::mutex> lock(matchmakingMutex); if (const auto it = std::find(matchmaking.begin(), matchmaking.end(), client); it != matchmaking.end()) { matchmaking.erase(it); } } - const auto username = client->getUsername(); clients.erase(std::find(clients.begin(), clients.end(), client)); - if (!username.empty()) { - addChatLine(yield, fmt::format("{} left.", username)); + if (client->isLoggedIn()) { + addChatLine(yield, fmt::format("{} left.", client->getUsername())); } }); } } void Server::addChatLine(boost::asio::yield_context yield, std::string line) { chatText += line; for (const auto& client : clients) { if (client->isLoggedIn()) { client->sendChatLine(yield, line); } } } LoginState Server::checkLogin(std::string username, std::string password) { soci::rowset<soci::row> rs = (sql.prepare << "select password from users where username = :username", soci::use(username, "username")); std::optional<std::string> realPassword; for (const auto& row : rs) { assert(!realPassword); realPassword = row.get<std::string>(0); } if (realPassword) { if (*realPassword == password) { // kick all other devices of this user: for (const auto& client : clients) { if (client->isLoggedIn() && client->getUsername() == username) { client->kick("Someone logged in from another device."); } } return LoginState::PasswordOK; } return LoginState::PasswordWrong; } return LoginState::UserDoesNotExist; } bool Server::registerUser(std::string username, std::string password) { try { sql << "insert into users (username, password) values(:username, :password)", soci::use(username), soci::use(password); } catch (soci::soci_error& e) { spdlog::error(e.what()); return false; } return true; } std::string Server::createAnonymousUser() { for (int i = 0; i < 10; ++i) { std::string name = "user" + std::to_string(rand() % 999999); if (registerUser(name, "")) { return name; } // already exists? Maybe we can login without a password: switch (checkLogin(name, "")) { case LoginState::PasswordWrong: break; case LoginState::UserDoesNotExist: assert(false); break; case LoginState::PasswordOK: return name; } } throw std::runtime_error("Couldn't generate a random username!"); } void Server::startMatchmaking(boost::asio::yield_context yield, std::shared_ptr<Client> client) { std::lock_guard<std::mutex> lock(matchmakingMutex); if (matchmaking.empty()) { matchmaking.emplace_back(client); addChatLine(yield, client->getUsername() + " started matchmaking."); } else { for (const auto& existingClient : matchmaking) { if (existingClient == client) { return; // somehow matchmaking was requested twice } } // Found opponent. Let's send p back to both clients so that the game starts. matchmaking.back()->setOpponent(client); client->setOpponent(matchmaking.back()); spdlog::info("matching '{}' and '{}'", matchmaking.back()->getUsername(), client->getUsername()); const int32_t seed = rand(); matchmaking.back()->sendStartGame(yield, seed); client->sendStartGame(yield, seed); matchmaking.pop_back(); } } std::string Server::loginAndGetWelcomeMessage(boost::asio::yield_context yield, const std::string& username) { addChatLine(yield, fmt::format("{} joined.", username)); size_t loggedIn = std::count_if(clients.begin(), clients.end(), [](const auto& client) { return client->isLoggedIn(); }) + 1 /* the current user doesn't count yet*/; return fmt::format("{} user{} online.", loggedIn, loggedIn == 1 ? "" : "s"); } void Server::printStats(const boost::system::error_code&) { spdlog::trace("connected clients: {}", clients.size()); timer.expires_from_now(boost::posix_time::seconds(15)); timer.async_wait([this](const auto& e) { printStats(e); }); }
jhasse/jntetri
3fcd2da19585f583591d3c45ab5a254358b01b0e
server: Fix invalid login message
diff --git a/server/Client.cpp b/server/Client.cpp index 249d34d..beaa035 100644 --- a/server/Client.cpp +++ b/server/Client.cpp @@ -1,227 +1,227 @@ #include "Client.hpp" #include "Server.hpp" #include "NetworkConstants.hpp" #include <boost/array.hpp> #include <boost/bind.hpp> #include <iostream> #include <nlohmann/json.hpp> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/spdlog.h> #include <thread> using nlohmann::json; Client::Client(Server& server, boost::asio::ip::tcp::socket socket) : socket(std::move(socket)), server(server) { commands["login"] = {false, std::bind(&Client::login, this, std::placeholders::_1, std::placeholders::_2)}; commands["login_anonymous"] = {false, std::bind(&Client::login_anonymous, this, std::placeholders::_1, std::placeholders::_2)}; commands["chat"] = {true, std::bind(&Client::chat, this, std::placeholders::_1, std::placeholders::_2)}; commands["game"] = {true, std::bind(&Client::game, this, std::placeholders::_1, std::placeholders::_2)}; commands["play"] = {true, std::bind(&Client::play, this, std::placeholders::_1, std::placeholders::_2)}; commands["register"] = {false, std::bind(&Client::register_user, this, std::placeholders::_1, std::placeholders::_2)}; commands["quit"] = {true, std::bind(&Client::quit, this, std::placeholders::_1, std::placeholders::_2)}; } void Client::login(boost::asio::yield_context yield, nlohmann::json data) { std::string user = data["name"]; std::string password = data["password"]; spdlog::info("login attempt from '{}' with password of length {}", user, password.size()); switch(server.checkLogin(user, password)) { case LoginState::UserDoesNotExist: errAndDisconnect(yield, "unknown name", "", false); break; case LoginState::PasswordOK: { loginAs(yield, std::move(user)); break; } case LoginState::PasswordWrong: errAndDisconnect(yield, "wrong password", "", false); break; } } void Client::login_anonymous(boost::asio::yield_context yield, nlohmann::json data) { loginAs(yield, server.createAnonymousUser()); } void Client::register_user(boost::asio::yield_context yield, nlohmann::json data) { std::string user = data["name"]; std::string pw = data["password"]; std::string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"; for (char c : user) { if (validChars.find(c) == std::string::npos) { errAndDisconnect(yield, "error", "You're username may only contain latin letters, numbers or hypens."); return; } } if(server.registerUser(user, pw)) { username = user; const auto msg = server.loginAndGetWelcomeMessage(yield, user); okMsg(yield); sendChatLine(yield, msg); } else { errAndDisconnect(yield, "error", "Something went wrong during register!"); } } void Client::chat(boost::asio::yield_context yield, nlohmann::json data) { std::string newChatLine = *username + ": " + data["text"].get<std::string>(); server.addChatLine(yield, newChatLine); log().trace("chat: {}", data["text"]); } void Client::play(boost::asio::yield_context yield, nlohmann::json data) { server.startMatchmaking(yield, shared_from_this()); } void Client::quit(boost::asio::yield_context yield, nlohmann::json) { if (opponent) { opponent->sendOpponentQuit(yield); opponent.reset(); } } void Client::sendStartGame(boost::asio::yield_context yield, const int32_t seed) { socket.send(yield, fmt::format("{{\"type\": \"play\", \"seed\": {} }}", seed)); } void Client::sendChatLine(boost::asio::yield_context yield, std::string line) { if (!isLoggedIn()) { return; } auto j = nlohmann::json { {"type", "chat"}, {"text", line} }; socket.send(yield, j.dump()); } void Client::sendOpponentQuit(boost::asio::yield_context yield) { auto j = nlohmann::json { {"type", "opponentQuit"} }; socket.send(yield, j.dump()); } void Client::game(boost::asio::yield_context yield, nlohmann::json data) { if (!opponent) { spdlog::error("Can't process \"game\" without opponent!"); return; } try { opponent->forward(yield, data["time"].get<uint8_t>(), data["control"].get<uint8_t>()); } catch(boost::system::system_error& e) { log().warn("opponent {} disconnected: {}", opponent->getUsername(), e.what()); opponent.reset(); socket.send(yield, "{\"type\": \"disconnected\"}"); } } void Client::loginAs(boost::asio::yield_context yield, std::string name) { createLogger("client " + name); log().info("logged in, sending \"ok\" ..."); - const auto msg = server.loginAndGetWelcomeMessage(yield, *username); + const auto msg = server.loginAndGetWelcomeMessage(yield, name); username = std::move(name); okMsg(yield); sendChatLine(yield, msg); } void Client::okMsg(boost::asio::yield_context yield) { socket.send(yield, json{ { "type", "ok" }, { "name", *username } }.dump()); log().trace("sent \"ok\""); } void Client::errAndDisconnect(boost::asio::yield_context yield, std::string type, std::string msg, bool really_disconnect) { auto j = nlohmann::json { {"type", type }}; if(msg != "") { j["msg"] = msg; } socket.send(yield, j.dump()); log().trace("sent {}", j.dump()); if(really_disconnect) { running = false; } } void Client::run(boost::asio::yield_context yield) { uint32_t protocolVersion; std::istringstream is(socket.receive(yield)); is >> protocolVersion; if (protocolVersion != PROTOCOL_VERSION) { log().error("protocol version: ", protocolVersion); errAndDisconnect(yield, "error", "Protocol version mismatch!"); return; } okMsg(yield); while (running) { try { std::string line = socket.receive(yield); auto data = nlohmann::json::parse(line); log().trace("got data {}", data.dump()); auto current_cmd = commands.find(data["type"]); if (current_cmd == commands.end()) { errAndDisconnect(yield, "error", "Unknown command!"); } else if (current_cmd->second.first && !isLoggedIn()) { errAndDisconnect(yield, "error", "You need to be logged in to use this command!"); } else { current_cmd->second.second(yield, data); } } catch (const boost::system::system_error& e) { if (e.code() == boost::asio::error::operation_aborted) { if (kickReason) { errAndDisconnect(yield, "error", *kickReason); break; } } else { throw e; } } } if (username) { std::cout << "Client " << *username << " exiting." << std::endl; } } void Client::setOpponent(std::shared_ptr<Client> opponent) { this->opponent = std::move(opponent); } bool Client::isLoggedIn() const { return username.has_value() && !kickReason; } std::string Client::getUsername() const { return username ? *username : "<invalid>"; } void Client::forward(boost::asio::yield_context yield, uint8_t time, uint8_t command) { nlohmann::json j = { { "type", "game" }, { "control", command }, { "time", time }, }; socket.send(yield, j.dump()); } void Client::createLogger(const std::string& name) { try { logger = spdlog::stdout_color_mt(name, spdlog::color_mode::always); } catch (spdlog::spdlog_ex&) { logger = spdlog::get(name); } } spdlog::logger& Client::log() { if (!logger) { createLogger("unnamed client " + std::to_string(ptrdiff_t(this))); } return *logger; } void Client::kick(std::string reason) { socket.cancel(); kickReason = reason; }
jhasse/jntetri
95881d5e8aa7acd7c90fe9d412cd271f865530dc
Skip Intro in Release build if first time
diff --git a/src/Intro.cpp b/src/Intro.cpp index 2ff2a26..230fb44 100644 --- a/src/Intro.cpp +++ b/src/Intro.cpp @@ -1,77 +1,78 @@ #include "Intro.hpp" #include "constants.hpp" #include "engine/fade.hpp" #include "engine/options.hpp" #include "engine/procedure.hpp" #include "engine/screen.hpp" #include "fonts.hpp" #include "Game.hpp" #include "menu.hpp" #include "multiplayermenu.hpp" #include <jngl.hpp> Intro::Intro() : blink_(0), finished_(false) { } void Intro::draw() const { jngl::setFontSize(250); jngl::setFontColor(50, 50, 50); GetScreen().printCentered("JNTETRI", { 0, -250 }); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(0, 150); float percentage; if (resizeGraphics_.isFinished(percentage)) { finished_ = true; jngl::setFontColor(0, 0, 0, blink_ > 255 ? 510 - blink_ : blink_); fonts::label(); // TODO: find a better way to load all fonts GetScreen().printCentered("Press any key to continue", { 0, 0 }); } else { GetScreen().printCentered(std::to_string(int(percentage)) + " %", { 0, 0 }); } jngl::popMatrix(); jngl::setFontColor(100, 100, 100, 255); jngl::setFontSize(35); GetScreen().printCentered(programVersion, { 0, 360 }); GetScreen().printCentered("https://bixense.itch.io/jntetri", { 0, 430 }); GetScreen().printCentered("Copyright 2009-2019 bixense.com", { 0, 500 }); } void Intro::step() { blink_ += 4; if (blink_ > 2 * 255) { blink_ = 0; } #ifdef NDEBUG - bool anyKeyPressed = jngl::mousePressed() || jngl::keyPressed(jngl::key::Any); + bool anyKeyPressed = jngl::mousePressed() || jngl::keyPressed(jngl::key::Any) || + getOptions().lastLoginName.empty(); #else bool anyKeyPressed = true; #endif if (anyKeyPressed && finished_) { bool login = false; for (const auto& arg : jngl::getArgs()) { if (arg == "--login") { login = true; } if (login) { getOptions().lastLoginName = arg; } } if (login) { jngl::setWork<MultiplayerMenu>(false); } else { if (getOptions().lastLoginName.empty()) { jngl::setWork<MultiplayerMenu>(true); } else { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } } // jngl::setWork(std::make_shared<Fade>(std::make_shared<ReplayPlayer>("test3.jtr"))); // jngl::setWork(std::make_shared<Game>(GameType::NORMAL, static_cast<int>(time(0)), // false)); } }
jhasse/jntetri
6760f35b28ade8eb1dcb41fafbc1dc0d4708aec4
Show better error message on protocol mismatch
diff --git a/src/Login.cpp b/src/Login.cpp index 15d063b..41a353e 100644 --- a/src/Login.cpp +++ b/src/Login.cpp @@ -1,183 +1,187 @@ #include "Login.hpp" #include "../server/NetworkConstants.hpp" #include "engine/screen.hpp" #include "engine/procedure.hpp" #include "engine/fade.hpp" #include "engine/options.hpp" #include "gui/Button.hpp" #include "lobby.hpp" #include <jngl.hpp> #include <boost/bind/bind.hpp> #include <boost/lexical_cast.hpp> #include <sstream> #include <spdlog/spdlog.h> #ifdef __EMSCRIPTEN__ const std::string Login::server_("89.58.48.219"); // boomshine.de const int Login::port_ = 9999; #else // const std::string Login::server_("127.0.0.1"); const std::string Login::server_("89.58.48.219"); // boomshine.de // const std::string Login::server_("85.214.187.23"); // babynamensuche.de const int Login::port_ = 7070; #endif Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu) : menu_(multiplayerMenu), text_("connecting ..."), cancel_("Cancel", [this]() { OnCancel(); }), socket_(new Socket) { spdlog::info("Connecting to {}:{}", server_, port_); try { socket_->connect(server_, port_, [this]() { HandleConnect(); }); } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.setCenter(0, 200); } void Login::HandleConnect() { text_ = "sending ..."; spdlog::info("Sending protocol version {}", PROTOCOL_VERSION); socket_->send(std::to_string(PROTOCOL_VERSION), [this]() { ProtocolCheck1(); }); } void Login::ProtocolCheck1() { text_ = "receiving ..."; spdlog::info("Waiting for server accept connection"); socket_->receive([this](json data) { ProtocolCheck2(std::move(data)); }); } void Login::ProtocolCheck2(json temp) { if (temp["type"] != "ok") { text_ = "Error: "; - text_ += temp; + if (const std::string msg = temp["msg"]; !msg.empty()) { + text_ += msg; + } else { + text_ += temp.dump(); + } OnError(); } else { if (menu_->GetName().empty()) { if (!menu_->GetPassword().empty()) { text_ = "Name must not be empty!"; return OnError(); } socket_->send(json{ { "type", "login_anonymous" } }, [this]() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; }); } else { socket_->send(json{ { "type", "login" }, { "name", menu_->GetName() }, { "password", menu_->GetPassword() } }, [this]() { HandleLogin1(); }); } } } void Login::HandleLogin1() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; } void Login::HandleLogin2(json temp) { if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else if (temp["type"] == "unknown name") { text_ = "No user with this name found.\nDo you want to register yourself?"; cancel_.setCenter(-350, 280); cancel_.SetText("No"); Button* yes = new Button("Yes", boost::bind(&Login::Register, this)); yes->setCenter(350, 280); addWidget(std::shared_ptr<Widget>(yes)); } else if (temp["type"] == "wrong password") { text_ = "The password you've entered\nis wrong. Please try again."; OnError(); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::Register() { json j{ { "type", "register" }, { "name", menu_->GetName() }, { "password", menu_->GetPassword() } }; spdlog::info("Sending: {}", j.dump()); socket_->send(j, boost::bind(&Login::HandleRegister1, this)); cancel_.setCenter(0, 200); cancel_.SetText("Cancel"); widgets_.clear(); // FIXME: Implement RemoveWidget function } void Login::HandleRegister1() { socket_->receive([this](json temp) { HandleRegister2(std::move(temp)); }); text_ = "please wait ..."; } void Login::HandleRegister2(json temp) { spdlog::debug("HandleRegister2"); if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::step() { try { if (socket_) { socket_->step(); } } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.step(); StepWidgets(); } void Login::GoToLobby(std::string username) { getOptions().lastLoginName = std::move(username); getOptions().Save(); jngl::setWork(std::make_shared<Fade>( std::make_shared<Lobby>(std::move(socket_), menu_->getQuickLogin()))); } void Login::draw() const { menu_->draw(); jngl::setColor(255, 255, 255, 220); jngl::drawRect(-jngl::getScreenWidth() / 2, -jngl::getScreenHeight() / 2, jngl::getScreenWidth(), jngl::getScreenHeight()); jngl::setFontColor(0, 0, 0); GetScreen().printCentered(text_, { 0, -150 }); cancel_.draw(); DrawWidgets(); } void Login::OnCancel() { jngl::setWork(menu_); } void Login::OnError() { // hacked together algorithm to word wrap long error messages: size_t pos = 42; while (jngl::getTextWidth(text_) > jngl::getScreenWidth() && pos < text_.size()) { size_t i = pos; while (i > 0 && text_[i - 1] != ' ') { if (text_[i] == '\n') { i = pos; break; } --i; } text_.insert(text_.begin() + i, '\n'); pos += 42; } cancel_.SetText("OK"); cancel_.setFocus(true); }
jhasse/jntetri
4d96cc8aba58f286f56f0c979c4069cbd9e8e2e0
Avoid endless quickLogin loop on errors
diff --git a/src/multiplayermenu.cpp b/src/multiplayermenu.cpp index efd51b8..c07ce02 100644 --- a/src/multiplayermenu.cpp +++ b/src/multiplayermenu.cpp @@ -1,62 +1,63 @@ #include "multiplayermenu.hpp" #include "engine/screen.hpp" #include "engine/procedure.hpp" #include "engine/fade.hpp" #include "engine/options.hpp" #include "menu.hpp" #include "Login.hpp" #include <jngl.hpp> MultiplayerMenu::MultiplayerMenu(const bool quickLogin) : name_(new Input(50, -240)), password_(new Input(50, -100)), quickLogin(quickLogin) { addWidget(name_); addWidget(password_); login_.reset(new Button("Login", [this]() { OnLogin(); })); addWidget(login_); back_.reset(new Button("Back", [this]() { OnBack(); })); addWidget(back_); back_->setCenter(-350, 280); login_->setCenter(350, 280); password_->SetPassword(true); name_->setText(getOptions().lastLoginName); if (name_->getText() != "") { FocusNext(); } } void MultiplayerMenu::step() { StepWidgets(); if (jngl::keyPressed(jngl::key::Return) || quickLogin) { + quickLogin = false; // if an error happens we will be reactivated OnLogin(); } } void MultiplayerMenu::draw() const { jngl::setFontColor(0, 0, 0); jngl::print("Name:", -500, -240); jngl::print("Password:", -500, -100); DrawWidgets(); } void MultiplayerMenu::OnBack() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void MultiplayerMenu::OnLogin() { jngl::setWork( std::make_shared<Login>(std::dynamic_pointer_cast<MultiplayerMenu>(jngl::getWork()))); } std::string MultiplayerMenu::GetName() const { return name_->getText(); } std::string MultiplayerMenu::GetPassword() const { return password_->getText(); } bool MultiplayerMenu::getQuickLogin() const { return quickLogin; }
jhasse/jntetri
1b8df01de7bd5107fb817df0620b8daf6a84f234
Only show Quit button if the platform can quit
diff --git a/src/menu.cpp b/src/menu.cpp index 7a046b6..52e905d 100644 --- a/src/menu.cpp +++ b/src/menu.cpp @@ -1,73 +1,75 @@ #include "menu.hpp" #include "engine/paths.hpp" #include "engine/procedure.hpp" #include "engine/fade.hpp" #include "gui/ButtonBox.hpp" #include "optionsmenu.hpp" #include "engine/screen.hpp" #include "Game.hpp" #include "multiplayermenu.hpp" #include <ctime> Menu::Menu() : buttonBox_(new ButtonBox(-450, 0)), normalHighscore_(GameType::NORMAL), fiftyLinesHighscore_(GameType::FIFTYLINES) { buttonBox_->add("Normal", std::bind(&Menu::Normal, this)); buttonBox_->add("50 Lines", std::bind(&Menu::FiftyLines, this)); buttonBox_->add("Multiplayer", []() { jngl::setWork(std::make_shared<Fade>(std::make_shared<MultiplayerMenu>(false))); }); // buttonBox_->add("Multiplayer", []() { // jngl::setWork(std::make_shared<Fade>(std::make_shared<SplitScreen>(std::make_shared<GamepadControl>(1)))); // }); buttonBox_->add("Options", std::bind(&Menu::OptionsMenuCallback, this)); - buttonBox_->add("Quit", std::bind(&Menu::QuitGame, this)); + if (jngl::canQuit()) { + buttonBox_->add("Quit", std::bind(&Menu::QuitGame, this)); + } addWidget(buttonBox_); } void Menu::BlinkHighscore(Data data) { normalHighscore_.Blink(data); fiftyLinesHighscore_.Blink(data); } void Menu::step() { StepWidgets(); } void Menu::draw() const { jngl::setBackgroundColor(0xffffff_rgb); DrawWidgets(); GetScreen().DrawCentered("box", 340, 0); jngl::pushMatrix(); jngl::translate(-20, -400); jngl::setFontSize(50); jngl::setFontColor(0, 0, 0); jngl::print("Highscores Normal", 0, -90); normalHighscore_.draw(); jngl::translate(0, 530); jngl::setFontColor(0, 0, 0); jngl::print("Highscores 50 Lines", 0, -90); fiftyLinesHighscore_.draw(); jngl::popMatrix(); } void Menu::Normal() const { jngl::setWork(std::make_shared<Fade>( std::make_shared<Game>(GameType::NORMAL, static_cast<int>(time(0)), false))); } void Menu::FiftyLines() const { jngl::setWork(std::make_shared<Fade>( std::make_shared<Game>(GameType::FIFTYLINES, static_cast<int>(time(0)), false))); } void Menu::OptionsMenuCallback() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<OptionsMenu>())); } void Menu::QuitGame() const { jngl::quit(); }
jhasse/jntetri
2b17b1b3e6067aeb3b8cf37666b5a52b8a1eb640
Login automatically when started for the first time
diff --git a/src/Intro.cpp b/src/Intro.cpp index 885bac0..2ff2a26 100644 --- a/src/Intro.cpp +++ b/src/Intro.cpp @@ -1,73 +1,77 @@ #include "Intro.hpp" #include "constants.hpp" #include "engine/fade.hpp" #include "engine/options.hpp" #include "engine/procedure.hpp" #include "engine/screen.hpp" #include "fonts.hpp" #include "Game.hpp" #include "menu.hpp" #include "multiplayermenu.hpp" #include <jngl.hpp> Intro::Intro() : blink_(0), finished_(false) { } void Intro::draw() const { jngl::setFontSize(250); jngl::setFontColor(50, 50, 50); GetScreen().printCentered("JNTETRI", { 0, -250 }); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(0, 150); float percentage; if (resizeGraphics_.isFinished(percentage)) { finished_ = true; jngl::setFontColor(0, 0, 0, blink_ > 255 ? 510 - blink_ : blink_); fonts::label(); // TODO: find a better way to load all fonts GetScreen().printCentered("Press any key to continue", { 0, 0 }); } else { GetScreen().printCentered(std::to_string(int(percentage)) + " %", { 0, 0 }); } jngl::popMatrix(); jngl::setFontColor(100, 100, 100, 255); jngl::setFontSize(35); GetScreen().printCentered(programVersion, { 0, 360 }); GetScreen().printCentered("https://bixense.itch.io/jntetri", { 0, 430 }); GetScreen().printCentered("Copyright 2009-2019 bixense.com", { 0, 500 }); } void Intro::step() { blink_ += 4; if (blink_ > 2 * 255) { blink_ = 0; } #ifdef NDEBUG bool anyKeyPressed = jngl::mousePressed() || jngl::keyPressed(jngl::key::Any); #else bool anyKeyPressed = true; #endif if (anyKeyPressed && finished_) { bool login = false; for (const auto& arg : jngl::getArgs()) { if (arg == "--login") { login = true; } if (login) { getOptions().lastLoginName = arg; } } if (login) { - jngl::setWork<MultiplayerMenu>(); + jngl::setWork<MultiplayerMenu>(false); } else { - jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); + if (getOptions().lastLoginName.empty()) { + jngl::setWork<MultiplayerMenu>(true); + } else { + jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); + } } // jngl::setWork(std::make_shared<Fade>(std::make_shared<ReplayPlayer>("test3.jtr"))); // jngl::setWork(std::make_shared<Game>(GameType::NORMAL, static_cast<int>(time(0)), // false)); } } diff --git a/src/Login.cpp b/src/Login.cpp index 84c3ef4..15d063b 100644 --- a/src/Login.cpp +++ b/src/Login.cpp @@ -1,179 +1,183 @@ #include "Login.hpp" #include "../server/NetworkConstants.hpp" #include "engine/screen.hpp" #include "engine/procedure.hpp" #include "engine/fade.hpp" #include "engine/options.hpp" #include "gui/Button.hpp" #include "lobby.hpp" #include <jngl.hpp> #include <boost/bind/bind.hpp> #include <boost/lexical_cast.hpp> #include <sstream> #include <spdlog/spdlog.h> #ifdef __EMSCRIPTEN__ const std::string Login::server_("89.58.48.219"); // boomshine.de const int Login::port_ = 9999; #else // const std::string Login::server_("127.0.0.1"); const std::string Login::server_("89.58.48.219"); // boomshine.de // const std::string Login::server_("85.214.187.23"); // babynamensuche.de const int Login::port_ = 7070; #endif Login::Login(std::shared_ptr<MultiplayerMenu> multiplayerMenu) : menu_(multiplayerMenu), text_("connecting ..."), cancel_("Cancel", [this]() { OnCancel(); }), socket_(new Socket) { spdlog::info("Connecting to {}:{}", server_, port_); try { socket_->connect(server_, port_, [this]() { HandleConnect(); }); } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.setCenter(0, 200); } void Login::HandleConnect() { text_ = "sending ..."; spdlog::info("Sending protocol version {}", PROTOCOL_VERSION); socket_->send(std::to_string(PROTOCOL_VERSION), [this]() { ProtocolCheck1(); }); } void Login::ProtocolCheck1() { text_ = "receiving ..."; spdlog::info("Waiting for server accept connection"); socket_->receive([this](json data) { ProtocolCheck2(std::move(data)); }); } void Login::ProtocolCheck2(json temp) { if (temp["type"] != "ok") { text_ = "Error: "; text_ += temp; OnError(); } else { if (menu_->GetName().empty()) { if (!menu_->GetPassword().empty()) { text_ = "Name must not be empty!"; return OnError(); } socket_->send(json{ { "type", "login_anonymous" } }, [this]() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; }); } else { socket_->send(json{ { "type", "login" }, { "name", menu_->GetName() }, { "password", menu_->GetPassword() } }, [this]() { HandleLogin1(); }); } } } void Login::HandleLogin1() { socket_->receive([this](json temp) { HandleLogin2(std::move(temp)); }); text_ = "waiting for authentification ..."; } void Login::HandleLogin2(json temp) { if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else if (temp["type"] == "unknown name") { text_ = "No user with this name found.\nDo you want to register yourself?"; cancel_.setCenter(-350, 280); cancel_.SetText("No"); Button* yes = new Button("Yes", boost::bind(&Login::Register, this)); yes->setCenter(350, 280); addWidget(std::shared_ptr<Widget>(yes)); } else if (temp["type"] == "wrong password") { text_ = "The password you've entered\nis wrong. Please try again."; OnError(); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::Register() { json j{ { "type", "register" }, { "name", menu_->GetName() }, { "password", menu_->GetPassword() } }; spdlog::info("Sending: {}", j.dump()); socket_->send(j, boost::bind(&Login::HandleRegister1, this)); cancel_.setCenter(0, 200); cancel_.SetText("Cancel"); widgets_.clear(); // FIXME: Implement RemoveWidget function } void Login::HandleRegister1() { socket_->receive([this](json temp) { HandleRegister2(std::move(temp)); }); text_ = "please wait ..."; } void Login::HandleRegister2(json temp) { spdlog::debug("HandleRegister2"); if (temp["type"] == "ok") { GoToLobby(temp["name"]); } else { text_ = "Error: "; text_ += temp.dump(); OnError(); } } void Login::step() { try { - socket_->step(); + if (socket_) { + socket_->step(); + } } catch(std::exception& e) { text_ = "Exception: "; text_ += e.what(); OnError(); } cancel_.step(); StepWidgets(); } void Login::GoToLobby(std::string username) { getOptions().lastLoginName = std::move(username); - jngl::setWork(std::make_shared<Fade>(std::make_shared<Lobby>(socket_))); + getOptions().Save(); + jngl::setWork(std::make_shared<Fade>( + std::make_shared<Lobby>(std::move(socket_), menu_->getQuickLogin()))); } void Login::draw() const { menu_->draw(); jngl::setColor(255, 255, 255, 220); jngl::drawRect(-jngl::getScreenWidth() / 2, -jngl::getScreenHeight() / 2, jngl::getScreenWidth(), jngl::getScreenHeight()); jngl::setFontColor(0, 0, 0); GetScreen().printCentered(text_, { 0, -150 }); cancel_.draw(); DrawWidgets(); } void Login::OnCancel() { jngl::setWork(menu_); } void Login::OnError() { // hacked together algorithm to word wrap long error messages: size_t pos = 42; while (jngl::getTextWidth(text_) > jngl::getScreenWidth() && pos < text_.size()) { size_t i = pos; while (i > 0 && text_[i - 1] != ' ') { if (text_[i] == '\n') { i = pos; break; } --i; } text_.insert(text_.begin() + i, '\n'); pos += 42; } cancel_.SetText("OK"); cancel_.setFocus(true); } diff --git a/src/NetworkControl.cpp b/src/NetworkControl.cpp index 8c9d5b3..76b44a2 100644 --- a/src/NetworkControl.cpp +++ b/src/NetworkControl.cpp @@ -1,113 +1,113 @@ #include "NetworkControl.hpp" #include "engine/socket.hpp" #include "gui/MessageBox.hpp" #include "jngl/window.hpp" #include "jngl/work.hpp" #include "lobby.hpp" #include "multiplayermenu.hpp" #include <nlohmann/json.hpp> #include <spdlog/spdlog.h> NetworkControl::NetworkControl(std::shared_ptr<Socket> socket) : socket(std::move(socket)) { this->socket->receive([this](json buf) { handleReceive(std::move(buf)); }); } bool NetworkControl::step(const std::function<void(ControlType)>& set) { if (!sendQueue.empty() && !sendingInProgress) { sendingInProgress = true; nlohmann::json j = { { "type", "game" }, { "time", sendQueue.front().first }, { "control", sendQueue.front().second }, }; socket->send(j, [this]() { sendQueue.pop(); // spdlog::info("sent package success. {} to go.", sendQueue.size()); sendingInProgress = false; }); } socket->step(); if (nullPackagesReceived < 1) { return false; } bool handledNullPackage = false; while ((time % BUFFER_LENGTH) == data.front().first) { if (data.front().second == ControlType::Null) { if (handledNullPackage) { break; // Don't skip ahead if there are no commands between two null packages } handledNullPackage = true; --nullPackagesReceived; } else { set(data.front().second); // execute command } data.pop(); if (data.empty()) { break; } } ++time; return true; } void NetworkControl::handleReceive(json j) { if (j["type"] == "game") { uint8_t time = j["time"].get<uint8_t>(); uint8_t control = j["control"].get<uint8_t>(); if (control >= static_cast<int>(ControlType::LastValue)) { spdlog::error("invalid control type in package: {}", control); } else { if (control == static_cast<uint8_t>(ControlType::Null)) { // spdlog::info("Null package received."); ++nullPackagesReceived; } data.push( std::pair<unsigned char, ControlType>(time, static_cast<ControlType>(control))); } } else if (j["type"] == "opponentQuit") { jngl::setWork<MessageBox>("Your opponent left.", - std::make_shared<Lobby>(std::move(socket))); + std::make_shared<Lobby>(std::move(socket), false)); return; } else if (j["type"] == "disconnected") { jngl::setWork<MessageBox>("Your opponent disconnected.", - std::make_shared<Lobby>(std::move(socket))); + std::make_shared<Lobby>(std::move(socket), false)); return; } else if (j["type"] == "error") { - jngl::setWork<MessageBox>(j["msg"], std::make_shared<MultiplayerMenu>()); + jngl::setWork<MessageBox>(j["msg"], std::make_shared<MultiplayerMenu>(false)); return; } else { spdlog::error("Unknown package: {}", j.dump()); } socket->receive([this](json buf) { handleReceive(std::move(buf)); }); } void NetworkControl::stepSend(Control& control) { if (sendTime % BUFFER_LENGTH == 0) { sendQueue.push(std::pair<uint8_t, ControlType>(0, ControlType::Null)); } control.forEach([this](ControlType c) { sendQueue.push(std::pair<uint8_t, ControlType>(sendTime % BUFFER_LENGTH, c)); }); ++sendTime; } bool NetworkControl::desync() const { std::stringstream sstream; sstream << "time: " << time << " sendTime: " << sendTime << " nullPackagesReceived: " << nullPackagesReceived << " sendQueue.size(): " << sendQueue.size(); jngl::setTitle(sstream.str()); return std::abs(time - sendTime) > 1000; } void NetworkControl::sendQuit() { socket->send(json{ { "type", "quit" } }, [this]() { spdlog::info("sent quit success."); }); } std::shared_ptr<Socket> NetworkControl::getSocket() { return socket; } diff --git a/src/SplitScreen.cpp b/src/SplitScreen.cpp index ab65c99..818fdb3 100644 --- a/src/SplitScreen.cpp +++ b/src/SplitScreen.cpp @@ -1,98 +1,98 @@ #include "SplitScreen.hpp" #include "engine/fade.hpp" #include "engine/screen.hpp" #include "Field.hpp" #include "NetworkControl.hpp" #include "NetworkRecorder.hpp" #include "lobby.hpp" #include <jngl/matrix.hpp> #include <jngl/font.hpp> #include <memory> #include <sstream> SplitScreen::SplitScreen(std::shared_ptr<ControlBase> opponentControl, const int32_t seed) : opponentControl(opponentControl) { reset(seed); } SplitScreen::~SplitScreen() = default; void SplitScreen::reset(const int32_t seed) { freezeCountdown = 0; field1.reset(new Field(seed, wins1, 0)); // FIXME: We shouldn't know about NetworkControl here if (const auto networkControl = std::dynamic_pointer_cast<NetworkControl>(opponentControl)) { field1->setControl(new NetworkRecorder( { std::make_shared<KeyboardControl>(), std::make_shared<GamepadControl>(0) }, networkControl)); field1->onUserQuit([networkControl]() { networkControl->sendQuit(); - jngl::setWork<Fade>(std::make_shared<Lobby>(networkControl->getSocket())); + jngl::setWork<Fade>(std::make_shared<Lobby>(networkControl->getSocket(), false)); }); } field2.reset(new Field(seed, wins2, 0)); field2->setControl(new Control{ opponentControl }); field1->setCheckDesync([this]() { return field2->desync(); }); } void SplitScreen::step() { field1->step(); field2->step(); if (freezeCountdown > 0) { --freezeCountdown; if (freezeCountdown == 1) { if (const auto networkControl = std::dynamic_pointer_cast<NetworkControl>(opponentControl)) { - jngl::setWork<Lobby>(networkControl->getSocket()); + jngl::setWork<Lobby>(networkControl->getSocket(), false); } else { reset(123); // TODO: Decide on next seed } } } else { const auto penalty = [](const int cleared) { switch(cleared) { case 2: return 1; case 3: return 2; case 4: return 4; } return 0; }; field2->addJunk(penalty(field1->getLinesCleared())); field1->addJunk(penalty(field2->getLinesCleared())); if (field1->GameOver()) { ++wins2; freezeCountdown = 200; } if (field2->GameOver()) { ++wins1; freezeCountdown = 200; } } } void SplitScreen::draw() const { jngl::pushMatrix(); jngl::translate(-660, 0); field1->draw(); jngl::translate(1320, 0); field2->draw(); jngl::popMatrix(); jngl::setFontSize(60); jngl::pushMatrix(); jngl::translate(-180, -500); field1->drawNextTetromino(); jngl::translate(330, 0); jngl::setFontColor(0, 0, 0, 150); jngl::setSpriteAlpha(150); field2->drawNextTetromino(); jngl::setFontColor(0, 0, 0, 255); jngl::setSpriteAlpha(255); jngl::popMatrix(); std::stringstream sstream; sstream << wins1 << " : " << wins2; jngl::setFontSize(140); GetScreen().printCentered(sstream.str(), { 0, 0 }); } diff --git a/src/lobby.cpp b/src/lobby.cpp index 11637d1..7094f77 100644 --- a/src/lobby.cpp +++ b/src/lobby.cpp @@ -1,99 +1,102 @@ #include "lobby.hpp" #include "engine/fade.hpp" #include "engine/procedure.hpp" #include "engine/screen.hpp" #include "gui/MessageBox.hpp" #include "multiplayermenu.hpp" #include "NetworkControl.hpp" #include "SplitScreen.hpp" #include <jngl.hpp> #include <nlohmann/json.hpp> #include <spdlog/spdlog.h> -Lobby::Lobby(std::shared_ptr<Socket> socket) +Lobby::Lobby(std::shared_ptr<Socket> socket, bool quickLogin) : socket_(socket), chatText_(""), input_(new Input(-700, 500)) { logout_.reset(new Button("Logout", [this]() { OnLogout(); })); play_.reset(new Button("Play!™", [this]() { OnPlay(); })); startReceiving(); input_->setMaxWidth(2500); addWidget(input_); addWidget(logout_); addWidget(play_); logout_->setCenter(-450, -450); play_->setCenter(450, -450); + if (quickLogin) { + OnPlay(); + } } void Lobby::OnLogout() { - jngl::setWork(std::make_shared<Fade>(std::make_shared<MultiplayerMenu>())); + jngl::setWork(std::make_shared<Fade>(std::make_shared<MultiplayerMenu>(false))); } void Lobby::OnPlay() { play_->setSensitive(false); socket_->send(json{ { "type", "play" } }, []() { spdlog::info("Successfully sent 'play'."); }); } void Lobby::step() { try { socket_->step(); } catch (std::exception& e) { jngl::setWork(std::make_shared<Fade>( - std::make_shared<MessageBox>(e.what(), std::make_shared<MultiplayerMenu>()))); + std::make_shared<MessageBox>(e.what(), std::make_shared<MultiplayerMenu>(false)))); } if (jngl::keyPressed(jngl::key::Return)) { nlohmann::json j = { { "type", "chat" }, { "text", input_->getText() }, }; spdlog::debug("Sending: {}", j.dump()); socket_->send(j, [this]() { OnMessageSent(); }); input_->setSensitive(false); } StepWidgets(); } void Lobby::OnMessageSent() { input_->setText(""); input_->setSensitive(true); } void Lobby::draw() const { jngl::setFontColor(0, 0, 0); jngl::setFontSize(35); jngl::print(chatText_, -700, -250); DrawWidgets(); } void Lobby::handleReceive(json buf) { if (buf["type"] == "chat") { chatText_ += buf["text"]; chatText_ += '\n'; int lineCount = 0; size_t pos = 0; while ((pos = chatText_.find_first_of("\n", pos + 1)) != std::string::npos) { ++lineCount; } if (lineCount > 13) { pos = chatText_.find_first_of("\n"); chatText_ = chatText_.substr(pos + 1); } } else if (buf["type"] == "play") { // Matchmaking was successful and an opponent found. Let's start the game. spdlog::debug("Starting match making"); auto control = std::make_shared<NetworkControl>(socket_); jngl::setWork(std::make_shared<Fade>( std::make_shared<SplitScreen>(control, buf["seed"].get<int32_t>()))); return; // move out of Lobby loop } else if (buf["type"] == "error") { - jngl::setWork<MessageBox>(buf["msg"], std::make_shared<MultiplayerMenu>()); + jngl::setWork<MessageBox>(buf["msg"], std::make_shared<MultiplayerMenu>(false)); return; } else { spdlog::warn("Received unknown type: {}", buf); } startReceiving(); } void Lobby::startReceiving() { socket_->receive([this](json buf) { handleReceive(std::move(buf)); }); } diff --git a/src/lobby.hpp b/src/lobby.hpp index b953f93..9d1e514 100644 --- a/src/lobby.hpp +++ b/src/lobby.hpp @@ -1,29 +1,30 @@ #pragma once #include "engine/work.hpp" #include "engine/socket.hpp" #include "gui/input.hpp" #include <memory> class Button; class Lobby : public Work { public: - Lobby(std::shared_ptr<Socket>); + /// if quickLogin is set, immediately starts matchmaking + Lobby(std::shared_ptr<Socket>, bool quickLogin); void step(); void draw() const; void handleReceive(json); void OnMessageSent(); void OnLogout(); void OnPlay(); private: void startReceiving(); std::shared_ptr<Socket> socket_; std::string chatText_; std::shared_ptr<Input> input_; std::shared_ptr<Button> logout_; std::shared_ptr<Button> play_; }; diff --git a/src/menu.cpp b/src/menu.cpp index f719c03..7a046b6 100644 --- a/src/menu.cpp +++ b/src/menu.cpp @@ -1,73 +1,73 @@ #include "menu.hpp" #include "engine/paths.hpp" #include "engine/procedure.hpp" #include "engine/fade.hpp" #include "gui/ButtonBox.hpp" #include "optionsmenu.hpp" #include "engine/screen.hpp" #include "Game.hpp" #include "multiplayermenu.hpp" #include <ctime> Menu::Menu() : buttonBox_(new ButtonBox(-450, 0)), normalHighscore_(GameType::NORMAL), fiftyLinesHighscore_(GameType::FIFTYLINES) { buttonBox_->add("Normal", std::bind(&Menu::Normal, this)); buttonBox_->add("50 Lines", std::bind(&Menu::FiftyLines, this)); - buttonBox_->add("Multiplayer", []() { - jngl::setWork(std::make_shared<Fade>(std::make_shared<MultiplayerMenu>())); + buttonBox_->add("Multiplayer", []() { + jngl::setWork(std::make_shared<Fade>(std::make_shared<MultiplayerMenu>(false))); }); // buttonBox_->add("Multiplayer", []() { // jngl::setWork(std::make_shared<Fade>(std::make_shared<SplitScreen>(std::make_shared<GamepadControl>(1)))); // }); buttonBox_->add("Options", std::bind(&Menu::OptionsMenuCallback, this)); buttonBox_->add("Quit", std::bind(&Menu::QuitGame, this)); addWidget(buttonBox_); } void Menu::BlinkHighscore(Data data) { normalHighscore_.Blink(data); fiftyLinesHighscore_.Blink(data); } void Menu::step() { StepWidgets(); } void Menu::draw() const { jngl::setBackgroundColor(0xffffff_rgb); DrawWidgets(); GetScreen().DrawCentered("box", 340, 0); jngl::pushMatrix(); jngl::translate(-20, -400); jngl::setFontSize(50); jngl::setFontColor(0, 0, 0); jngl::print("Highscores Normal", 0, -90); normalHighscore_.draw(); jngl::translate(0, 530); jngl::setFontColor(0, 0, 0); jngl::print("Highscores 50 Lines", 0, -90); fiftyLinesHighscore_.draw(); jngl::popMatrix(); } void Menu::Normal() const { jngl::setWork(std::make_shared<Fade>( std::make_shared<Game>(GameType::NORMAL, static_cast<int>(time(0)), false))); } void Menu::FiftyLines() const { jngl::setWork(std::make_shared<Fade>( std::make_shared<Game>(GameType::FIFTYLINES, static_cast<int>(time(0)), false))); } void Menu::OptionsMenuCallback() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<OptionsMenu>())); } void Menu::QuitGame() const { jngl::quit(); } diff --git a/src/multiplayermenu.cpp b/src/multiplayermenu.cpp index 3880484..efd51b8 100644 --- a/src/multiplayermenu.cpp +++ b/src/multiplayermenu.cpp @@ -1,57 +1,62 @@ #include "multiplayermenu.hpp" #include "engine/screen.hpp" #include "engine/procedure.hpp" #include "engine/fade.hpp" #include "engine/options.hpp" #include "menu.hpp" #include "Login.hpp" #include <jngl.hpp> -MultiplayerMenu::MultiplayerMenu() : name_(new Input(50, -240)), password_(new Input(50, -100)) { +MultiplayerMenu::MultiplayerMenu(const bool quickLogin) +: name_(new Input(50, -240)), password_(new Input(50, -100)), quickLogin(quickLogin) { addWidget(name_); addWidget(password_); login_.reset(new Button("Login", [this]() { OnLogin(); })); addWidget(login_); back_.reset(new Button("Back", [this]() { OnBack(); })); addWidget(back_); back_->setCenter(-350, 280); login_->setCenter(350, 280); password_->SetPassword(true); name_->setText(getOptions().lastLoginName); if (name_->getText() != "") { FocusNext(); } } void MultiplayerMenu::step() { StepWidgets(); - if (jngl::keyPressed(jngl::key::Return)) { + if (jngl::keyPressed(jngl::key::Return) || quickLogin) { OnLogin(); } } void MultiplayerMenu::draw() const { jngl::setFontColor(0, 0, 0); jngl::print("Name:", -500, -240); jngl::print("Password:", -500, -100); DrawWidgets(); } void MultiplayerMenu::OnBack() const { jngl::setWork(std::make_shared<Fade>(std::make_shared<Menu>())); } void MultiplayerMenu::OnLogin() { jngl::setWork( std::make_shared<Login>(std::dynamic_pointer_cast<MultiplayerMenu>(jngl::getWork()))); } std::string MultiplayerMenu::GetName() const { return name_->getText(); } std::string MultiplayerMenu::GetPassword() const { return password_->getText(); } + +bool MultiplayerMenu::getQuickLogin() const { + return quickLogin; +} diff --git a/src/multiplayermenu.hpp b/src/multiplayermenu.hpp index 93d702a..9df2016 100644 --- a/src/multiplayermenu.hpp +++ b/src/multiplayermenu.hpp @@ -1,26 +1,28 @@ #pragma once #include "engine/work.hpp" #include "gui/input.hpp" #include <memory> class Button; class MultiplayerMenu : public Work { public: - MultiplayerMenu(); + MultiplayerMenu(bool quickLogin); void step(); void draw() const; void OnBack() const; void OnLogin(); std::string GetName() const; std::string GetPassword() const; void login(const std::string& name, const std::string& password); + bool getQuickLogin() const; private: std::shared_ptr<Button> back_; std::shared_ptr<Button> login_; std::shared_ptr<Input> name_; std::shared_ptr<Input> password_; + bool quickLogin; };
jhasse/jntetri
1b5623da952834622525becab4afca40cb59e843
Avoid own login message being sent to a user which is about to login
diff --git a/server/Client.cpp b/server/Client.cpp index b0ab0d9..249d34d 100644 --- a/server/Client.cpp +++ b/server/Client.cpp @@ -1,227 +1,227 @@ #include "Client.hpp" #include "Server.hpp" #include "NetworkConstants.hpp" #include <boost/array.hpp> #include <boost/bind.hpp> #include <iostream> #include <nlohmann/json.hpp> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/spdlog.h> #include <thread> using nlohmann::json; Client::Client(Server& server, boost::asio::ip::tcp::socket socket) : socket(std::move(socket)), server(server) { commands["login"] = {false, std::bind(&Client::login, this, std::placeholders::_1, std::placeholders::_2)}; commands["login_anonymous"] = {false, std::bind(&Client::login_anonymous, this, std::placeholders::_1, std::placeholders::_2)}; commands["chat"] = {true, std::bind(&Client::chat, this, std::placeholders::_1, std::placeholders::_2)}; commands["game"] = {true, std::bind(&Client::game, this, std::placeholders::_1, std::placeholders::_2)}; commands["play"] = {true, std::bind(&Client::play, this, std::placeholders::_1, std::placeholders::_2)}; commands["register"] = {false, std::bind(&Client::register_user, this, std::placeholders::_1, std::placeholders::_2)}; commands["quit"] = {true, std::bind(&Client::quit, this, std::placeholders::_1, std::placeholders::_2)}; } void Client::login(boost::asio::yield_context yield, nlohmann::json data) { std::string user = data["name"]; std::string password = data["password"]; spdlog::info("login attempt from '{}' with password of length {}", user, password.size()); switch(server.checkLogin(user, password)) { case LoginState::UserDoesNotExist: errAndDisconnect(yield, "unknown name", "", false); break; case LoginState::PasswordOK: { loginAs(yield, std::move(user)); break; } case LoginState::PasswordWrong: errAndDisconnect(yield, "wrong password", "", false); break; } } void Client::login_anonymous(boost::asio::yield_context yield, nlohmann::json data) { loginAs(yield, server.createAnonymousUser()); } void Client::register_user(boost::asio::yield_context yield, nlohmann::json data) { std::string user = data["name"]; std::string pw = data["password"]; std::string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"; for (char c : user) { if (validChars.find(c) == std::string::npos) { errAndDisconnect(yield, "error", "You're username may only contain latin letters, numbers or hypens."); return; } } if(server.registerUser(user, pw)) { username = user; const auto msg = server.loginAndGetWelcomeMessage(yield, user); okMsg(yield); sendChatLine(yield, msg); } else { errAndDisconnect(yield, "error", "Something went wrong during register!"); } } void Client::chat(boost::asio::yield_context yield, nlohmann::json data) { std::string newChatLine = *username + ": " + data["text"].get<std::string>(); server.addChatLine(yield, newChatLine); log().trace("chat: {}", data["text"]); } void Client::play(boost::asio::yield_context yield, nlohmann::json data) { server.startMatchmaking(yield, shared_from_this()); } void Client::quit(boost::asio::yield_context yield, nlohmann::json) { if (opponent) { opponent->sendOpponentQuit(yield); opponent.reset(); } } void Client::sendStartGame(boost::asio::yield_context yield, const int32_t seed) { socket.send(yield, fmt::format("{{\"type\": \"play\", \"seed\": {} }}", seed)); } void Client::sendChatLine(boost::asio::yield_context yield, std::string line) { if (!isLoggedIn()) { return; } auto j = nlohmann::json { {"type", "chat"}, {"text", line} }; socket.send(yield, j.dump()); } void Client::sendOpponentQuit(boost::asio::yield_context yield) { auto j = nlohmann::json { {"type", "opponentQuit"} }; socket.send(yield, j.dump()); } void Client::game(boost::asio::yield_context yield, nlohmann::json data) { if (!opponent) { spdlog::error("Can't process \"game\" without opponent!"); return; } try { opponent->forward(yield, data["time"].get<uint8_t>(), data["control"].get<uint8_t>()); } catch(boost::system::system_error& e) { log().warn("opponent {} disconnected: {}", opponent->getUsername(), e.what()); opponent.reset(); socket.send(yield, "{\"type\": \"disconnected\"}"); } } void Client::loginAs(boost::asio::yield_context yield, std::string name) { createLogger("client " + name); log().info("logged in, sending \"ok\" ..."); - username = std::move(name); const auto msg = server.loginAndGetWelcomeMessage(yield, *username); + username = std::move(name); okMsg(yield); sendChatLine(yield, msg); } void Client::okMsg(boost::asio::yield_context yield) { socket.send(yield, json{ { "type", "ok" }, { "name", *username } }.dump()); log().trace("sent \"ok\""); } void Client::errAndDisconnect(boost::asio::yield_context yield, std::string type, std::string msg, bool really_disconnect) { auto j = nlohmann::json { {"type", type }}; if(msg != "") { j["msg"] = msg; } socket.send(yield, j.dump()); log().trace("sent {}", j.dump()); if(really_disconnect) { running = false; } } void Client::run(boost::asio::yield_context yield) { uint32_t protocolVersion; std::istringstream is(socket.receive(yield)); is >> protocolVersion; if (protocolVersion != PROTOCOL_VERSION) { log().error("protocol version: ", protocolVersion); errAndDisconnect(yield, "error", "Protocol version mismatch!"); return; } okMsg(yield); while (running) { try { std::string line = socket.receive(yield); auto data = nlohmann::json::parse(line); log().trace("got data {}", data.dump()); auto current_cmd = commands.find(data["type"]); if (current_cmd == commands.end()) { errAndDisconnect(yield, "error", "Unknown command!"); } else if (current_cmd->second.first && !isLoggedIn()) { errAndDisconnect(yield, "error", "You need to be logged in to use this command!"); } else { current_cmd->second.second(yield, data); } } catch (const boost::system::system_error& e) { if (e.code() == boost::asio::error::operation_aborted) { if (kickReason) { errAndDisconnect(yield, "error", *kickReason); break; } } else { throw e; } } } if (username) { std::cout << "Client " << *username << " exiting." << std::endl; } } void Client::setOpponent(std::shared_ptr<Client> opponent) { this->opponent = std::move(opponent); } bool Client::isLoggedIn() const { return username.has_value() && !kickReason; } std::string Client::getUsername() const { return username ? *username : "<invalid>"; } void Client::forward(boost::asio::yield_context yield, uint8_t time, uint8_t command) { nlohmann::json j = { { "type", "game" }, { "control", command }, { "time", time }, }; socket.send(yield, j.dump()); } void Client::createLogger(const std::string& name) { try { logger = spdlog::stdout_color_mt(name, spdlog::color_mode::always); } catch (spdlog::spdlog_ex&) { logger = spdlog::get(name); } } spdlog::logger& Client::log() { if (!logger) { createLogger("unnamed client " + std::to_string(ptrdiff_t(this))); } return *logger; } void Client::kick(std::string reason) { socket.cancel(); kickReason = reason; } diff --git a/server/Server.cpp b/server/Server.cpp index 9af6299..415f3f9 100644 --- a/server/Server.cpp +++ b/server/Server.cpp @@ -1,160 +1,161 @@ #include "Server.hpp" #include "Client.hpp" #include "NetworkConstants.hpp" #include <boost/bind/bind.hpp> #include <iostream> #include <soci/sqlite3/soci-sqlite3.h> #include <spdlog/spdlog.h> #include <optional> using boost::asio::ip::tcp; Server::Server() : socket(context), acceptor(context, tcp::endpoint(tcp::v4(), JNTETRI_PORT)), timer(context, boost::posix_time::seconds(15)), sql(soci::sqlite3, "jntetri.sqlite") { sql << "CREATE TABLE IF NOT EXISTS users (" "username VARCHAR(80) UNIQUE NOT NULL," "password VARCHAR(256) NOT NULL)"; timer.async_wait([this](const auto& e) { printStats(e); }); } Server::~Server() { socket.close(); } void Server::run() { boost::asio::spawn(context, [this](boost::asio::yield_context yield) { doAccept(yield); }); spdlog::info("start"); context.run(); } void Server::doAccept(boost::asio::yield_context yield) { while (true) { boost::asio::ip::tcp::socket socket(context); acceptor.async_accept(socket, yield); auto client = std::make_shared<Client>(*this, std::move(socket)); spdlog::info("new connection"); clients.emplace_back(client); boost::asio::spawn(context, [this, client](boost::asio::yield_context yield) { try { client->run(yield); } catch (std::exception& e) { client->log().error(e.what()); } client->log().info("disconnected"); { std::lock_guard<std::mutex> lock(matchmakingMutex); if (const auto it = std::find(matchmaking.begin(), matchmaking.end(), client); it != matchmaking.end()) { matchmaking.erase(it); } } const auto username = client->getUsername(); clients.erase(std::find(clients.begin(), clients.end(), client)); if (!username.empty()) { addChatLine(yield, fmt::format("{} left.", username)); } }); } } void Server::addChatLine(boost::asio::yield_context yield, std::string line) { chatText += line; for (const auto& client : clients) { if (client->isLoggedIn()) { client->sendChatLine(yield, line); } } } LoginState Server::checkLogin(std::string username, std::string password) { soci::rowset<soci::row> rs = (sql.prepare << "select password from users where username = :username", soci::use(username, "username")); std::optional<std::string> realPassword; for (const auto& row : rs) { assert(!realPassword); realPassword = row.get<std::string>(0); } if (realPassword) { if (*realPassword == password) { // kick all other devices of this user: for (const auto& client : clients) { if (client->isLoggedIn() && client->getUsername() == username) { client->kick("Someone logged in from another device."); } } return LoginState::PasswordOK; } return LoginState::PasswordWrong; } return LoginState::UserDoesNotExist; } bool Server::registerUser(std::string username, std::string password) { try { sql << "insert into users (username, password) values(:username, :password)", soci::use(username), soci::use(password); } catch (soci::soci_error& e) { spdlog::error(e.what()); return false; } return true; } std::string Server::createAnonymousUser() { for (int i = 0; i < 10; ++i) { std::string name = "user" + std::to_string(rand() % 999999); if (registerUser(name, "")) { return name; } // already exists? Maybe we can login without a password: switch (checkLogin(name, "")) { case LoginState::PasswordWrong: break; case LoginState::UserDoesNotExist: assert(false); break; case LoginState::PasswordOK: return name; } } throw std::runtime_error("Couldn't generate a random username!"); } void Server::startMatchmaking(boost::asio::yield_context yield, std::shared_ptr<Client> client) { std::lock_guard<std::mutex> lock(matchmakingMutex); if (matchmaking.empty()) { matchmaking.emplace_back(client); addChatLine(yield, client->getUsername() + " started matchmaking."); } else { for (const auto& existingClient : matchmaking) { if (existingClient == client) { return; // somehow matchmaking was requested twice } } // Found opponent. Let's send p back to both clients so that the game starts. matchmaking.back()->setOpponent(client); client->setOpponent(matchmaking.back()); spdlog::info("matching '{}' and '{}'", matchmaking.back()->getUsername(), client->getUsername()); const int32_t seed = rand(); matchmaking.back()->sendStartGame(yield, seed); client->sendStartGame(yield, seed); matchmaking.pop_back(); } } std::string Server::loginAndGetWelcomeMessage(boost::asio::yield_context yield, const std::string& username) { addChatLine(yield, fmt::format("{} joined.", username)); size_t loggedIn = std::count_if(clients.begin(), clients.end(), - [](const auto& client) { return client->isLoggedIn(); }); + [](const auto& client) { return client->isLoggedIn(); }) + + 1 /* the current user doesn't count yet*/; return fmt::format("{} user{} online.", loggedIn, loggedIn == 1 ? "" : "s"); } void Server::printStats(const boost::system::error_code&) { spdlog::trace("connected clients: {}", clients.size()); timer.expires_from_now(boost::posix_time::seconds(15)); timer.async_wait([this](const auto& e) { printStats(e); }); }